gdb_driver_mysql.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. package gdb
  7. import (
  8. "context"
  9. "database/sql"
  10. "fmt"
  11. "github.com/gogf/gf/errors/gcode"
  12. "github.com/gogf/gf/errors/gerror"
  13. "github.com/gogf/gf/internal/intlog"
  14. "github.com/gogf/gf/text/gregex"
  15. "github.com/gogf/gf/text/gstr"
  16. "net/url"
  17. _ "github.com/go-sql-driver/mysql"
  18. )
  19. // DriverMysql is the driver for mysql database.
  20. type DriverMysql struct {
  21. *Core
  22. }
  23. // New creates and returns a database object for mysql.
  24. // It implements the interface of gdb.Driver for extra database driver installation.
  25. func (d *DriverMysql) New(core *Core, node *ConfigNode) (DB, error) {
  26. return &DriverMysql{
  27. Core: core,
  28. }, nil
  29. }
  30. // Open creates and returns an underlying sql.DB object for mysql.
  31. // Note that it converts time.Time argument to local timezone in default.
  32. func (d *DriverMysql) Open(config *ConfigNode) (*sql.DB, error) {
  33. var source string
  34. if config.Link != "" {
  35. source = config.Link
  36. // Custom changing the schema in runtime.
  37. if config.Name != "" {
  38. source, _ = gregex.ReplaceString(`/([\w\.\-]+)+`, "/"+config.Name, source)
  39. }
  40. } else {
  41. source = fmt.Sprintf(
  42. "%s:%s@tcp(%s:%s)/%s?charset=%s",
  43. config.User, config.Pass, config.Host, config.Port, config.Name, config.Charset,
  44. )
  45. if config.Timezone != "" {
  46. source = fmt.Sprintf("%s&loc=%s", source, url.QueryEscape(config.Timezone))
  47. }
  48. }
  49. intlog.Printf(d.GetCtx(), "Open: %s", source)
  50. if db, err := sql.Open("mysql", source); err == nil {
  51. return db, nil
  52. } else {
  53. return nil, err
  54. }
  55. }
  56. // FilteredLink retrieves and returns filtered `linkInfo` that can be using for
  57. // logging or tracing purpose.
  58. func (d *DriverMysql) FilteredLink() string {
  59. linkInfo := d.GetConfig().Link
  60. if linkInfo == "" {
  61. return ""
  62. }
  63. s, _ := gregex.ReplaceString(
  64. `(.+?):(.+)@tcp(.+)`,
  65. `$1:xxx@tcp$3`,
  66. linkInfo,
  67. )
  68. return s
  69. }
  70. // GetChars returns the security char for this type of database.
  71. func (d *DriverMysql) GetChars() (charLeft string, charRight string) {
  72. return "`", "`"
  73. }
  74. // DoCommit handles the sql before posts it to database.
  75. func (d *DriverMysql) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) {
  76. return d.Core.DoCommit(ctx, link, sql, args)
  77. }
  78. // Tables retrieves and returns the tables of current schema.
  79. // It's mainly used in cli tool chain for automatically generating the models.
  80. func (d *DriverMysql) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
  81. var result Result
  82. link, err := d.SlaveLink(schema...)
  83. if err != nil {
  84. return nil, err
  85. }
  86. result, err = d.DoGetAll(ctx, link, `SHOW TABLES`)
  87. if err != nil {
  88. return
  89. }
  90. for _, m := range result {
  91. for _, v := range m {
  92. tables = append(tables, v.String())
  93. }
  94. }
  95. return
  96. }
  97. // TableFields retrieves and returns the fields information of specified table of current
  98. // schema.
  99. //
  100. // The parameter `link` is optional, if given nil it automatically retrieves a raw sql connection
  101. // as its link to proceed necessary sql query.
  102. //
  103. // Note that it returns a map containing the field name and its corresponding fields.
  104. // As a map is unsorted, the TableField struct has a "Index" field marks its sequence in
  105. // the fields.
  106. //
  107. // It's using cache feature to enhance the performance, which is never expired util the
  108. // process restarts.
  109. func (d *DriverMysql) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error) {
  110. charL, charR := d.GetChars()
  111. table = gstr.Trim(table, charL+charR)
  112. if gstr.Contains(table, " ") {
  113. return nil, gerror.NewCode(gcode.CodeInvalidParameter, "function TableFields supports only single table operations")
  114. }
  115. useSchema := d.schema.Val()
  116. if len(schema) > 0 && schema[0] != "" {
  117. useSchema = schema[0]
  118. }
  119. tableFieldsCacheKey := fmt.Sprintf(
  120. `mysql_table_fields_%s_%s@group:%s`,
  121. table, useSchema, d.GetGroup(),
  122. )
  123. v := tableFieldsMap.GetOrSetFuncLock(tableFieldsCacheKey, func() interface{} {
  124. var (
  125. result Result
  126. link, err = d.SlaveLink(useSchema)
  127. )
  128. if err != nil {
  129. return nil
  130. }
  131. result, err = d.DoGetAll(ctx, link, fmt.Sprintf(`SHOW FULL COLUMNS FROM %s`, d.QuoteWord(table)))
  132. if err != nil {
  133. return nil
  134. }
  135. fields = make(map[string]*TableField)
  136. for i, m := range result {
  137. fields[m["Field"].String()] = &TableField{
  138. Index: i,
  139. Name: m["Field"].String(),
  140. Type: m["Type"].String(),
  141. Null: m["Null"].Bool(),
  142. Key: m["Key"].String(),
  143. Default: m["Default"].Val(),
  144. Extra: m["Extra"].String(),
  145. Comment: m["Comment"].String(),
  146. }
  147. }
  148. return fields
  149. })
  150. if v != nil {
  151. fields = v.(map[string]*TableField)
  152. }
  153. return
  154. }