-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
74 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
package driver | ||
|
||
import ( | ||
"database/sql" | ||
"time" | ||
|
||
_ "github.com/jackc/pgconn" | ||
_ "github.com/jackc/pgx/v4" | ||
_ "github.com/jackc/pgx/v4/stdlib" | ||
) | ||
|
||
// DB holds the database connection pool | ||
type DB struct { | ||
SQL *sql.DB | ||
} | ||
|
||
var dbConn = &DB{} | ||
|
||
const maxOpenDbConn = 10 | ||
const maxIdleDbConn = 5 | ||
const maxDbLifeTime = 5 * time.Minute | ||
|
||
// ConnectSQL creates database pool for Postgres | ||
func ConnectSQL(dsn string) (*DB, error) { | ||
d, err := NewDatabase(dsn) | ||
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) { | ||
db, err := sql.Open("pgx", dsn) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
if err = db.Ping(); err != nil { | ||
return nil, err | ||
} | ||
|
||
return db, nil | ||
} |