github.com/seashell-org/golang-migrate/v4@v4.15.3-0.20220722221203-6ab6c6c062d1/database/stub/stub.go (about)

     1  package stub
     2  
     3  import (
     4  	"io"
     5  	"io/ioutil"
     6  	"reflect"
     7  
     8  	"go.uber.org/atomic"
     9  
    10  	"github.com/seashell-org/golang-migrate/v4/database"
    11  )
    12  
    13  func init() {
    14  	database.Register("stub", &Stub{})
    15  }
    16  
    17  type Stub struct {
    18  	Url               string
    19  	Instance          interface{}
    20  	CurrentVersion    int
    21  	MigrationSequence []string
    22  	LastRunMigration  []byte // todo: make []string
    23  	IsDirty           bool
    24  	isLocked          atomic.Bool
    25  
    26  	Config *Config
    27  }
    28  
    29  func (s *Stub) Open(url string) (database.Driver, error) {
    30  	return &Stub{
    31  		Url:               url,
    32  		CurrentVersion:    database.NilVersion,
    33  		MigrationSequence: make([]string, 0),
    34  		Config:            &Config{},
    35  	}, nil
    36  }
    37  
    38  type Config struct{}
    39  
    40  func WithInstance(instance interface{}, config *Config) (database.Driver, error) {
    41  	return &Stub{
    42  		Instance:          instance,
    43  		CurrentVersion:    database.NilVersion,
    44  		MigrationSequence: make([]string, 0),
    45  		Config:            config,
    46  	}, nil
    47  }
    48  
    49  func (s *Stub) Close() error {
    50  	return nil
    51  }
    52  
    53  func (s *Stub) Lock() error {
    54  	if !s.isLocked.CAS(false, true) {
    55  		return database.ErrLocked
    56  	}
    57  	return nil
    58  }
    59  
    60  func (s *Stub) Unlock() error {
    61  	if !s.isLocked.CAS(true, false) {
    62  		return database.ErrNotLocked
    63  	}
    64  	return nil
    65  }
    66  
    67  func (s *Stub) Run(migration io.Reader) error {
    68  	m, err := ioutil.ReadAll(migration)
    69  	if err != nil {
    70  		return err
    71  	}
    72  	s.LastRunMigration = m
    73  	s.MigrationSequence = append(s.MigrationSequence, string(m[:]))
    74  	return nil
    75  }
    76  
    77  func (s *Stub) SetVersion(version int, state bool) error {
    78  	s.CurrentVersion = version
    79  	s.IsDirty = state
    80  	return nil
    81  }
    82  
    83  func (s *Stub) Version() (version int, dirty bool, err error) {
    84  	return s.CurrentVersion, s.IsDirty, nil
    85  }
    86  
    87  const DROP = "DROP"
    88  
    89  func (s *Stub) Drop() error {
    90  	s.CurrentVersion = database.NilVersion
    91  	s.LastRunMigration = nil
    92  	s.MigrationSequence = append(s.MigrationSequence, DROP)
    93  	return nil
    94  }
    95  
    96  func (s *Stub) EqualSequence(seq []string) bool {
    97  	return reflect.DeepEqual(seq, s.MigrationSequence)
    98  }