gorm.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. FullSaveAssociations: true,
  18. })
  19. }
  20. // connect to default postgres instance first
  21. baseDSN := fmt.Sprintf(
  22. "user=%s password=%s port=%d host=%s",
  23. conf.Username,
  24. conf.Password,
  25. conf.Port,
  26. conf.Host,
  27. )
  28. if conf.ForceSSL {
  29. baseDSN = baseDSN + " sslmode=require"
  30. } else {
  31. baseDSN = baseDSN + " sslmode=disable"
  32. }
  33. postgresDSN := baseDSN + " database=postgres"
  34. targetDSN := baseDSN + " database=" + conf.DbName
  35. defaultDB, err := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{
  36. FullSaveAssociations: true,
  37. })
  38. // attempt to create the database
  39. if conf.DbName != "" {
  40. defaultDB.Exec(fmt.Sprintf("CREATE DATABASE %s;", conf.DbName))
  41. }
  42. // open the database connection
  43. res, err := gorm.Open(postgres.Open(targetDSN), &gorm.Config{
  44. FullSaveAssociations: true,
  45. })
  46. // retry the connection 3 times
  47. retryCount := 0
  48. timeout, _ := time.ParseDuration("5s")
  49. if err != nil {
  50. for {
  51. time.Sleep(timeout)
  52. res, err = gorm.Open(postgres.Open(targetDSN), &gorm.Config{
  53. FullSaveAssociations: true,
  54. })
  55. if retryCount > 3 {
  56. return nil, err
  57. }
  58. if err == nil {
  59. return res, nil
  60. }
  61. retryCount++
  62. }
  63. }
  64. return res, err
  65. }