gorm.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package adapter
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/porter-dev/porter/internal/config"
  6. "gorm.io/driver/postgres"
  7. "gorm.io/driver/sqlite"
  8. "gorm.io/gorm"
  9. )
  10. // New returns a new gorm database instance
  11. func New(conf *config.DBConf) (*gorm.DB, error) {
  12. if conf.SQLLite {
  13. // we add DisableForeignKeyConstraintWhenMigrating since our sqlite does
  14. // not support foreign key constraints
  15. return gorm.Open(sqlite.Open(conf.SQLLitePath), &gorm.Config{
  16. DisableForeignKeyConstraintWhenMigrating: true,
  17. })
  18. }
  19. dsn := fmt.Sprintf(
  20. "user=%s password=%s port=%d host=%s sslmode=disable",
  21. conf.Username,
  22. conf.Password,
  23. conf.Port,
  24. conf.Host,
  25. )
  26. res, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
  27. // retry the connection 3 times
  28. retryCount := 0
  29. timeout, _ := time.ParseDuration("5s")
  30. if err != nil {
  31. for {
  32. time.Sleep(timeout)
  33. res, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
  34. if retryCount > 3 {
  35. return nil, err
  36. }
  37. if err == nil {
  38. return res, nil
  39. }
  40. retryCount++
  41. }
  42. }
  43. return res, err
  44. }