github.com/bibaroc/wingman@v0.0.2-0.20200911182922-33c2085136b1/pkg/db/pgx.go (about)

     1  package db
     2  
     3  import (
     4  	"database/sql"
     5  	"fmt"
     6  
     7  	"github.com/bibaroc/wingman/pkg"
     8  	"github.com/google/wire"
     9  	_ "github.com/jackc/pgx/v4/stdlib"
    10  )
    11  
    12  var (
    13  	PGXSet = wire.NewSet(
    14  		pkg.DBConfigurationFromEnv,
    15  		NewPGXConnector,
    16  	)
    17  )
    18  
    19  type PGXConnector struct{}
    20  
    21  func (p PGXConnector) Connect(dbConfig pkg.DBConfiguration) (*sql.DB, error) {
    22  	dataSource := fmt.Sprintf(
    23  		"postgres://%s:%s@%s:%d/%s?sslmode=disable",
    24  		dbConfig.User,
    25  		dbConfig.Password,
    26  		dbConfig.Host,
    27  		dbConfig.Port,
    28  		dbConfig.DbName,
    29  	)
    30  	database, err := sql.Open("pgx", dataSource)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  
    35  	err = database.Ping()
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  
    40  	return database, nil
    41  }
    42  
    43  func NewPGXConnector() PGXConnector {
    44  	return PGXConnector{}
    45  }