项目作者: tcfw

项目描述 :
Stupidly simple SQL migrations
高级语言: Go
项目地址: git://github.com/tcfw/go-migrate.git
创建时间: 2020-09-21T00:34:49Z
项目社区:https://github.com/tcfw/go-migrate

开源协议:MIT License

下载


go-migrate

PkgGoDev Go Report Card

Stupidly simple SQL migrations

Migrations should be packages with your binary, so why not codify them!

Example migration

  1. //your-package/migrations/2020_09_21_115238_create_users_table.go
  2. package migrations
  3. import (
  4. "database/sql"
  5. "time"
  6. "github.com/tcfw/go-migrate"
  7. )
  8. func init() {
  9. register(migrate.NewSimpleMigration(
  10. //Migration name to use in DB
  11. "create_users_table",
  12. //Timestamp of migration
  13. time.Date(2020, 9, 21, 11, 52, 38, 0, time.Local),
  14. //Up
  15. func(tx *sql.Tx) error {
  16. _, err := tx.Exec(`CREATE TABLE users (
  17. id UUID PRIMARY KEY,
  18. email string
  19. )`)
  20. return err
  21. },
  22. //Down
  23. func(tx *sql.Tx) error {
  24. _, err := tx.Exec(`DROP TABLE users`)
  25. return err
  26. },
  27. ))
  28. }
  1. //your-package/migrations/migrations.go
  2. package migrations
  3. import (
  4. "database/sql"
  5. "github.com/sirupsen/logrus"
  6. "github.com/tcfw/go-migrate"
  7. )
  8. //migs List of known migrations
  9. var migs migrate.MigrationList = migrate.MigrationList{}
  10. //register helper to register migrations from init
  11. func register(mig migrate.Migration) {
  12. migs = append(migs, mig)
  13. }
  14. //Migrate runs migrations up (run in main or init)
  15. func Migrate(db *sql.DB, log *logrus.Logger) error {
  16. return migrate.Migrate(db, log, migs)
  17. }

Notes

  • File names are irrelevant which is why name and date are in the migration struct (possibly fix in future)
  • There’s no auto migrate down like there is for up as increments aren’t stored in groups (like in for example Laravel migrations in PHP) and it is assumed that if you are migrating down, it should probably be a manual process anyway
  • There is no DB table locking.
  • Any failures rollback the TX of the total increment over multiple migrations