udemy-go-web-1/internal/repository/driverrepo/sqldriver.go

62 lines
1.1 KiB
Go
Raw Normal View History

package driverrepo
2024-07-06 20:26:41 +00:00
import (
"database/sql"
"go-udemy-web-1/internal/repository"
2024-07-06 20:26:41 +00:00
"time"
_ "github.com/jackc/pgconn"
_ "github.com/jackc/pgx/v5"
_ "github.com/jackc/pgx/v5/stdlib"
)
const (
maxOpenDbConn = 10
maxIdleDbConn = 5
maxDbLifetime = 5 * time.Minute
)
// ConnectSQL creates SQL pool for Postgres
func (s *sqlDriverRepo) ConnectSQL(dsn string) (*repository.DB, error) {
2024-08-01 14:49:59 +00:00
d, err := s.newDatabase(dsn)
2024-07-06 20:26:41 +00:00
if err != nil {
panic(err)
}
d.SetMaxOpenConns(maxOpenDbConn)
d.SetMaxIdleConns(maxIdleDbConn)
d.SetConnMaxLifetime(maxDbLifetime)
dbConn.SQL = d
2024-08-01 14:49:59 +00:00
err = s.testDB(d)
2024-07-06 20:26:41 +00:00
if err != nil {
return nil, err
}
return dbConn, nil
}
// testDB tries to ping the database
2024-08-01 14:49:59 +00:00
func (s *sqlDriverRepo) testDB(d *sql.DB) error {
2024-07-06 20:26:41 +00:00
err := d.Ping()
if err != nil {
return err
}
return nil
}
// newDatabase creates a new database for the application
2024-08-01 14:49:59 +00:00
func (s *sqlDriverRepo) newDatabase(dsn string) (*sql.DB, error) {
2024-07-06 20:26:41 +00:00
db, err := sql.Open("pgx", dsn)
if err != nil {
return nil, err
}
// Ping test the conn
if err = db.Ping(); err != nil {
return nil, err
}
return db, err
}