talent/db.go

51 lines
1.1 KiB
Go
Raw Normal View History

2021-12-30 09:16:20 +00:00
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{
2022-01-03 05:08:09 +00:00
Logger: logger.Discard,
2021-12-30 09:16:20 +00:00
SkipDefaultTransaction: true,
}
2022-01-03 05:08:09 +00:00
if flagDev {
config.Logger = logger.Default
}
2021-12-30 09:16:20 +00:00
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)
}
2021-12-30 13:39:00 +00:00
if err := DB.AutoMigrate(&Node{}, &User{}, &Profile{}, &Product{}, &Order{}); err != nil {
2021-12-30 09:16:20 +00:00
panic(err)
}
}