|
| 1 | +// Copyright 2018 The Gitea Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a MIT-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package migrations |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + |
| 10 | + "code.gitea.io/gitea/modules/log" |
| 11 | + "code.gitea.io/gitea/modules/setting" |
| 12 | + |
| 13 | + "github.com/go-sql-driver/mysql" |
| 14 | + "github.com/go-xorm/xorm" |
| 15 | +) |
| 16 | + |
| 17 | +func mysqlColumnsToUTF8MB4(x *xorm.Engine) (err error) { |
| 18 | + if !setting.UseMySQL { |
| 19 | + log.Info("Nothing to do") |
| 20 | + return nil |
| 21 | + } |
| 22 | + |
| 23 | + const maxvc = 191 |
| 24 | + migrationSuccess := true |
| 25 | + |
| 26 | + tables, err := x.DBMetas() |
| 27 | + if err != nil { |
| 28 | + return fmt.Errorf("cannot get tables: %v", err) |
| 29 | + } |
| 30 | + for _, table := range tables { |
| 31 | + readyForConversion := true |
| 32 | + for _, col := range table.Columns() { |
| 33 | + if !(len(col.Indexes) > 0 || col.IsPrimaryKey) { |
| 34 | + continue |
| 35 | + } |
| 36 | + if !(col.SQLType.Name == "VARCHAR" && col.Length > maxvc) { |
| 37 | + continue |
| 38 | + } |
| 39 | + log.Info("reducing column %s.%s from %d to %d bytes", table.Name, col.Name, col.Length, maxvc) |
| 40 | + sqlstmt := fmt.Sprintf("alter table `%s` change column `%s` `%s` varchar(%d)", table.Name, col.Name, col.Name, maxvc) |
| 41 | + if _, err := x.Exec(sqlstmt); err != nil { |
| 42 | + if e, ok := err.(*mysql.MySQLError); ok { |
| 43 | + if e.Number == 1265 || e.Number == 1406 { |
| 44 | + log.Warn("failed. Please cut all data of this column down to a maximum of %d bytes", maxvc) |
| 45 | + } else { |
| 46 | + log.Warn("failed with %v", err) |
| 47 | + } |
| 48 | + readyForConversion = false |
| 49 | + migrationSuccess = false |
| 50 | + continue |
| 51 | + } |
| 52 | + return fmt.Errorf("something went horribly wrong: %v", err) |
| 53 | + } |
| 54 | + } |
| 55 | + if readyForConversion { |
| 56 | + log.Info("%s: converting table to utf8mb4", table.Name) |
| 57 | + if _, err := x.Exec("alter table `" + table.Name + "` convert to character set utf8mb4"); err != nil { |
| 58 | + log.Warn("conversion of %s failed: %v", table.Name, err) |
| 59 | + migrationSuccess = false |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + if !migrationSuccess { |
| 64 | + return fmt.Errorf("conversion of some of the tables failed. Please check the logs and re-run gitea") |
| 65 | + } |
| 66 | + return nil |
| 67 | +} |
0 commit comments