package pgxprocess

import (
	
	

	
	
)

// database is a common interface for [pgx.Conn] and [pgxpool.Pool].
type database interface {
	Ping(context.Context) error
	Begin(context.Context) (pgx.Tx, error)
	BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error)
	Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
	Query(context.Context, string, ...any) (pgx.Rows, error)
	QueryRow(context.Context, string, ...any) pgx.Row
	CopyFrom(context.Context, pgx.Identifier, []string, pgx.CopyFromSource) (int64, error)
	SendBatch(context.Context, *pgx.Batch) pgx.BatchResults
}

type handle[ any,  interface {
	*
	database
}] struct {
	pointer atomic.Pointer[]
}

// Handle returns the underlying database handle.
func ( *handle[, ]) ()  {
	return (.pointer.Load())
}

func ( *handle[, ]) ( context.Context) error {
	 := (.pointer.Load())
	if  == nil {
		return ErrNotConnected
	}
	return .Ping()
}

func ( *handle[, ]) ( context.Context) (pgx.Tx, error) {
	 := (.pointer.Load())
	if  == nil {
		return nil, ErrNotConnected
	}
	return .Begin()
}

func ( *handle[, ]) ( context.Context,  pgx.TxOptions) (pgx.Tx, error) {
	 := (.pointer.Load())
	if  == nil {
		return nil, ErrNotConnected
	}
	return .BeginTx(, )
}

func ( *handle[, ]) ( context.Context,  string,  ...any) (pgconn.CommandTag, error) {
	 := (.pointer.Load())
	if  == nil {
		return pgconn.CommandTag{}, ErrNotConnected
	}
	return .Exec(, , ...)
}

func ( *handle[, ]) ( context.Context,  string,  ...any) (pgx.Rows, error) {
	 := (.pointer.Load())
	if  == nil {
		return nil, ErrNotConnected
	}
	return .Query(, , ...)
}

func ( *handle[, ]) ( context.Context,  string,  ...any) pgx.Row {
	 := (.pointer.Load())
	if  == nil {
		return errRow{}
	}
	return .QueryRow(, , ...)
}

func ( *handle[, ]) ( context.Context,  pgx.Identifier,  []string,  pgx.CopyFromSource) (int64, error) {
	 := (.pointer.Load())
	if  == nil {
		return 0, ErrNotConnected
	}
	return .CopyFrom(, , , )
}

func ( *handle[, ]) ( context.Context,  *pgx.Batch) pgx.BatchResults {
	 := (.pointer.Load())
	if  == nil {
		return errBatchResults{}
	}
	return .SendBatch(, )
}