package db import ( "fmt" "log" "os" "git.obamna.ru/erius/ozon-task/graph/model" "gorm.io/driver/postgres" "gorm.io/gorm" ) 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}) 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 }