ozon-task/internal/storage/db/postgres.go
erius e0aa12b126 Separated graphql schema into multiple files and moved them to graph/schema dir, update the gqlgen.yml accordingly
Removed unnecesary bindings for ID and Int in gqlgen.yml
Minor changes to Makefile docker-clean target
Reduced docker-compose postgres healthcheck interval for faster local db connections
Added pagination to graphql schema, the paginated queries are WIP
Removed unneeded fields from the model structs
Added allowComment check when adding comments
Switched gorm logger to Info mode
App now panics if the specified APP_STORAGE in env doesn't exist
Reworked database methods, still barely working and are WIP
2024-06-26 04:45:04 +03:00

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 scheme to database...")
err = db.AutoMigrate(&model.Post{}, &model.Comment{})
if err != nil {
log.Printf("failed to automatically migrate model scheme: %s", err)
return nil, err
}
log.Println("finished migrating model scheme")
return &Database{db}, nil
}