Skip to content

Commit

Permalink
add check if all migrations already applied
Browse files Browse the repository at this point in the history
Signed-off-by: Maxim Trofimov <qwerty65k@mail.ru>
  • Loading branch information
GOodCoffeeLover committed Aug 26, 2023
1 parent f2c6cb8 commit df5904d
Showing 1 changed file with 43 additions and 4 deletions.
47 changes: 43 additions & 4 deletions pkg/storage/driver/sql.go
Expand Up @@ -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{
{
Expand All @@ -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,
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit df5904d

Please sign in to comment.