add check if all migrations already applied

Signed-off-by: Maxim Trofimov <qwerty65k@mail.ru>
pull/12019/head
Maxim Trofimov 1 year ago
parent f2c6cb8d01
commit df5904d88a

@ -94,8 +94,42 @@ func (s *SQL) Name() string {
return SQLDriverName
}
// Check if all migrations al
func (s *SQL) checkAlreadyApplied(migrations []*migrate.Migration) bool {
// make map (set) of ids for fast search
migrationsIds := make(map[string]struct{})
for _, migration := range migrations {
migrationsIds[migration.Id] = struct{}{}
}
// get list of applied migrations
migrate.SetDisableCreateTable(true)
records, err := migrate.GetMigrationRecords(s.db.DB, postgreSQLDialect)
migrate.SetDisableCreateTable(false)
if err != nil {
s.Log("checkAlreadyApplied: failed to get migration records: %v", err)
return false
}
for _, record := range records {
if _, ok := migrationsIds[record.Id]; ok {
s.Log("checkAlreadyApplied: found previous migration (Id: %v) applied at %v", record.Id, record.AppliedAt)
delete(migrationsIds, record.Id)
}
}
// check if all migrations appliyed
if len(migrationsIds) != 0 {
for id := range migrationsIds {
s.Log("checkAlreadyApplied: find unapplied migration (id: %v)", id)
}
return false
}
return true
}
func (s *SQL) ensureDBSetup() error {
// Populate the database with the relations we need if they don't exist yet
migrations := &migrate.MemoryMigrationSource{
Migrations: []*migrate.Migration{
{
@ -121,9 +155,9 @@ func (s *SQL) ensureDBSetup() error {
CREATE INDEX ON %s (%s);
CREATE INDEX ON %s (%s);
CREATE INDEX ON %s (%s);
GRANT ALL ON %s TO PUBLIC;
ALTER TABLE %s ENABLE ROW LEVEL SECURITY;
`,
sqlReleaseTableName,
@ -200,6 +234,12 @@ func (s *SQL) ensureDBSetup() error {
},
}
// Check that init migration already applied
if s.checkAlreadyApplied(migrations.Migrations) {
return nil
}
// Populate the database with the relations we need if they don't exist yet
_, err := migrate.Exec(s.db.DB, postgreSQLDialect, migrations, migrate.Up)
return err
}
@ -315,7 +355,6 @@ func (s *SQL) List(filter func(*rspb.Release) bool) ([]*rspb.Release, error) {
s.Log("list: failed to list: %v", err)
return nil, err
}
var releases []*rspb.Release
for _, record := range records {
release, err := decodeRelease(record.Body)

Loading…
Cancel
Save