go-pkg/mercury/sql/otel.go

45 lines
983 B
Go
Raw Normal View History

2024-01-22 16:00:58 -07:00
package sql
import (
"database/sql"
2024-04-19 10:56:27 -06:00
"strings"
2024-01-22 16:00:58 -07:00
"go.nhat.io/otelsql"
semconv "go.opentelemetry.io/otel/semconv/v1.20.0"
)
func openDB(driver, dsn string) (*sql.DB, error) {
system := semconv.DBSystemPostgreSQL
2024-04-19 10:56:27 -06:00
if driver == "sqlite" || strings.HasPrefix(driver, "libsql") {
2024-01-22 16:00:58 -07:00
system = semconv.DBSystemSqlite
}
2024-04-19 10:56:27 -06:00
if driver == "postgres" {
var err error
// Register the otelsql wrapper for the provided postgres driver.
driver, err = otelsql.Register(driver,
otelsql.AllowRoot(),
otelsql.TraceQueryWithoutArgs(),
otelsql.TraceRowsClose(),
otelsql.TraceRowsAffected(),
// otelsql.WithDatabaseName("my_database"), // Optional.
otelsql.WithSystem(system), // Optional.
)
if err != nil {
return nil, err
}
2024-01-22 16:00:58 -07:00
}
2024-04-19 10:56:27 -06:00
2024-01-22 16:00:58 -07:00
// Connect to a Postgres database using the postgres driver wrapper.
2024-04-19 10:56:27 -06:00
db, err := sql.Open(driver, dsn)
2024-01-22 16:00:58 -07:00
if err != nil {
return nil, err
}
if err := otelsql.RecordStats(db); err != nil {
return nil, err
}
return db, nil
}