62 lines
1.1 KiB
Go
62 lines
1.1 KiB
Go
package pg
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"sync"
|
|
"template/config"
|
|
)
|
|
|
|
type Postgres struct {
|
|
Db *pgxpool.Pool
|
|
}
|
|
|
|
var (
|
|
pgInstance *Postgres
|
|
pgOnce sync.Once
|
|
)
|
|
|
|
func NewPgPool(
|
|
ctx context.Context,
|
|
username, password, host, port, dbname string,
|
|
) (*Postgres, error) {
|
|
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, nil
|
|
}
|
|
|
|
func (pg *Postgres) Ping(ctx context.Context) error {
|
|
err := pg.Db.Ping(ctx)
|
|
return err
|
|
}
|
|
|
|
func (pg *Postgres) Close() {
|
|
pg.Db.Close()
|
|
}
|
|
|
|
func (pg *Postgres) CreateTable(ctx context.Context) error {
|
|
result, err := pg.Db.Exec(ctx, createTableQuery)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fmt.Println(result)
|
|
return nil
|
|
}
|
|
|
|
var Pool, _ = NewPgPool(
|
|
context.Background(),
|
|
config.Config.Database.Username,
|
|
config.Config.Database.Password,
|
|
config.Config.Database.Host,
|
|
config.Config.Database.Port,
|
|
config.Config.Database.DBName,
|
|
)
|