migration.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package comm
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. "github.com/golang-migrate/migrate/v4"
  7. "github.com/golang-migrate/migrate/v4/database/mongodb"
  8. _ "github.com/golang-migrate/migrate/v4/source/file"
  9. )
  10. func AppMongoMiration() {
  11. ///data/migrations==mongodb://root:3dshow@3dshow-mongo-alpha:27017/dbname?query&&/data/migrations==mongodb://user:password@host:port/dbname?query
  12. config := os.Getenv("MONGO_MIGRATIONS")
  13. if len(config) < 1 {
  14. return
  15. }
  16. dbs := strings.Split(config, "&&")
  17. fmt.Println("mongo_migrations_dbs: ", dbs)
  18. for _, db := range dbs {
  19. frags := strings.Split(db, "==")
  20. if len(frags) != 2 {
  21. panic("mongo-migration config err=>" + db)
  22. }
  23. sourc := frags[0]
  24. dbUri := frags[1]
  25. p := &mongodb.Mongo{}
  26. d, err := p.Open(dbUri)
  27. if err != nil {
  28. panic("mongo-migration open err=>" + err.Error())
  29. }
  30. fileSource := fmt.Sprintf("file://%s", sourc)
  31. fmt.Println("mongo_migrations_file_source: ", fileSource)
  32. mi, err := migrate.NewWithDatabaseInstance(fileSource, "", d)
  33. if err != nil {
  34. panic("mongo-migration new instance err=>" + err.Error())
  35. }
  36. err = mi.Up()
  37. if err != nil {
  38. fmt.Println("mongo-migration up err=>" + err.Error())
  39. }
  40. }
  41. }