github.com/quay/claircore@v1.5.28/datastore/postgres/connect.go (about)

     1  package postgres
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/jackc/pgx/v4/pgxpool"
     8  	"github.com/prometheus/client_golang/prometheus"
     9  	"github.com/quay/zlog"
    10  
    11  	"github.com/quay/claircore/pkg/poolstats"
    12  )
    13  
    14  // Connect initialize a postgres pgxpool.Pool based on the connection string
    15  func Connect(ctx context.Context, connString string, applicationName string) (*pgxpool.Pool, error) {
    16  	// we are going to use pgx for more control over connection pool and
    17  	// and a cleaner api around bulk inserts
    18  	cfg, err := pgxpool.ParseConfig(connString)
    19  	if err != nil {
    20  		return nil, fmt.Errorf("failed to parse ConnString: %v", err)
    21  	}
    22  	const appnameKey = `application_name`
    23  	params := cfg.ConnConfig.RuntimeParams
    24  	if _, ok := params[appnameKey]; !ok {
    25  		params[appnameKey] = applicationName
    26  	}
    27  
    28  	pool, err := pgxpool.ConnectConfig(ctx, cfg)
    29  	if err != nil {
    30  		return nil, fmt.Errorf("failed to create ConnPool: %v", err)
    31  	}
    32  
    33  	if err := prometheus.Register(poolstats.NewCollector(pool, applicationName)); err != nil {
    34  		zlog.Info(ctx).Msg("pool metrics already registered")
    35  	}
    36  
    37  	return pool, nil
    38  }