fix: patch migration SQL by code (#18660)

Using code to patch the migration SQL instead of migration SQL file by
go-migrate, the latter way will bring the potential upgrade issue, refer
to code comments for more details.

Signed-off-by: chlins <chenyuzh@vmware.com>
This commit is contained in:
Chlins Zhang 2023-05-16 15:08:34 +08:00 committed by GitHub
parent e54389f271
commit 2ee3c3e40d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 1 deletions

View File

@ -1 +0,0 @@
CREATE INDEX IF NOT EXISTS idx_task_extra_attrs_report_uuids ON task USING gin ((extra_attrs::jsonb->'report_uuids'));

View File

@ -164,6 +164,7 @@ func main() {
if err := dao.InitDatabase(database); err != nil {
log.Fatalf("failed to initialize database: %v", err)
}
if strings.EqualFold(*runMode, "migrate") {
// Used by Harbor helm preinstall, preupgrade hook container
if err = migration.Migrate(database); err != nil {
@ -183,6 +184,18 @@ func main() {
}
ctx = orm.Clone(ctx)
// patch SQL here
// due to the limitation of go-migrate: https://github.com/golang-migrate/migrate/issues/278
// if one migration SQL file applied to main, and also need to backport to N-2 patch version,
// it's normal for N-1, but cannot work for N-2 because applied to N-2 then the schema version
// will be a new version which only can be included in the un-released version(e.g main/N-1.x),
// hence here will be a potential risk is user want upgrade from N-2.x to N-1.0(released version),
// the migration will be failed as go-migrate cannot find the new schema version in a released version.
// NOTE: the SQL should be Idempotent as it may be executed for multiple times.
if err := patchSQL(ctx); err != nil {
log.Fatalf("failed to patch sql: %v", err)
}
if err := config.Load(ctx); err != nil {
log.Fatalf("failed to load config: %v", err)
}
@ -306,3 +319,15 @@ func getDefaultScannerName() string {
}
return ""
}
func patchSQL(ctx context.Context) error {
ormer, err := orm.FromContext(ctx)
if err != nil {
return err
}
// 1. [v2.7.3] Add the index for report_uuids of task's extra_attrs to improve the query performance
// CREATE INDEX IF NOT EXISTS idx_task_extra_attrs_report_uuids ON task USING gin ((extra_attrs::jsonb->'report_uuids'));
sql := `CREATE INDEX IF NOT EXISTS idx_task_extra_attrs_report_uuids ON task USING gin ((extra_attrs::jsonb->'report_uuids'))`
_, err = ormer.Raw(sql).Exec()
return err
}