84 lines
1.7 KiB
Go
84 lines
1.7 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{}) (int64, error) {
|
|
var id int64
|
|
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) Update(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) 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) 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
|
|
}
|