github.com/filecoin-project/bacalhau@v0.3.23-0.20230228154132-45c989550ace/pkg/localdb/postgres/postgres.go (about)

     1  package postgres
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/XSAM/otelsql"
     7  	"github.com/filecoin-project/bacalhau/pkg/localdb/shared"
     8  	semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
     9  
    10  	_ "github.com/golang-migrate/migrate/v4/database/postgres"
    11  	_ "github.com/lib/pq"
    12  )
    13  
    14  func NewPostgresDatastore(
    15  	host string,
    16  	port int,
    17  	database string,
    18  	username string,
    19  	password string,
    20  	autoMigrate bool,
    21  ) (*shared.GenericSQLDatastore, error) {
    22  	connectionString := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", username, password, host, port, database)
    23  	db, err := otelsql.Open(
    24  		"postgres",
    25  		connectionString,
    26  		otelsql.WithAttributes(semconv.DBSystemPostgreSQL, semconv.HostName(host), semconv.PeerService("postgres")),
    27  	)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  
    32  	if err := otelsql.RegisterDBStatsMetrics(db, otelsql.WithAttributes(semconv.DBSystemPostgreSQL)); err != nil { //nolint:govet
    33  		return nil, err
    34  	}
    35  
    36  	datastore, err := shared.NewGenericSQLDatastore(
    37  		db,
    38  		"postgres",
    39  		connectionString,
    40  	)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	if autoMigrate {
    45  		err = datastore.MigrateUp()
    46  		if err != nil {
    47  			return nil, fmt.Errorf("there was an error doing the migration: %w", err)
    48  		}
    49  	}
    50  	return datastore, err
    51  }