mysql_dialect.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package migrator
  2. import (
  3. "strconv"
  4. "strings"
  5. )
  6. type Mysql struct {
  7. BaseDialect
  8. }
  9. func NewMysqlDialect() *Mysql {
  10. d := Mysql{}
  11. d.BaseDialect.dialect = &d
  12. d.BaseDialect.driverName = MYSQL
  13. return &d
  14. }
  15. func (db *Mysql) SupportEngine() bool {
  16. return true
  17. }
  18. func (db *Mysql) Quote(name string) string {
  19. return "`" + name + "`"
  20. }
  21. func (db *Mysql) QuoteStr() string {
  22. return "`"
  23. }
  24. func (db *Mysql) AutoIncrStr() string {
  25. return "AUTO_INCREMENT"
  26. }
  27. func (db *Mysql) BooleanStr(value bool) string {
  28. if value {
  29. return "1"
  30. }
  31. return "0"
  32. }
  33. func (db *Mysql) SqlType(c *Column) string {
  34. var res string
  35. switch c.Type {
  36. case DB_Bool:
  37. res = DB_TinyInt
  38. c.Length = 1
  39. case DB_Serial:
  40. c.IsAutoIncrement = true
  41. c.IsPrimaryKey = true
  42. c.Nullable = false
  43. res = DB_Int
  44. case DB_BigSerial:
  45. c.IsAutoIncrement = true
  46. c.IsPrimaryKey = true
  47. c.Nullable = false
  48. res = DB_BigInt
  49. case DB_Bytea:
  50. res = DB_Blob
  51. case DB_TimeStampz:
  52. res = DB_Char
  53. c.Length = 64
  54. case DB_NVarchar:
  55. res = DB_Varchar
  56. default:
  57. res = c.Type
  58. }
  59. var hasLen1 = (c.Length > 0)
  60. var hasLen2 = (c.Length2 > 0)
  61. if res == DB_BigInt && !hasLen1 && !hasLen2 {
  62. c.Length = 20
  63. hasLen1 = true
  64. }
  65. if hasLen2 {
  66. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  67. } else if hasLen1 {
  68. res += "(" + strconv.Itoa(c.Length) + ")"
  69. }
  70. switch c.Type {
  71. case DB_Char, DB_Varchar, DB_NVarchar, DB_TinyText, DB_Text, DB_MediumText, DB_LongText:
  72. res += " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
  73. }
  74. return res
  75. }
  76. func (db *Mysql) TableCheckSql(tableName string) (string, []interface{}) {
  77. args := []interface{}{"grafana", tableName}
  78. sql := "SELECT `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? and `TABLE_NAME`=?"
  79. return sql, args
  80. }
  81. func (db *Mysql) UpdateTableSql(tableName string, columns []*Column) string {
  82. var statements = []string{}
  83. statements = append(statements, "DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
  84. for _, col := range columns {
  85. statements = append(statements, "MODIFY "+col.StringNoPk(db))
  86. }
  87. return "ALTER TABLE " + db.Quote(tableName) + " " + strings.Join(statements, ", ") + ";"
  88. }