eintopf.info@v0.13.16/service/dbmigration/store.go (about)

     1  package dbmigration
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  
     7  	"github.com/jmoiron/sqlx"
     8  )
     9  
    10  type SqlStore struct {
    11  	db *sqlx.DB
    12  }
    13  
    14  func NewSqlStore(db *sqlx.DB) (*SqlStore, error) {
    15  	_, err := db.Exec(`
    16          CREATE TABLE IF NOT EXISTS migrations (
    17              name varchar(64) NOT NULL PRIMARY KEY UNIQUE
    18          );
    19      `)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	return &SqlStore{db: db}, nil
    24  }
    25  
    26  func (s *SqlStore) AddMigration(ctx context.Context, name string) error {
    27  	_, err := s.db.ExecContext(ctx, `INSERT INTO migrations (name) VALUES ($1)`, name)
    28  	return err
    29  }
    30  
    31  func (s *SqlStore) HasMigration(ctx context.Context, name string) (bool, error) {
    32  	migrations := []string{}
    33  	err := s.db.SelectContext(ctx, &migrations, `SELECT name FROM migrations WHERE name = $1`, name)
    34  	if err != nil {
    35  		if err == sql.ErrNoRows {
    36  			return false, nil
    37  		}
    38  		return false, err
    39  	}
    40  	if len(migrations) == 0 {
    41  		return false, nil
    42  	}
    43  	return true, nil
    44  }