mysql.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package mysql
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "math"
  6. _ "github.com/go-sql-driver/mysql"
  7. "github.com/jinzhu/gorm"
  8. "github.com/jinzhu/gorm/callbacks"
  9. "github.com/jinzhu/gorm/migrator"
  10. "github.com/jinzhu/gorm/schema"
  11. )
  12. type Dialector struct {
  13. DSN string
  14. }
  15. func Open(dsn string) gorm.Dialector {
  16. return &Dialector{DSN: dsn}
  17. }
  18. func (dialector Dialector) Initialize(db *gorm.DB) (err error) {
  19. // register callbacks
  20. callbacks.RegisterDefaultCallbacks(db)
  21. db.DB, err = sql.Open("sqlite3", dialector.DSN)
  22. return nil
  23. }
  24. func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator {
  25. return Migrator{migrator.Migrator{Config: migrator.Config{
  26. DB: db,
  27. Dialector: dialector,
  28. }}}
  29. }
  30. func (dialector Dialector) BindVar(stmt *gorm.Statement, v interface{}) string {
  31. return "?"
  32. }
  33. func (dialector Dialector) QuoteChars() [2]byte {
  34. return [2]byte{'`', '`'} // `name`
  35. }
  36. func (dialector Dialector) DataTypeOf(field *schema.Field) string {
  37. switch field.DataType {
  38. case schema.Bool:
  39. return "boolean"
  40. case schema.Int, schema.Uint:
  41. sqlType := "int"
  42. switch {
  43. case field.Size <= 8:
  44. sqlType = "tinyint"
  45. case field.Size <= 16:
  46. sqlType = "smallint"
  47. case field.Size <= 32:
  48. sqlType = "int"
  49. default:
  50. sqlType = "bigint"
  51. }
  52. if field.DataType == schema.Uint {
  53. sqlType += " unsigned"
  54. }
  55. if field.AutoIncrement {
  56. sqlType += " AUTO_INCREMENT"
  57. }
  58. return sqlType
  59. case schema.Float:
  60. if field.Size <= 32 {
  61. return "float"
  62. }
  63. return "double"
  64. case schema.String:
  65. size := field.Size
  66. if size >= 65536 && size <= int(math.Pow(2, 24)) {
  67. return "mediumtext"
  68. } else if size > int(math.Pow(2, 24)) || size < 0 {
  69. return "longtext"
  70. }
  71. return fmt.Sprintf("varchar(%d)", size)
  72. case schema.Time:
  73. precision := ""
  74. if field.Precision > 0 {
  75. precision = fmt.Sprintf("(%d)", field.Precision)
  76. }
  77. if field.NotNull || field.PrimaryKey {
  78. return "datetime" + precision
  79. }
  80. return "datetime" + precision + " NULL"
  81. case schema.Bytes:
  82. if field.Size > 0 && field.Size < 65536 {
  83. return fmt.Sprintf("varbinary(%d)", field.Size)
  84. }
  85. if field.Size >= 65536 && field.Size <= int(math.Pow(2, 24)) {
  86. return "mediumblob"
  87. }
  88. return "longblob"
  89. }
  90. return ""
  91. }