Files
donat-widget/infrastructure/pg/connection.go
2024-09-27 13:50:20 +05:00

68 lines
1.3 KiB
Go

package pg
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"sync"
)
type Postgres struct {
db *pgxpool.Pool
}
var (
pgInstance *Postgres
pgOnce sync.Once
)
func NewPgPool(
ctx context.Context,
username, password, host, port, dbname string,
) *Postgres {
connString := "postgres://" + username + ":" + password + "@" + host + ":" + port + "/" + dbname + "?pool_max_conns=100"
pgOnce.Do(func() {
db, err := pgxpool.New(ctx, connString)
if err != nil {
panic(err)
}
pgInstance = &Postgres{db}
})
return pgInstance
}
func (pg *Postgres) Exec(ctx context.Context, query string, args ...interface{}) (pgconn.CommandTag, error) {
result, err := pg.db.Exec(ctx, query, args...)
if err != nil {
return result, err
}
return result, nil
}
func (pg *Postgres) Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) {
result, err := pg.db.Query(ctx, query, args...)
if err != nil {
return nil, err
}
return result, nil
}
func (pg *Postgres) CreateTable(ctx context.Context, query string) error {
_, err := pg.db.Exec(ctx, query)
if err != nil {
return err
}
return nil
}
func (pg *Postgres) DropTable(ctx context.Context, query string) error {
_, err := pg.db.Exec(ctx, query)
if err != nil {
return err
}
return nil
}