You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
quartermaster/internal/postgres/database.go

72 lines
1.9 KiB

package postgres
import (
"database/sql"
"errors"
"fmt"
"log"
"github.com/dustinpianalto/quartermaster"
migrate "github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/pkger"
_ "github.com/lib/pq"
"github.com/markbates/pkger"
)
var (
ItemService quartermaster.ItemService
NutritionService quartermaster.NutritionService
LocationService quartermaster.LocationService
VitaminService quartermaster.VitaminService
GroupService quartermaster.GroupService
CategoryService quartermaster.CategoryService
UserService quartermaster.UserService
)
func ConnectDatabase(dbConnString string, version uint) {
db, err := sql.Open("postgres", dbConnString)
if err != nil {
panic(fmt.Sprintf("Can't connect to the database. %v", err))
}
db.SetMaxOpenConns(75) // The RDS instance has a max of 75 open connections
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(300)
log.Println("Database Connected")
err = runMigrations(db, version)
if err != nil {
log.Fatal(err)
}
log.Println("Migrations Completed")
initServices(db)
log.Println("Postgres Database Initialized")
}
func runMigrations(db *sql.DB, version uint) error {
_ = pkger.Include("/internal/postgres/migrations")
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
return err
}
m, err := migrate.NewWithDatabaseInstance("pkger:///internal/postgres/migrations", "postgres", driver)
if err != nil {
log.Fatalln(err)
}
if err := m.Migrate(version); errors.Is(err, migrate.ErrNoChange) {
log.Println(err)
} else if err != nil {
return err
}
return nil
}
func initServices(db *sql.DB) {
ItemService = itemService{db: db}
NutritionService = nutritionService{db: db}
LocationService = locationService{db: db}
VitaminService = vitaminService{db: db}
GroupService = groupService{db: db}
CategoryService = categoryService{db: db}
UserService = userService{db: db}
}