postgresql/postgresql.go

61 lines
1.1 KiB
Go
Raw Normal View History

2021-08-09 03:24:54 +00:00
package postgresql
import (
"fmt"
"log"
"time"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq" // For postgres dialect
"github.com/logrusorgru/aurora"
2021-10-15 10:07:33 +00:00
"go.elastic.co/apm/module/apmsql"
_ "go.elastic.co/apm/module/apmsql/pq" // For apm dialect
2021-08-09 03:24:54 +00:00
)
var (
sqlxClient *sqlx.DB
)
2021-08-09 03:30:00 +00:00
// Connect to postgresql database
2021-08-09 03:24:54 +00:00
func Connect(host, user, password, dbname, port, sslmode string) error {
// Connect string
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=%s TimeZone=UTC",
host, user, password, dbname, port, sslmode,
)
2021-08-09 03:30:00 +00:00
// TODO: write case for SSL mode
2021-10-15 10:07:33 +00:00
// db, err := sqlx.Connect("postgres", dsn)
// if err != nil {
// log.Fatalln(err)
// }
apmDB, err := apmsql.Open("postgres", dsn)
2021-08-09 03:24:54 +00:00
if err != nil {
log.Fatalln(err)
}
2021-10-15 10:07:33 +00:00
db := sqlx.NewDb(apmDB, "postgres")
2021-08-09 03:24:54 +00:00
fmt.Println(aurora.Green("*** CONNECTED TO POSTGRESQL - SQLX: " + dsn))
// Config connection pool
sqlDB := db.DB
sqlDB.SetMaxOpenConns(100)
sqlDB.SetMaxIdleConns(20)
sqlDB.SetConnMaxLifetime(time.Minute * 5)
// Assign client
sqlxClient = db
return nil
}
// GetSqlxInstance ...
func GetSqlxInstance() *sqlx.DB {
return sqlxClient
}