package driverrepo import ( "database/sql" "go-udemy-web-1/internal/repository" "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) { d, err := s.newDatabase(dsn) if err != nil { panic(err) } d.SetMaxOpenConns(maxOpenDbConn) d.SetMaxIdleConns(maxIdleDbConn) d.SetConnMaxLifetime(maxDbLifetime) dbConn.SQL = d err = s.testDB(d) if err != nil { return nil, err } return dbConn, nil } // testDB tries to ping the database func (s *sqlDriverRepo) testDB(d *sql.DB) error { err := d.Ping() if err != nil { return err } return nil } // newDatabase creates a new database for the application func (s *sqlDriverRepo) newDatabase(dsn string) (*sql.DB, error) { 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 }