...

Source file src/github.com/cybertec-postgresql/pgwatch/v3/internal/db/conn.go

Documentation: github.com/cybertec-postgresql/pgwatch/v3/internal/db

     1  package db
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"reflect"
     7  
     8  	pgx "github.com/jackc/pgx/v5"
     9  	pgconn "github.com/jackc/pgx/v5/pgconn"
    10  	pgxpool "github.com/jackc/pgx/v5/pgxpool"
    11  )
    12  
    13  type Querier interface {
    14  	Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error)
    15  }
    16  
    17  // PgxIface is common interface for every pgx class
    18  type PgxIface interface {
    19  	Begin(ctx context.Context) (pgx.Tx, error)
    20  	Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
    21  	QueryRow(context.Context, string, ...interface{}) pgx.Row
    22  	Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error)
    23  	CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
    24  }
    25  
    26  // PgxConnIface is interface representing pgx connection
    27  type PgxConnIface interface {
    28  	PgxIface
    29  	BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)
    30  	Close(ctx context.Context) error
    31  	Ping(ctx context.Context) error
    32  }
    33  
    34  // PgxPoolIface is interface representing pgx pool
    35  type PgxPoolIface interface {
    36  	PgxIface
    37  	Acquire(ctx context.Context) (*pgxpool.Conn, error)
    38  	BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)
    39  	Close()
    40  	Config() *pgxpool.Config
    41  	Ping(ctx context.Context) error
    42  	Stat() *pgxpool.Stat
    43  }
    44  
    45  func MarshallParamToJSONB(v any) any {
    46  	if v == nil {
    47  		return nil
    48  	}
    49  	val := reflect.ValueOf(v)
    50  	switch val.Kind() {
    51  	case reflect.Map, reflect.Slice:
    52  		if val.Len() == 0 {
    53  			return nil
    54  		}
    55  	case reflect.Struct:
    56  		if reflect.DeepEqual(v, reflect.Zero(val.Type()).Interface()) {
    57  			return nil
    58  		}
    59  	}
    60  	if b, err := json.Marshal(v); err == nil {
    61  		return string(b)
    62  	}
    63  	return nil
    64  }
    65