ozon-task/internal/storage/db/postgres.go

44 lines
1.2 KiB
Go
Raw Permalink Normal View History

2024-06-24 23:34:10 +00:00
package db
import (
"fmt"
2024-06-25 00:19:53 +00:00
"log"
2024-06-24 23:34:10 +00:00
"os"
"git.obamna.ru/erius/ozon-task/graph/model"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
2024-06-24 23:34:10 +00:00
)
var (
host = os.Getenv("APP_POSTGRES_HOST")
port = os.Getenv("APP_POSTGRES_PORT")
user = os.Getenv("APP_POSTGRES_USER")
passwd = os.Getenv("APP_POSTGRES_PASSWORD")
db = os.Getenv("APP_POSTGRES_DB")
con = fmt.Sprintf("postgres://%s:%s@%s:%s/%s", user, passwd, host, port, db)
)
func InitPostgres() (*Database, error) {
2024-06-25 00:19:53 +00:00
log.Printf("connecting to PostgreSQL database at %s...", con)
2024-06-24 23:34:10 +00:00
// PrepareStmt is true for caching complex sql statements when adding comments or replies
db, err := gorm.Open(postgres.Open(con), &gorm.Config{
PrepareStmt: true,
Logger: logger.Default.LogMode(logger.Info),
})
2024-06-24 23:34:10 +00:00
if err != nil {
2024-06-25 00:19:53 +00:00
log.Printf("failed to connect to database: %s", err)
2024-06-24 23:34:10 +00:00
return nil, err
}
2024-06-25 00:19:53 +00:00
log.Println("opened connection to PostgreSQL database")
log.Println("migrating model schema to database...")
2024-06-25 00:19:53 +00:00
err = db.AutoMigrate(&model.Post{}, &model.Comment{})
if err != nil {
log.Printf("failed to automatically migrate model schema: %s", err)
2024-06-25 00:19:53 +00:00
return nil, err
}
log.Println("finished migrating model schema")
return InitDatabase(db), nil
2024-06-24 23:34:10 +00:00
}