Skip to content

Commit ecae628

Browse files
GiteaBotwolfogre
andauthored
Refactor setting.Database.UseXXX to methods (#23354) (#23356)
Backport #23354 Replace #23350. Refactor `setting.Database.UseMySQL` to `setting.Database.Type.IsMySQL()`. To avoid mismatching between `Type` and `UseXXX`. This refactor can fix the bug mentioned in #23350, so it should be backported. Co-authored-by: Jason Song <i@wolfogre.com>
1 parent e8e871b commit ecae628

File tree

36 files changed

+103
-96
lines changed

36 files changed

+103
-96
lines changed

Diff for: cmd/convert.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ func runConvert(ctx *cli.Context) error {
3535
log.Info("Log path: %s", setting.Log.RootPath)
3636
log.Info("Configuration file: %s", setting.CustomConf)
3737

38-
if !setting.Database.UseMySQL {
38+
if !setting.Database.Type.IsMySQL() {
3939
fmt.Println("This command can only be used with a MySQL database")
4040
return nil
4141
}

Diff for: cmd/dump.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,7 @@ func runDump(ctx *cli.Context) error {
279279
}()
280280

281281
targetDBType := ctx.String("database")
282-
if len(targetDBType) > 0 && targetDBType != setting.Database.Type {
282+
if len(targetDBType) > 0 && targetDBType != setting.Database.Type.String() {
283283
log.Info("Dumping database %s => %s...", setting.Database.Type, targetDBType)
284284
} else {
285285
log.Info("Dumping database...")

Diff for: models/activities/action.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ func (a *Action) TableIndices() []*schemas.Index {
9999
actUserIndex.AddColumn("act_user_id", "repo_id", "created_unix", "user_id", "is_deleted")
100100

101101
indices := []*schemas.Index{actUserIndex, repoIndex}
102-
if setting.Database.UsePostgreSQL {
102+
if setting.Database.Type.IsPostgreSQL() {
103103
cudIndex := schemas.NewIndex("c_u_d", schemas.IndexType)
104104
cudIndex.AddColumn("created_unix", "user_id", "is_deleted")
105105
indices = append(indices, cudIndex)
@@ -640,15 +640,15 @@ func DeleteIssueActions(ctx context.Context, repoID, issueID int64) error {
640640

641641
// CountActionCreatedUnixString count actions where created_unix is an empty string
642642
func CountActionCreatedUnixString(ctx context.Context) (int64, error) {
643-
if setting.Database.UseSQLite3 {
643+
if setting.Database.Type.IsSQLite3() {
644644
return db.GetEngine(ctx).Where(`created_unix = ""`).Count(new(Action))
645645
}
646646
return 0, nil
647647
}
648648

649649
// FixActionCreatedUnixString set created_unix to zero if it is an empty string
650650
func FixActionCreatedUnixString(ctx context.Context) (int64, error) {
651-
if setting.Database.UseSQLite3 {
651+
if setting.Database.Type.IsSQLite3() {
652652
res, err := db.GetEngine(ctx).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ""`)
653653
if err != nil {
654654
return 0, err

Diff for: models/activities/action_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ func TestGetFeedsCorrupted(t *testing.T) {
234234
}
235235

236236
func TestConsistencyUpdateAction(t *testing.T) {
237-
if !setting.Database.UseSQLite3 {
237+
if !setting.Database.Type.IsSQLite3() {
238238
t.Skip("Test is only for SQLite database.")
239239
}
240240
assert.NoError(t, unittest.PrepareTestDatabase())

Diff for: models/activities/user_heatmap.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ func getUserHeatmapData(user *user_model.User, team *organization.Team, doer *us
3939
groupBy := "created_unix / 900 * 900"
4040
groupByName := "timestamp" // We need this extra case because mssql doesn't allow grouping by alias
4141
switch {
42-
case setting.Database.UseMySQL:
42+
case setting.Database.Type.IsMySQL():
4343
groupBy = "created_unix DIV 900 * 900"
44-
case setting.Database.UseMSSQL:
44+
case setting.Database.Type.IsMSSQL():
4545
groupByName = groupBy
4646
}
4747

Diff for: models/db/common.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
// BuildCaseInsensitiveLike returns a condition to check if the given value is like the given key case-insensitively.
1616
// Handles especially SQLite correctly as UPPER there only transforms ASCII letters.
1717
func BuildCaseInsensitiveLike(key, value string) builder.Cond {
18-
if setting.Database.UseSQLite3 {
18+
if setting.Database.Type.IsSQLite3() {
1919
return builder.Like{"UPPER(" + key + ")", util.ToUpperASCII(value)}
2020
}
2121
return builder.Like{"UPPER(" + key + ")", strings.ToUpper(value)}

Diff for: models/db/engine.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -100,12 +100,12 @@ func newXORMEngine() (*xorm.Engine, error) {
100100

101101
var engine *xorm.Engine
102102

103-
if setting.Database.UsePostgreSQL && len(setting.Database.Schema) > 0 {
103+
if setting.Database.Type.IsPostgreSQL() && len(setting.Database.Schema) > 0 {
104104
// OK whilst we sort out our schema issues - create a schema aware postgres
105105
registerPostgresSchemaDriver()
106106
engine, err = xorm.NewEngine("postgresschema", connStr)
107107
} else {
108-
engine, err = xorm.NewEngine(setting.Database.Type, connStr)
108+
engine, err = xorm.NewEngine(setting.Database.Type.String(), connStr)
109109
}
110110

111111
if err != nil {

Diff for: models/db/index.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ func postgresGetNextResourceIndex(ctx context.Context, tableName string, groupID
7373

7474
// GetNextResourceIndex generates a resource index, it must run in the same transaction where the resource is created
7575
func GetNextResourceIndex(ctx context.Context, tableName string, groupID int64) (int64, error) {
76-
if setting.Database.UsePostgreSQL {
76+
if setting.Database.Type.IsPostgreSQL() {
7777
return postgresGetNextResourceIndex(ctx, tableName, groupID)
7878
}
7979

Diff for: models/db/sequence.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313

1414
// CountBadSequences looks for broken sequences from recreate-table mistakes
1515
func CountBadSequences(_ context.Context) (int64, error) {
16-
if !setting.Database.UsePostgreSQL {
16+
if !setting.Database.Type.IsPostgreSQL() {
1717
return 0, nil
1818
}
1919

@@ -34,7 +34,7 @@ func CountBadSequences(_ context.Context) (int64, error) {
3434

3535
// FixBadSequences fixes for broken sequences from recreate-table mistakes
3636
func FixBadSequences(_ context.Context) error {
37-
if !setting.Database.UsePostgreSQL {
37+
if !setting.Database.Type.IsPostgreSQL() {
3838
return nil
3939
}
4040

Diff for: models/git/commit_status.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ func postgresGetCommitStatusIndex(ctx context.Context, repoID int64, sha string)
6565

6666
// GetNextCommitStatusIndex retried 3 times to generate a resource index
6767
func GetNextCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) {
68-
if setting.Database.UsePostgreSQL {
68+
if setting.Database.Type.IsPostgreSQL() {
6969
return postgresGetCommitStatusIndex(ctx, repoID, sha)
7070
}
7171

Diff for: models/migrations/base/db.go

+14-14
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
8989
hasID = hasID || (column.IsPrimaryKey && column.IsAutoIncrement)
9090
}
9191

92-
if hasID && setting.Database.UseMSSQL {
92+
if hasID && setting.Database.Type.IsMSSQL() {
9393
if _, err := sess.Exec(fmt.Sprintf("SET IDENTITY_INSERT `%s` ON", tempTableName)); err != nil {
9494
log.Error("Unable to set identity insert for table %s. Error: %v", tempTableName, err)
9595
return err
@@ -143,15 +143,15 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
143143
return err
144144
}
145145

146-
if hasID && setting.Database.UseMSSQL {
146+
if hasID && setting.Database.Type.IsMSSQL() {
147147
if _, err := sess.Exec(fmt.Sprintf("SET IDENTITY_INSERT `%s` OFF", tempTableName)); err != nil {
148148
log.Error("Unable to switch off identity insert for table %s. Error: %v", tempTableName, err)
149149
return err
150150
}
151151
}
152152

153153
switch {
154-
case setting.Database.UseSQLite3:
154+
case setting.Database.Type.IsSQLite3():
155155
// SQLite will drop all the constraints on the old table
156156
if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
157157
log.Error("Unable to drop old table %s. Error: %v", tableName, err)
@@ -178,7 +178,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
178178
return err
179179
}
180180

181-
case setting.Database.UseMySQL:
181+
case setting.Database.Type.IsMySQL():
182182
// MySQL will drop all the constraints on the old table
183183
if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
184184
log.Error("Unable to drop old table %s. Error: %v", tableName, err)
@@ -205,7 +205,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
205205
log.Error("Unable to recreate uniques on table %s. Error: %v", tableName, err)
206206
return err
207207
}
208-
case setting.Database.UsePostgreSQL:
208+
case setting.Database.Type.IsPostgreSQL():
209209
var originalSequences []string
210210
type sequenceData struct {
211211
LastValue int `xorm:"'last_value'"`
@@ -296,7 +296,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
296296

297297
}
298298

299-
case setting.Database.UseMSSQL:
299+
case setting.Database.Type.IsMSSQL():
300300
// MSSQL will drop all the constraints on the old table
301301
if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
302302
log.Error("Unable to drop old table %s. Error: %v", tableName, err)
@@ -323,7 +323,7 @@ func DropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
323323
// TODO: This will not work if there are foreign keys
324324

325325
switch {
326-
case setting.Database.UseSQLite3:
326+
case setting.Database.Type.IsSQLite3():
327327
// First drop the indexes on the columns
328328
res, errIndex := sess.Query(fmt.Sprintf("PRAGMA index_list(`%s`)", tableName))
329329
if errIndex != nil {
@@ -405,7 +405,7 @@ func DropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
405405
return err
406406
}
407407

408-
case setting.Database.UsePostgreSQL:
408+
case setting.Database.Type.IsPostgreSQL():
409409
cols := ""
410410
for _, col := range columnNames {
411411
if cols != "" {
@@ -416,7 +416,7 @@ func DropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
416416
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
417417
return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
418418
}
419-
case setting.Database.UseMySQL:
419+
case setting.Database.Type.IsMySQL():
420420
// Drop indexes on columns first
421421
sql := fmt.Sprintf("SHOW INDEX FROM %s WHERE column_name IN ('%s')", tableName, strings.Join(columnNames, "','"))
422422
res, err := sess.Query(sql)
@@ -444,7 +444,7 @@ func DropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
444444
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
445445
return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
446446
}
447-
case setting.Database.UseMSSQL:
447+
case setting.Database.Type.IsMSSQL():
448448
cols := ""
449449
for _, col := range columnNames {
450450
if cols != "" {
@@ -543,13 +543,13 @@ func newXORMEngine() (*xorm.Engine, error) {
543543

544544
func deleteDB() error {
545545
switch {
546-
case setting.Database.UseSQLite3:
546+
case setting.Database.Type.IsSQLite3():
547547
if err := util.Remove(setting.Database.Path); err != nil {
548548
return err
549549
}
550550
return os.MkdirAll(path.Dir(setting.Database.Path), os.ModePerm)
551551

552-
case setting.Database.UseMySQL:
552+
case setting.Database.Type.IsMySQL():
553553
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
554554
setting.Database.User, setting.Database.Passwd, setting.Database.Host))
555555
if err != nil {
@@ -565,7 +565,7 @@ func deleteDB() error {
565565
return err
566566
}
567567
return nil
568-
case setting.Database.UsePostgreSQL:
568+
case setting.Database.Type.IsPostgreSQL():
569569
db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
570570
setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.SSLMode))
571571
if err != nil {
@@ -612,7 +612,7 @@ func deleteDB() error {
612612
}
613613
return nil
614614
}
615-
case setting.Database.UseMSSQL:
615+
case setting.Database.Type.IsMSSQL():
616616
host, port := setting.ParseMSSQLHostPort(setting.Database.Host)
617617
db, err := sql.Open("mssql", fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
618618
host, port, "master", setting.Database.User, setting.Database.Passwd))

Diff for: models/migrations/v1_12/v139.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ func PrependRefsHeadsToIssueRefs(x *xorm.Engine) error {
1313
var query string
1414

1515
switch {
16-
case setting.Database.UseMSSQL:
16+
case setting.Database.Type.IsMSSQL():
1717
query = "UPDATE `issue` SET `ref` = 'refs/heads/' + `ref` WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%'"
18-
case setting.Database.UseMySQL:
18+
case setting.Database.Type.IsMySQL():
1919
query = "UPDATE `issue` SET `ref` = CONCAT('refs/heads/', `ref`) WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%';"
2020
default:
2121
query = "UPDATE `issue` SET `ref` = 'refs/heads/' || `ref` WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%'"

Diff for: models/migrations/v1_13/v140.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func FixLanguageStatsToSaveSize(x *xorm.Engine) error {
4141

4242
// Delete language stat statuses
4343
truncExpr := "TRUNCATE TABLE"
44-
if setting.Database.UseSQLite3 {
44+
if setting.Database.Type.IsSQLite3() {
4545
truncExpr = "DELETE FROM"
4646
}
4747

Diff for: models/migrations/v1_13/v145.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ func IncreaseLanguageField(x *xorm.Engine) error {
2121
return err
2222
}
2323

24-
if setting.Database.UseSQLite3 {
24+
if setting.Database.Type.IsSQLite3() {
2525
// SQLite maps VARCHAR to TEXT without size so we're done
2626
return nil
2727
}
@@ -41,11 +41,11 @@ func IncreaseLanguageField(x *xorm.Engine) error {
4141
}
4242

4343
switch {
44-
case setting.Database.UseMySQL:
44+
case setting.Database.Type.IsMySQL():
4545
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE language_stat MODIFY COLUMN language %s", sqlType)); err != nil {
4646
return err
4747
}
48-
case setting.Database.UseMSSQL:
48+
case setting.Database.Type.IsMSSQL():
4949
// Yet again MSSQL just has to be awkward.
5050
// Here we have to drop the constraints first and then rebuild them
5151
constraints := make([]string, 0)
@@ -71,7 +71,7 @@ func IncreaseLanguageField(x *xorm.Engine) error {
7171
if err := sess.CreateUniques(new(LanguageStat)); err != nil {
7272
return err
7373
}
74-
case setting.Database.UsePostgreSQL:
74+
case setting.Database.Type.IsPostgreSQL():
7575
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE language_stat ALTER COLUMN language TYPE %s", sqlType)); err != nil {
7676
return err
7777
}

Diff for: models/migrations/v1_13/v151.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,13 @@ import (
1717

1818
func SetDefaultPasswordToArgon2(x *xorm.Engine) error {
1919
switch {
20-
case setting.Database.UseMySQL:
20+
case setting.Database.Type.IsMySQL():
2121
_, err := x.Exec("ALTER TABLE `user` ALTER passwd_hash_algo SET DEFAULT 'argon2';")
2222
return err
23-
case setting.Database.UsePostgreSQL:
23+
case setting.Database.Type.IsPostgreSQL():
2424
_, err := x.Exec("ALTER TABLE `user` ALTER COLUMN passwd_hash_algo SET DEFAULT 'argon2';")
2525
return err
26-
case setting.Database.UseMSSQL:
26+
case setting.Database.Type.IsMSSQL():
2727
// need to find the constraint and drop it, then recreate it.
2828
sess := x.NewSession()
2929
defer sess.Close()
@@ -53,7 +53,7 @@ func SetDefaultPasswordToArgon2(x *xorm.Engine) error {
5353
}
5454
return sess.Commit()
5555

56-
case setting.Database.UseSQLite3:
56+
case setting.Database.Type.IsSQLite3():
5757
// drop through
5858
default:
5959
log.Fatal("Unrecognized DB")

Diff for: models/migrations/v1_14/v158.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ func UpdateCodeCommentReplies(x *xorm.Engine) error {
6262
return err
6363
}
6464

65-
if setting.Database.UseMSSQL {
65+
if setting.Database.Type.IsMSSQL() {
6666
if _, err := sess.Exec(sqlSelect + " INTO #temp_comments" + sqlTail); err != nil {
6767
log.Error("unable to create temporary table")
6868
return err
@@ -72,13 +72,13 @@ func UpdateCodeCommentReplies(x *xorm.Engine) error {
7272
comments := make([]*Comment, 0, batchSize)
7373

7474
switch {
75-
case setting.Database.UseMySQL:
75+
case setting.Database.Type.IsMySQL():
7676
sqlCmd = sqlSelect + sqlTail + " LIMIT " + strconv.Itoa(batchSize) + ", " + strconv.Itoa(start)
77-
case setting.Database.UsePostgreSQL:
77+
case setting.Database.Type.IsPostgreSQL():
7878
fallthrough
79-
case setting.Database.UseSQLite3:
79+
case setting.Database.Type.IsSQLite3():
8080
sqlCmd = sqlSelect + sqlTail + " LIMIT " + strconv.Itoa(batchSize) + " OFFSET " + strconv.Itoa(start)
81-
case setting.Database.UseMSSQL:
81+
case setting.Database.Type.IsMSSQL():
8282
sqlCmd = "SELECT TOP " + strconv.Itoa(batchSize) + " * FROM #temp_comments WHERE " +
8383
"(id NOT IN ( SELECT TOP " + strconv.Itoa(start) + " id FROM #temp_comments ORDER BY id )) ORDER BY id"
8484
default:

Diff for: models/migrations/v1_14/v175.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import (
1414
)
1515

1616
func FixPostgresIDSequences(x *xorm.Engine) error {
17-
if !setting.Database.UsePostgreSQL {
17+
if !setting.Database.Type.IsPostgreSQL() {
1818
return nil
1919
}
2020

Diff for: models/migrations/v1_15/v184.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,11 @@ func RenameTaskErrorsToMessage(x *xorm.Engine) error {
5454
}
5555

5656
switch {
57-
case setting.Database.UseMySQL:
57+
case setting.Database.Type.IsMySQL():
5858
if _, err := sess.Exec("ALTER TABLE `task` CHANGE errors message text"); err != nil {
5959
return err
6060
}
61-
case setting.Database.UseMSSQL:
61+
case setting.Database.Type.IsMSSQL():
6262
if _, err := sess.Exec("sp_rename 'task.errors', 'message', 'COLUMN'"); err != nil {
6363
return err
6464
}

Diff for: models/migrations/v1_16/v191.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func AlterIssueAndCommentTextFieldsToLongText(x *xorm.Engine) error {
1616
return err
1717
}
1818

19-
if setting.Database.UseMySQL {
19+
if setting.Database.Type.IsMySQL() {
2020
if _, err := sess.Exec("ALTER TABLE `issue` CHANGE `content` `content` LONGTEXT"); err != nil {
2121
return err
2222
}

Diff for: models/migrations/v1_17/v217.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func AlterHookTaskTextFieldsToLongText(x *xorm.Engine) error {
1616
return err
1717
}
1818

19-
if setting.Database.UseMySQL {
19+
if setting.Database.Type.IsMySQL() {
2020
if _, err := sess.Exec("ALTER TABLE `hook_task` CHANGE `payload_content` `payload_content` LONGTEXT, CHANGE `request_content` `request_content` LONGTEXT, change `response_content` `response_content` LONGTEXT"); err != nil {
2121
return err
2222
}

0 commit comments

Comments
 (0)