erius
8fce488888
TODO: use dataloaders to reduce amount of sql queries (figure out how to batch query nested paginated data) and add some basic unit or integrated testing
43 lines
1.2 KiB
Go
43 lines
1.2 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
|
|
"git.obamna.ru/erius/ozon-task/graph/model"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
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) {
|
|
log.Printf("connecting to PostgreSQL database at %s...", con)
|
|
// 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),
|
|
})
|
|
if err != nil {
|
|
log.Printf("failed to connect to database: %s", err)
|
|
return nil, err
|
|
}
|
|
log.Println("opened connection to PostgreSQL database")
|
|
log.Println("migrating model schema to database...")
|
|
err = db.AutoMigrate(&model.Post{}, &model.Comment{})
|
|
if err != nil {
|
|
log.Printf("failed to automatically migrate model schema: %s", err)
|
|
return nil, err
|
|
}
|
|
log.Println("finished migrating model schema")
|
|
return InitDatabase(db), nil
|
|
}
|