mysql.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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{DB: db}}}
  26. }
  27. func (dialector Dialector) BindVar(stmt *gorm.Statement, v interface{}) string {
  28. return "?"
  29. }
  30. func (dialector Dialector) QuoteChars() [2]byte {
  31. return [2]byte{'`', '`'} // `name`
  32. }
  33. func (dialector Dialector) DataTypeOf(field *schema.Field) string {
  34. switch field.DataType {
  35. case schema.Bool:
  36. return "boolean"
  37. case schema.Int, schema.Uint:
  38. sqlType := "int"
  39. switch {
  40. case field.Size <= 8:
  41. sqlType = "tinyint"
  42. case field.Size <= 16:
  43. sqlType = "smallint"
  44. case field.Size <= 32:
  45. sqlType = "int"
  46. default:
  47. sqlType = "bigint"
  48. }
  49. if field.DataType == schema.Uint {
  50. sqlType += " unsigned"
  51. }
  52. if field.AutoIncrement {
  53. sqlType += " AUTO_INCREMENT"
  54. }
  55. return sqlType
  56. case schema.Float:
  57. if field.Size <= 32 {
  58. return "float"
  59. }
  60. return "double"
  61. case schema.String:
  62. size := field.Size
  63. if size >= 65536 && size <= int(math.Pow(2, 24)) {
  64. return "mediumtext"
  65. } else if size > int(math.Pow(2, 24)) || size < 0 {
  66. return "longtext"
  67. }
  68. return fmt.Sprintf("varchar(%d)", size)
  69. case schema.Time:
  70. precision := ""
  71. if field.Precision > 0 {
  72. precision = fmt.Sprintf("(%d)", field.Precision)
  73. }
  74. if field.NotNull || field.PrimaryKey {
  75. return "datetime" + precision
  76. }
  77. return "datetime" + precision + " NULL"
  78. case schema.Bytes:
  79. if field.Size > 0 && field.Size < 65536 {
  80. return fmt.Sprintf("varbinary(%d)", field.Size)
  81. }
  82. if field.Size >= 65536 && field.Size <= int(math.Pow(2, 24)) {
  83. return "mediumblob"
  84. }
  85. return "longblob"
  86. }
  87. return ""
  88. }