-
Notifications
You must be signed in to change notification settings - Fork 47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature db migration #96
Merged
colynn
merged 6 commits into
go-atomci:v1.5.0-feat-app-refactor
from
sampsonye:feature-db-migration
Mar 16, 2022
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9fa92d0
support basic db migration by code
sampsonye f842083
remove unused files and commands
sampsonye e8e4f7c
migration 迁移到独立目录下
sampsonye c433233
优化Migration策略,在数据库中记录最新的Migration历史,确保每个Migration有且执行一次
sampsonye ac9b475
import os
sampsonye 71e24f1
更新CONTRIBUTING
sampsonye File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
package migrations | ||
|
||
import ( | ||
"fmt" | ||
"github.com/astaxie/beego/orm" | ||
"github.com/go-atomci/atomci/internal/middleware/log" | ||
"time" | ||
) | ||
|
||
type Migration20220101 struct { | ||
} | ||
|
||
func (m Migration20220101) GetCreateAt() time.Time { | ||
return time.Date(2022, 1, 1, 0, 0, 0, 0, time.Local) | ||
} | ||
|
||
func (m Migration20220101) Upgrade(ormer orm.Ormer) error { | ||
tables := []string{ | ||
"sys_resource_type", | ||
"sys_resource_operation", | ||
"sys_resource_constraint", | ||
"sys_user", | ||
"sys_group", | ||
"sys_group_user_rel", | ||
"sys_group_user_constraint", | ||
"sys_group_role", | ||
"sys_group_role_user", | ||
"sys_group_role_operation", | ||
"sys_audit", | ||
"sys_resource_router", | ||
} | ||
|
||
if err := setCreateAt(ormer, tables); err != nil { | ||
log.Log.Error(err.Error()) | ||
return err | ||
} | ||
if err := setUpdateAt(ormer, tables); err != nil { | ||
log.Log.Error(err.Error()) | ||
return err | ||
} | ||
return nil | ||
} | ||
|
||
func setCreateAt(ormer orm.Ormer, tables []string) error { | ||
for _, table := range tables { | ||
var count int | ||
sql := `SELECT count(1) FROM INFORMATION_SCHEMA.Columns WHERE table_schema=DATABASE() AND table_name=? | ||
AND column_name='create_at' AND COLUMN_DEFAULT='CURRENT_TIMESTAMP'` | ||
if err := ormer.Raw(sql, table).QueryRow(&count); err != nil { | ||
return err | ||
} | ||
if count == 0 { | ||
sql = `alter table ` + table + ` modify column create_at datetime not null DEFAULT CURRENT_TIMESTAMP` | ||
if _, err := ormer.Raw(sql).Exec(); err != nil { | ||
return err | ||
} | ||
log.Log.Info(sql) | ||
} else { | ||
log.Log.Debug(fmt.Sprintf("table `%v` already alter create_at, skip", table)) | ||
} | ||
} | ||
return nil | ||
} | ||
|
||
func setUpdateAt(ormer orm.Ormer, tables []string) error { | ||
for _, table := range tables { | ||
var count int | ||
sql := `SELECT count(1) FROM INFORMATION_SCHEMA.Columns WHERE table_schema=DATABASE() AND table_name=? | ||
AND column_name='update_at' AND COLUMN_DEFAULT='CURRENT_TIMESTAMP' AND EXTRA='on update CURRENT_TIMESTAMP'` | ||
if err := ormer.Raw(sql, table).QueryRow(&count); err != nil { | ||
return err | ||
} | ||
if count == 0 { | ||
sql = `alter table ` + table + ` modify column update_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP` | ||
if _, err := ormer.Raw(sql).Exec(); err != nil { | ||
return err | ||
} | ||
log.Log.Info(sql) | ||
} else { | ||
log.Log.Debug(fmt.Sprintf("table `%v` already alter update_at, skip", table)) | ||
} | ||
} | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package migrations | ||
|
||
import ( | ||
"github.com/astaxie/beego/orm" | ||
"strings" | ||
"time" | ||
) | ||
|
||
type Migration20220309 struct { | ||
} | ||
|
||
func (m Migration20220309) GetCreateAt() time.Time { | ||
return time.Date(2022, 3, 9, 0, 0, 0, 0, time.Local) | ||
} | ||
|
||
func (m Migration20220309) Upgrade(ormer orm.Ormer) error { | ||
_, err := ormer.Raw("UPDATE `sys_integrate_setting` SET `type`='registry' WHERE `type`='harbor';").Exec() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
_, err = ormer.Raw("DROP PROCEDURE IF EXISTS `ModifyHarborToRegistry`;").Exec() | ||
_, err = ormer.Raw(strings.ReplaceAll(`CREATE PROCEDURE <|SPIT|>ModifyHarborToRegistry<|SPIT|>() | ||
BEGIN | ||
DECLARE HARBOREXISTS int DEFAULT 0; | ||
DECLARE REGISTRYEXISTS int DEFAULT 0; | ||
SELECT count(1) INTO @HARBOREXISTS FROM information_schema.COLUMNS WHERE TABLE_NAME='project_env' AND COLUMN_NAME='harbor'; | ||
SELECT count(1) INTO @REGISTRYEXISTS FROM information_schema.COLUMNS WHERE TABLE_NAME='project_env' AND COLUMN_NAME='registry'; | ||
IF @HARBOREXISTS>0 AND @REGISTRYEXISTS=0 | ||
THEN | ||
ALTER TABLE <|SPIT|>project_env<|SPIT|> CHANGE COLUMN <|SPIT|>harbor<|SPIT|> <|SPIT|>registry<|SPIT|> bigint(20) NOT NULL DEFAULT 0; | ||
ELSEIF @HARBOREXISTS>0 AND @REGISTRYEXISTS>0 | ||
THEN | ||
UPDATE <|SPIT|>project_env<|SPIT|> SET <|SPIT|>registry<|SPIT|>=<|SPIT|>harbor<|SPIT|>; | ||
ALTER TABLE <|SPIT|>project_env<|SPIT|> DROP COLUMN <|SPIT|>harbor<|SPIT|>; | ||
END IF; | ||
END;`, "<|SPIT|>", "`")).Exec() | ||
|
||
_, err = ormer.Raw("CALL `ModifyHarborToRegistry`;").Exec() | ||
_, err = ormer.Raw("DROP PROCEDURE IF EXISTS `ModifyHarborToRegistry`;").Exec() | ||
|
||
if err != nil { | ||
return err | ||
} | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
package migrations | ||
|
||
import ( | ||
"github.com/astaxie/beego/orm" | ||
"sort" | ||
"time" | ||
) | ||
|
||
type MigrationTypes []Migration | ||
|
||
// Migration db migration base interface | ||
type Migration interface { | ||
GetCreateAt() time.Time | ||
Upgrade(ormer orm.Ormer) error | ||
} | ||
|
||
// Len 排序三人组 | ||
func (t MigrationTypes) Len() int { | ||
return len(t) | ||
} | ||
|
||
// Less 排序三人组 | ||
func (t MigrationTypes) Less(i, j int) bool { | ||
return t[i].GetCreateAt().Before(t[j].GetCreateAt()) | ||
} | ||
|
||
// Swap 排序三人组 | ||
func (t MigrationTypes) Swap(i, j int) { | ||
t[i], t[j] = t[j], t[i] | ||
} | ||
|
||
// InitMigration db migration register | ||
func InitMigration() { | ||
migrationTypes := MigrationTypes{ | ||
new(Migration20220101), | ||
new(Migration20220309), | ||
} | ||
|
||
migrateInTx(migrationTypes) | ||
} | ||
|
||
func migrateInTx(migrationTypes MigrationTypes) { | ||
//升序 | ||
sort.Sort(migrationTypes) | ||
|
||
//数据迁移(事务) | ||
ormClient := orm.NewOrm() | ||
last := getNewestData(ormClient) | ||
tempLast := last | ||
errRet := ormClient.Begin() | ||
for _, m := range migrationTypes { | ||
if m.GetCreateAt().After(last) { | ||
errRet = m.Upgrade(ormClient) | ||
if errRet != nil { | ||
break | ||
} | ||
} | ||
tempLast = m.GetCreateAt() | ||
} | ||
errRet = updateNewestData(ormClient, tempLast) | ||
if errRet != nil { | ||
ormClient.Rollback() | ||
} else { | ||
ormClient.Commit() | ||
} | ||
} | ||
|
||
func getNewestData(ormer orm.Ormer) time.Time { | ||
sureCreateTable(ormer) | ||
sql := `Select * From __dbmigration Limit 1` | ||
var lastMigrationDate time.Time | ||
ormer.Raw(sql).QueryRow(&lastMigrationDate) | ||
if lastMigrationDate.IsZero() { | ||
lastMigrationDate = time.Now() | ||
} | ||
return lastMigrationDate | ||
} | ||
|
||
func updateNewestData(ormer orm.Ormer, lastTime time.Time) error { | ||
countSql := "Select count(*) from __dbmigration" | ||
var count int | ||
ormer.Raw(countSql).QueryRow(&count) | ||
|
||
sql := "Update __dbmigration set last_migration_date=?" | ||
if count == 0 { | ||
sql = "Insert into __dbmigration(last_migration_date) values (?)" | ||
} | ||
_, err := ormer.Raw(sql, lastTime).Exec() | ||
return err | ||
} | ||
|
||
func sureCreateTable(ormer orm.Ormer) { | ||
ddl := `CREATE TABLE IF NOT EXISTS __dbmigration ( | ||
last_migration_date datetime DEFAULT CURRENT_TIMESTAMP | ||
)` | ||
ormer.Raw(ddl).Exec() | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
不考虑加个索引什么的?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
记录来自 @sampsonye 的私下回复
https://dev.mysql.com/doc/refman/8.0/en/mysql-indexes.html