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

64 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"
)
var dbConn = &repository.DB{}
2024-07-06 20:26:41 +00:00
const (
maxOpenDbConn = 10
maxIdleDbConn = 5
maxDbLifetime = 5 * time.Minute
)
// ConnectSQL creates SQL pool for Postgres
func (s *sqlDriverRepo) ConnectSQL(dsn string) (*repository.DB, error) {
d, err := 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
err = testDB(d)
if err != nil {
return nil, err
}
return dbConn, nil
}
// testDB tries to ping the database
func testDB(d *sql.DB) error {
err := d.Ping()
if err != nil {
return err
}
return nil
}
// newDatabase creates a new database for the application
func 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
}