github.com/dhui/migrate@v3.4.0+incompatible/source/stub/stub.go (about) 1 package stub 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "io/ioutil" 8 "os" 9 10 "github.com/golang-migrate/migrate/source" 11 ) 12 13 func init() { 14 source.Register("stub", &Stub{}) 15 } 16 17 type Config struct{} 18 19 // d, _ := source.Open("stub://") 20 // d.(*stub.Stub).Migrations = 21 22 type Stub struct { 23 Url string 24 Instance interface{} 25 Migrations *source.Migrations 26 Config *Config 27 } 28 29 func (s *Stub) Open(url string) (source.Driver, error) { 30 return &Stub{ 31 Url: url, 32 Migrations: source.NewMigrations(), 33 Config: &Config{}, 34 }, nil 35 } 36 37 func WithInstance(instance interface{}, config *Config) (source.Driver, error) { 38 return &Stub{ 39 Instance: instance, 40 Migrations: source.NewMigrations(), 41 Config: config, 42 }, nil 43 } 44 45 func (s *Stub) Close() error { 46 return nil 47 } 48 49 func (s *Stub) First() (version uint, err error) { 50 if v, ok := s.Migrations.First(); !ok { 51 return 0, &os.PathError{"first", s.Url, os.ErrNotExist} // TODO: s.Url can be empty when called with WithInstance 52 } else { 53 return v, nil 54 } 55 } 56 57 func (s *Stub) Prev(version uint) (prevVersion uint, err error) { 58 if v, ok := s.Migrations.Prev(version); !ok { 59 return 0, &os.PathError{fmt.Sprintf("prev for version %v", version), s.Url, os.ErrNotExist} 60 } else { 61 return v, nil 62 } 63 } 64 65 func (s *Stub) Next(version uint) (nextVersion uint, err error) { 66 if v, ok := s.Migrations.Next(version); !ok { 67 return 0, &os.PathError{fmt.Sprintf("next for version %v", version), s.Url, os.ErrNotExist} 68 } else { 69 return v, nil 70 } 71 } 72 73 func (s *Stub) ReadUp(version uint) (r io.ReadCloser, identifier string, err error) { 74 if m, ok := s.Migrations.Up(version); ok { 75 return ioutil.NopCloser(bytes.NewBufferString(m.Identifier)), fmt.Sprintf("%v.up.stub", version), nil 76 } 77 return nil, "", &os.PathError{fmt.Sprintf("read up version %v", version), s.Url, os.ErrNotExist} 78 } 79 80 func (s *Stub) ReadDown(version uint) (r io.ReadCloser, identifier string, err error) { 81 if m, ok := s.Migrations.Down(version); ok { 82 return ioutil.NopCloser(bytes.NewBufferString(m.Identifier)), fmt.Sprintf("%v.down.stub", version), nil 83 } 84 return nil, "", &os.PathError{fmt.Sprintf("read down version %v", version), s.Url, os.ErrNotExist} 85 }