package database import ( "context" "errors" "strings" "sync/atomic" "highload/internal/observability" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" ) func NewPostgres(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) { config, err := pgxpool.ParseConfig(databaseURL) if err != nil { return nil, err } tracer := &postgresTrace{} config.ConnConfig.Tracer = tracer pool, err := pgxpool.NewWithConfig(ctx, config) if err != nil { return nil, err } if err = pool.Ping(ctx); err != nil { pool.Close() return nil, err } observability.WatchPool(pool, &tracer.waiting) return pool, nil } type postgresTrace struct{ waiting atomic.Int64 } func (p *postgresTrace) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context { p.waiting.Add(1) if !trace.SpanContextFromContext(ctx).IsValid() { return ctx } ctx, _ = observability.Tracer.Start(ctx, "postgres.acquire", trace.WithSpanKind(trace.SpanKindClient), trace.WithAttributes(attribute.String("db.system.name", "postgresql"))) return ctx } func (p *postgresTrace) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) { p.waiting.Add(-1) observability.End(trace.SpanFromContext(ctx), data.Err) } func (*postgresTrace) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context { if !trace.SpanContextFromContext(ctx).IsValid() { return ctx } operation := "statement" if name, ok := strings.CutPrefix(data.SQL, "-- name: "); ok { // sqlc embeds the static query name. SQL and arguments stay local. operation, _, _ = strings.Cut(name, " ") } else { switch data.SQL { case "begin", "commit", "rollback": operation = data.SQL } } ctx, _ = observability.Tracer.Start(ctx, "postgres.query", trace.WithSpanKind(trace.SpanKindClient), trace.WithAttributes(attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", operation))) return ctx } func (*postgresTrace) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) { span := trace.SpanFromContext(ctx) var pgErr *pgconn.PgError if errors.As(data.Err, &pgErr) { span.SetAttributes(attribute.String("db.response.status_code", pgErr.Code)) } err := data.Err if errors.Is(err, pgx.ErrNoRows) { err = nil } observability.End(span, err) }