105 lines
2.1 KiB
Go

package pg
import (
"context"
"github.com/jackc/pgx/v5"
"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) Insert(ctx context.Context, query string, args ...interface{}) (any, error) {
var id any
err := pg.db.QueryRow(ctx, query, args...).Scan(&id)
if err != nil {
return 0, err
}
return id, nil
}
func (pg *Postgres) Select(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) SelectOne(ctx context.Context, query string, args ...interface{}) (pgx.Row, error) {
rows, err := pg.Select(ctx, query, args...)
if err != nil {
return nil, err
}
if !rows.Next() {
return nil, nil
}
return rows, nil
}
func (pg *Postgres) Update(ctx context.Context, query string, args ...interface{}) error {
_, err := pg.db.Exec(ctx, query, args...)
if err != nil {
return err
}
return nil
}
func (pg *Postgres) Delete(ctx context.Context, query string, args ...interface{}) error {
_, err := pg.db.Query(ctx, query, args...)
if err != nil {
return err
}
return nil
}
func (pg *Postgres) Exec(ctx context.Context, query string, args ...interface{}) error {
_, err := pg.db.Exec(ctx, query, args...)
if err != nil {
return err
}
return 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
}