Skip to content

Commit 11e0a4b

Browse files
饺子wjmattheis
authored andcommitted
Fix blob inconsistency in mysql (#196)
By default gorm uses the type `varbinary(255)` for []byte in database models. 255 characters isn't enough for a plugin config therefore we use longblob instead.
1 parent 05a1aa2 commit 11e0a4b

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

database/database.go

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,14 @@ func New(dialect, connection, defaultUser, defaultPass string, strength int, cre
3535
db.DB().SetMaxOpenConns(1)
3636
}
3737

38-
db.AutoMigrate(new(model.User), new(model.Application), new(model.Message), new(model.Client), new(model.PluginConf))
38+
if err := db.AutoMigrate(new(model.User), new(model.Application), new(model.Message), new(model.Client), new(model.PluginConf)).Error; err != nil {
39+
return nil, err
40+
}
41+
42+
if err := prepareBlobColumn(dialect, db); err != nil {
43+
return nil, err
44+
}
45+
3946
userCount := 0
4047
db.Find(new(model.User)).Count(&userCount)
4148
if createDefaultUserIfNotExist && userCount == 0 {
@@ -45,6 +52,31 @@ func New(dialect, connection, defaultUser, defaultPass string, strength int, cre
4552
return &GormDatabase{DB: db}, nil
4653
}
4754

55+
func prepareBlobColumn(dialect string, db *gorm.DB) error {
56+
blobType := ""
57+
switch dialect {
58+
case "mysql":
59+
blobType = "longblob"
60+
case "postgres":
61+
blobType = "bytea"
62+
}
63+
if blobType != "" {
64+
for _, target := range []struct {
65+
Table interface{}
66+
Column string
67+
}{
68+
{model.Message{}, "extras"},
69+
{model.PluginConf{}, "config"},
70+
{model.PluginConf{}, "storage"},
71+
} {
72+
if err := db.Model(target.Table).ModifyColumn(target.Column, blobType).Error; err != nil {
73+
return err
74+
}
75+
}
76+
}
77+
return nil
78+
}
79+
4880
func createDirectoryIfSqlite(dialect string, connection string) {
4981
if dialect == "sqlite3" {
5082
if _, err := os.Stat(filepath.Dir(connection)); os.IsNotExist(err) {

0 commit comments

Comments
 (0)