dialect_mysql.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. package gorm
  2. import (
  3. "crypto/sha1"
  4. "database/sql"
  5. "fmt"
  6. "reflect"
  7. "regexp"
  8. "strings"
  9. "time"
  10. "unicode/utf8"
  11. )
  12. var mysqlIndexRegex = regexp.MustCompile(`^(.+)\((\d+)\)$`)
  13. type mysql struct {
  14. commonDialect
  15. }
  16. func init() {
  17. RegisterDialect("mysql", &mysql{})
  18. }
  19. func (mysql) GetName() string {
  20. return "mysql"
  21. }
  22. func (mysql) Quote(key string) string {
  23. return fmt.Sprintf("`%s`", key)
  24. }
  25. // Get Data Type for MySQL Dialect
  26. func (s *mysql) DataTypeOf(field *StructField) string {
  27. var dataValue, sqlType, size, additionalType = ParseFieldStructForDialect(field, s)
  28. // MySQL allows only one auto increment column per table, and it must
  29. // be a KEY column.
  30. if _, ok := field.TagSettingsGet("AUTO_INCREMENT"); ok {
  31. if _, ok = field.TagSettingsGet("INDEX"); !ok && !field.IsPrimaryKey {
  32. field.TagSettingsDelete("AUTO_INCREMENT")
  33. }
  34. }
  35. if sqlType == "" {
  36. switch dataValue.Kind() {
  37. case reflect.Bool:
  38. sqlType = "boolean"
  39. case reflect.Int8:
  40. if s.fieldCanAutoIncrement(field) {
  41. field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT")
  42. sqlType = "tinyint AUTO_INCREMENT"
  43. } else {
  44. sqlType = "tinyint"
  45. }
  46. case reflect.Int, reflect.Int16, reflect.Int32:
  47. if s.fieldCanAutoIncrement(field) {
  48. field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT")
  49. sqlType = "int AUTO_INCREMENT"
  50. } else {
  51. sqlType = "int"
  52. }
  53. case reflect.Uint8:
  54. if s.fieldCanAutoIncrement(field) {
  55. field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT")
  56. sqlType = "tinyint unsigned AUTO_INCREMENT"
  57. } else {
  58. sqlType = "tinyint unsigned"
  59. }
  60. case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uintptr:
  61. if s.fieldCanAutoIncrement(field) {
  62. field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT")
  63. sqlType = "int unsigned AUTO_INCREMENT"
  64. } else {
  65. sqlType = "int unsigned"
  66. }
  67. case reflect.Int64:
  68. if s.fieldCanAutoIncrement(field) {
  69. field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT")
  70. sqlType = "bigint AUTO_INCREMENT"
  71. } else {
  72. sqlType = "bigint"
  73. }
  74. case reflect.Uint64:
  75. if s.fieldCanAutoIncrement(field) {
  76. field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT")
  77. sqlType = "bigint unsigned AUTO_INCREMENT"
  78. } else {
  79. sqlType = "bigint unsigned"
  80. }
  81. case reflect.Float32, reflect.Float64:
  82. sqlType = "double"
  83. case reflect.String:
  84. if size > 0 && size < 65532 {
  85. sqlType = fmt.Sprintf("varchar(%d)", size)
  86. } else {
  87. sqlType = "longtext"
  88. }
  89. case reflect.Struct:
  90. if _, ok := dataValue.Interface().(time.Time); ok {
  91. precision := ""
  92. if p, ok := field.TagSettingsGet("PRECISION"); ok {
  93. precision = fmt.Sprintf("(%s)", p)
  94. }
  95. if _, ok := field.TagSettings["NOT NULL"]; ok || field.IsPrimaryKey {
  96. sqlType = fmt.Sprintf("DATETIME%v", precision)
  97. } else {
  98. sqlType = fmt.Sprintf("DATETIME%v NULL", precision)
  99. }
  100. }
  101. default:
  102. if IsByteArrayOrSlice(dataValue) {
  103. if size > 0 && size < 65532 {
  104. sqlType = fmt.Sprintf("varbinary(%d)", size)
  105. } else {
  106. sqlType = "longblob"
  107. }
  108. }
  109. }
  110. }
  111. if sqlType == "" {
  112. panic(fmt.Sprintf("invalid sql type %s (%s) in field %s for mysql", dataValue.Type().Name(), dataValue.Kind().String(), field.Name))
  113. }
  114. if strings.TrimSpace(additionalType) == "" {
  115. return sqlType
  116. }
  117. return fmt.Sprintf("%v %v", sqlType, additionalType)
  118. }
  119. func (s mysql) RemoveIndex(tableName string, indexName string) error {
  120. _, err := s.db.Exec(fmt.Sprintf("DROP INDEX %v ON %v", indexName, s.Quote(tableName)))
  121. return err
  122. }
  123. func (s mysql) ModifyColumn(tableName string, columnName string, typ string) error {
  124. _, err := s.db.Exec(fmt.Sprintf("ALTER TABLE %v MODIFY COLUMN %v %v", tableName, columnName, typ))
  125. return err
  126. }
  127. func (s mysql) LimitAndOffsetSQL(limit, offset interface{}) (sql string, err error) {
  128. if limit != nil {
  129. parsedLimit, err := s.parseInt(limit)
  130. if err != nil {
  131. return "", err
  132. }
  133. if parsedLimit >= 0 {
  134. sql += fmt.Sprintf(" LIMIT %d", parsedLimit)
  135. if offset != nil {
  136. parsedOffset, err := s.parseInt(offset)
  137. if err != nil {
  138. return "", err
  139. }
  140. if parsedOffset >= 0 {
  141. sql += fmt.Sprintf(" OFFSET %d", parsedOffset)
  142. }
  143. }
  144. }
  145. }
  146. return
  147. }
  148. func (s mysql) HasForeignKey(tableName string, foreignKeyName string) bool {
  149. var count int
  150. currentDatabase, tableName := currentDatabaseAndTable(&s, tableName)
  151. s.db.QueryRow("SELECT count(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA=? AND TABLE_NAME=? AND CONSTRAINT_NAME=? AND CONSTRAINT_TYPE='FOREIGN KEY'", currentDatabase, tableName, foreignKeyName).Scan(&count)
  152. return count > 0
  153. }
  154. func (s mysql) HasTable(tableName string) bool {
  155. currentDatabase, tableName := currentDatabaseAndTable(&s, tableName)
  156. var name string
  157. // allow mysql database name with '-' character
  158. if err := s.db.QueryRow(fmt.Sprintf("SHOW TABLES FROM `%s` WHERE `Tables_in_%s` = ?", currentDatabase, currentDatabase), tableName).Scan(&name); err != nil {
  159. if err == sql.ErrNoRows {
  160. return false
  161. }
  162. panic(err)
  163. } else {
  164. return true
  165. }
  166. }
  167. func (s mysql) HasIndex(tableName string, indexName string) bool {
  168. currentDatabase, tableName := currentDatabaseAndTable(&s, tableName)
  169. if rows, err := s.db.Query(fmt.Sprintf("SHOW INDEXES FROM `%s` FROM `%s` WHERE Key_name = ?", tableName, currentDatabase), indexName); err != nil {
  170. panic(err)
  171. } else {
  172. defer rows.Close()
  173. return rows.Next()
  174. }
  175. }
  176. func (s mysql) HasColumn(tableName string, columnName string) bool {
  177. currentDatabase, tableName := currentDatabaseAndTable(&s, tableName)
  178. if rows, err := s.db.Query(fmt.Sprintf("SHOW COLUMNS FROM `%s` FROM `%s` WHERE Field = ?", tableName, currentDatabase), columnName); err != nil {
  179. panic(err)
  180. } else {
  181. defer rows.Close()
  182. return rows.Next()
  183. }
  184. }
  185. func (s mysql) CurrentDatabase() (name string) {
  186. s.db.QueryRow("SELECT DATABASE()").Scan(&name)
  187. return
  188. }
  189. func (mysql) SelectFromDummyTable() string {
  190. return "FROM DUAL"
  191. }
  192. func (s mysql) BuildKeyName(kind, tableName string, fields ...string) string {
  193. keyName := s.commonDialect.BuildKeyName(kind, tableName, fields...)
  194. if utf8.RuneCountInString(keyName) <= 64 {
  195. return keyName
  196. }
  197. h := sha1.New()
  198. h.Write([]byte(keyName))
  199. bs := h.Sum(nil)
  200. // sha1 is 40 characters, keep first 24 characters of destination
  201. destRunes := []rune(keyNameRegex.ReplaceAllString(fields[0], "_"))
  202. if len(destRunes) > 24 {
  203. destRunes = destRunes[:24]
  204. }
  205. return fmt.Sprintf("%s%x", string(destRunes), bs)
  206. }
  207. // NormalizeIndexAndColumn returns index name and column name for specify an index prefix length if needed
  208. func (mysql) NormalizeIndexAndColumn(indexName, columnName string) (string, string) {
  209. submatch := mysqlIndexRegex.FindStringSubmatch(indexName)
  210. if len(submatch) != 3 {
  211. return indexName, columnName
  212. }
  213. indexName = submatch[1]
  214. columnName = fmt.Sprintf("%s(%s)", columnName, submatch[2])
  215. return indexName, columnName
  216. }
  217. func (mysql) DefaultValueStr() string {
  218. return "VALUES()"
  219. }