Documentation
¶
Overview ¶
Package pgxexec provides a unified interface for executing SQL queries and transactions using pgx. It is designed to work seamlessly with sqlc-generated code, allowing for easy integration.
Example ¶
package main
import (
"context"
"fmt"
"os"
"github.com/krhubert/pgxexec"
"github.com/krhubert/pgxexec/internal/sqlc/gensqlc"
"github.com/jackc/pgx/v5/pgxpool"
)
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, "postgres://postgres:@localhost:5432/postgres")
if err != nil {
fmt.Fprintln(os.Stderr, "Unable to connect to database:", err)
os.Exit(1)
}
exec := pgxexec.NewExecutor(pool, gensqlc.New(pool))
if err := exec.Queries().UserDeleteById(ctx, 1); err != nil {
fmt.Fprintln(os.Stderr, "query now() failed:", err)
os.Exit(1)
}
if err := pgxexec.ExecuteInTx(ctx, exec, func(tx *gensqlc.Queries) error {
user, err := tx.UserCreate(ctx, gensqlc.UserCreateParams{
Email: "testuser@localhost.dev",
Password: []byte("password"),
})
if err != nil {
return err
}
fmt.Println("created user with ID:", user.Id)
if err := tx.UserDeleteById(ctx, user.Id); err != nil {
return err
}
return nil
}); err != nil {
fmt.Fprintln(os.Stderr, "transaction failed:", err)
os.Exit(1)
}
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ExecuteInTx ¶
func ExecuteInTx[Q any, Queries QTx[Q]]( ctx context.Context, e ExecutorDBTX[Q, Queries], fn func(tx Queries) error, ) (err error)
ExecuteInTx executes a function within a transaction context.
Types ¶
type DB ¶
type DB interface {
Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
Query(context.Context, string, ...any) (pgx.Rows, error)
QueryRow(context.Context, string, ...any) pgx.Row
CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
}
DB defines a common interface for pgx.Conn ang pgxpool.Pool,
It matches the interface generated by sqlc for database operations.
type DBTX ¶
type DBTX interface {
DB
Begin(ctx context.Context) (pgx.Tx, error)
BeginTx(ctx context.Context, opts pgx.TxOptions) (pgx.Tx, error)
}
DBTX adds transaction capabilities to the DB interface.
type Executor ¶
type Executor[Q any, Queries QTx[Q]] interface { ExecutorDBTX[Q, Queries] BeginTx(ctx context.Context, opts pgx.TxOptions) (Tx[Q, Queries], error) }
Executor defines an interface for executing queries and managing transactions on database.
type ExecutorDBTX ¶
type ExecutorDBTX[Q any, Queries QTx[Q]] interface { Querier[Q, Queries] Begin(ctx context.Context) (Tx[Q, Queries], error) }
ExecutorDBTX defines an interface that is shared between Executor and Tx, allowing for transaction management and query execution.