67 lines
1.8 KiB
Go
67 lines
1.8 KiB
Go
// Copyright (c) 2025 Nikolai Papin
|
|
//
|
|
// This file is part of Easywish
|
|
//
|
|
// This program is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
//
|
|
// This program is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
|
// the GNU General Public License for more details.
|
|
//
|
|
// You should have received a copy of the GNU General Public License
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
package database
|
|
|
|
import (
|
|
"context"
|
|
|
|
"easywish/config"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type DbContext interface {
|
|
DBTX
|
|
Close()
|
|
BeginTx(ctx context.Context) (pgx.Tx, error)
|
|
}
|
|
|
|
type dbContextImpl struct {
|
|
Pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewDbContext() DbContext {
|
|
pool, err := pgxpool.New(context.Background(), config.GetConfig().DatabaseUrl)
|
|
if err != nil {
|
|
panic("db connection failed: " + err.Error())
|
|
}
|
|
return &dbContextImpl{Pool: pool}
|
|
}
|
|
|
|
func (d *dbContextImpl) Close() {
|
|
d.Pool.Close()
|
|
}
|
|
|
|
func (d *dbContextImpl) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
|
|
return d.Pool.Exec(ctx, sql, args...)
|
|
}
|
|
|
|
func (d *dbContextImpl) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
|
|
return d.Pool.Query(ctx, sql, args...)
|
|
}
|
|
|
|
func (d *dbContextImpl) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
|
|
return d.Pool.QueryRow(ctx, sql, args...)
|
|
}
|
|
|
|
func (d *dbContextImpl) BeginTx(ctx context.Context) (pgx.Tx, error) {
|
|
return d.Pool.Begin(ctx)
|
|
}
|