github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/migrator/migrator.go (about)

     1  package migrator
     2  
     3  import (
     4  	"context"
     5  	"sort"
     6  
     7  	"github.com/octohelm/storage/internal/sql/adapter"
     8  	"github.com/octohelm/storage/pkg/sqlbuilder"
     9  )
    10  
    11  type actionType int
    12  
    13  const (
    14  	dropTableIndex actionType = iota
    15  	dropTableColumn
    16  	renameTableColumn
    17  	modifyTableColumn
    18  	addTableColumn
    19  	addTableIndex
    20  	createTable
    21  )
    22  
    23  func Migrate(ctx context.Context, a adapter.Adapter, toTables *sqlbuilder.Tables) error {
    24  	fromTables, err := a.Catalog(ctx)
    25  	if err != nil {
    26  		return err
    27  	}
    28  
    29  	migrations := make([]sqlbuilder.SqlExpr, 0)
    30  
    31  	for _, name := range toTables.TableNames() {
    32  		as := diff(a.Dialect(), fromTables.Table(name), toTables.Table(name))
    33  		sort.Sort(as)
    34  
    35  		for i := range as {
    36  			migrations = append(migrations, as[i].exprs...)
    37  		}
    38  	}
    39  
    40  	if len(migrations) == 0 {
    41  		return nil
    42  	}
    43  
    44  	return a.Transaction(ctx, func(ctx context.Context) error {
    45  		for _, m := range migrations {
    46  			if _, err := a.Exec(ctx, m); err != nil {
    47  				return err
    48  			}
    49  		}
    50  		return nil
    51  	})
    52  }