github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/internal/db/pg/pg.go (about)

     1  package pg
     2  
     3  //nolint:gci
     4  import (
     5  	"fmt"
     6  
     7  	_ "github.com/lib/pq" // register PostgreSQL driver
     8  
     9  	"github.com/ShoshinNikita/budget-manager/internal/db/base"
    10  	"github.com/ShoshinNikita/budget-manager/internal/db/pg/migrations"
    11  	"github.com/ShoshinNikita/budget-manager/internal/logger"
    12  )
    13  
    14  type Config struct {
    15  	Host     string
    16  	Port     int
    17  	User     string
    18  	Password string
    19  	Database string
    20  }
    21  
    22  func (c Config) toURL() string {
    23  	return fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", c.User, c.Password, c.Host, c.Port, c.Database)
    24  }
    25  
    26  type DB struct {
    27  	*base.DB
    28  }
    29  
    30  func NewDB(config Config, log logger.Logger) (*DB, error) {
    31  	db, err := base.NewDB("postgres", config.toURL(), base.Dollar, migrations.GetMigrations(), log)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	return &DB{db}, nil
    36  }