...

Source file src/github.com/ory/x/popx/migration_info.go

Documentation: github.com/ory/x/popx

     1  package popx
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  
     7  	"github.com/gobuffalo/pop/v5"
     8  )
     9  
    10  // Migration handles the data for a given database migration
    11  type Migration struct {
    12  	// Path to the migration (./migrations/123_create_widgets.up.sql)
    13  	Path string
    14  	// Version of the migration (123)
    15  	Version string
    16  	// Name of the migration (create_widgets)
    17  	Name string
    18  	// Direction of the migration (up)
    19  	Direction string
    20  	// Type of migration (sql)
    21  	Type string
    22  	// DB type (all|postgres|mysql...)
    23  	DBType string
    24  	// Runner function to run/execute the migration
    25  	Runner func(Migration, *pop.Connection, *pop.Tx) error
    26  }
    27  
    28  // Run the migration. Returns an error if there is
    29  // no mf.Runner defined.
    30  func (mf Migration) Run(c *pop.Connection, tx *pop.Tx) error {
    31  	if mf.Runner == nil {
    32  		return fmt.Errorf("no runner defined for %s", mf.Path)
    33  	}
    34  	return mf.Runner(mf, c, tx)
    35  }
    36  
    37  // Migrations is a collection of Migration
    38  type Migrations []Migration
    39  
    40  func (mfs Migrations) Len() int {
    41  	return len(mfs)
    42  }
    43  
    44  func (mfs Migrations) Less(i, j int) bool {
    45  	if mfs[i].Version == mfs[j].Version {
    46  		// force "all" to the back
    47  		return mfs[i].DBType != "all"
    48  	}
    49  	return mfs[i].Version < mfs[j].Version
    50  }
    51  
    52  func (mfs Migrations) Swap(i, j int) {
    53  	mfs[i], mfs[j] = mfs[j], mfs[i]
    54  }
    55  
    56  func sortIdent(i sort.Interface) sort.Interface {
    57  	return i
    58  }
    59  
    60  func (mfs Migrations) SortAndFilter(dialect string, modifiers ...func(sort.Interface) sort.Interface) Migrations {
    61  	// We need to sort mfs in order to push the dbType=="all" migrations
    62  	// to the back.
    63  	m := append(Migrations{}, mfs...)
    64  	sort.Sort(m)
    65  
    66  	vsf := make(Migrations, 0)
    67  	for k, v := range m {
    68  		if v.DBType == "all" {
    69  			// Add "all" only if we can not find a more specific migration for the dialect.
    70  			var hasSpecific bool
    71  			for kk, vv := range m {
    72  				if v.Version == vv.Version && kk != k && vv.DBType == dialect {
    73  					hasSpecific = true
    74  					break
    75  				}
    76  			}
    77  
    78  			if !hasSpecific {
    79  				vsf = append(vsf, v)
    80  			}
    81  		} else if v.DBType == dialect {
    82  			vsf = append(vsf, v)
    83  		}
    84  	}
    85  
    86  	mod := sortIdent(vsf)
    87  	for _, m := range modifiers {
    88  		mod = m(mod)
    89  	}
    90  
    91  	sort.Sort(mod)
    92  	return vsf
    93  }
    94  

View as plain text