package main import ( "fmt" "time" "github.com/rs/zerolog/log" "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" ) var DB *gorm.DB func connectToDB() { dsn := fmt.Sprintf( "host=%v user=%v password=%v dbname=%v port=%v sslmode=disable TimeZone=Asia/Taipei", DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT, ) config := &gorm.Config{ Logger: logger.Discard, SkipDefaultTransaction: true, } if flagDev { config.Logger = logger.Default } for { db, err := gorm.Open(postgres.New(postgres.Config{ DSN: dsn, // data source name // PreferSimpleProtocol: true, // disables implicit prepared statement usage }), config) if err == nil { DB = db break } log.Warn().Err(err).Msg("Unable to connect to database") log.Warn().Msgf("Retrying in %v second.", 5) time.Sleep(time.Second * 5) } log.Info().Msg("Connection to postgres, ok.") } func migrateDB() { if err := DB.SetupJoinTable(&User{}, "Products", &Order{}); err != nil { panic(err) } if err := DB.AutoMigrate(&Node{}, &User{}, &Profile{}, &Product{}, &Order{}); err != nil { panic(err) } }