5
5
package migrations
6
6
7
7
import (
8
+ "context"
9
+
10
+ "code.gitea.io/gitea/modules/log"
8
11
"xorm.io/xorm"
9
12
"xorm.io/xorm/schemas"
10
13
)
11
14
15
+ func modifyColumn (x * xorm.Engine , tableName string , col * schemas.Column ) error {
16
+ var indexes map [string ]* schemas.Index
17
+ var err error
18
+ // MSSQL have to remove index at first, otherwise alter column will fail
19
+ // ref. https://sqlzealots.com/2018/05/09/error-message-the-index-is-dependent-on-column-alter-table-alter-column-failed-because-one-or-more-objects-access-this-column/
20
+ if x .Dialect ().URI ().DBType == schemas .MSSQL {
21
+ indexes , err = x .Dialect ().GetIndexes (x .DB (), context .Background (), tableName )
22
+ if err != nil {
23
+ return err
24
+ }
25
+
26
+ for _ , index := range indexes {
27
+ _ , err = x .Exec (x .Dialect ().DropIndexSQL (tableName , index ))
28
+ if err != nil {
29
+ return err
30
+ }
31
+ }
32
+ }
33
+
34
+ defer func () {
35
+ for _ , index := range indexes {
36
+ _ , err = x .Exec (x .Dialect ().CreateIndexSQL (tableName , index ))
37
+ if err != nil {
38
+ log .Error ("Create index %s on table %s failed: %v" , index .Name , tableName , err )
39
+ }
40
+ }
41
+ }()
42
+
43
+ alterSQL := x .Dialect ().ModifyColumnSQL (tableName , col )
44
+ if _ , err := x .Exec (alterSQL ); err != nil {
45
+ return err
46
+ }
47
+ return nil
48
+ }
49
+
12
50
func convertHookTaskTypeToVarcharAndTrim (x * xorm.Engine ) error {
13
51
dbType := x .Dialect ().URI ().DBType
14
52
if dbType == schemas .SQLITE { // For SQLITE, varchar or char will always be represented as TEXT
@@ -18,16 +56,15 @@ func convertHookTaskTypeToVarcharAndTrim(x *xorm.Engine) error {
18
56
type HookTask struct {
19
57
Typ string `xorm:"VARCHAR(16) index"`
20
58
}
21
- alterSQL := x . Dialect (). ModifyColumnSQL ( "hook_task" , & schemas. Column {
22
- Name : "typ" ,
23
- TableName : "hook_task " ,
59
+
60
+ if err := modifyColumn ( x , "hook_task" , & schemas. Column {
61
+ Name : "typ " ,
24
62
SQLType : schemas.SQLType {
25
63
Name : "VARCHAR" ,
26
64
},
27
65
Length : 16 ,
28
66
Nullable : true , // To keep compatible as nullable
29
- })
30
- if _ , err := x .Exec (alterSQL ); err != nil {
67
+ }); err != nil {
31
68
return err
32
69
}
33
70
@@ -45,16 +82,14 @@ func convertHookTaskTypeToVarcharAndTrim(x *xorm.Engine) error {
45
82
Type string `xorm:"VARCHAR(16) index"`
46
83
}
47
84
48
- alterSQL = x .Dialect ().ModifyColumnSQL ("webhook" , & schemas.Column {
49
- Name : "type" ,
50
- TableName : "webhook" ,
85
+ if err := modifyColumn (x , "webhook" , & schemas.Column {
86
+ Name : "type" ,
51
87
SQLType : schemas.SQLType {
52
88
Name : "VARCHAR" ,
53
89
},
54
90
Length : 16 ,
55
91
Nullable : true , // To keep compatible as nullable
56
- })
57
- if _ , err := x .Exec (alterSQL ); err != nil {
92
+ }); err != nil {
58
93
return err
59
94
}
60
95
0 commit comments