github.com/go-srvc/mods/sqlxmod
go get github.com/go-srvc/mods/sqlxmod@v1.17.0
README
sqlxmod
sqlxmod wraps jmoiron/sqlx as a module and closes the connection pool gracefully when the application exits.
package main
import (
"fmt"
"net/http"
"os"
"github.com/XSAM/otelsql"
"github.com/go-srvc/mods/httpmod"
"github.com/go-srvc/mods/sigmod"
"github.com/go-srvc/mods/sqlxmod"
"github.com/go-srvc/srvc"
semconv "go.opentelemetry.io/otel/semconv/v1.30.0"
_ "github.com/jackc/pgx/v5/stdlib"
)
func main() {
db := sqlxmod.New(
sqlxmod.WithOtel("pgx", os.Getenv("DSN"),
otelsql.WithAttributes(semconv.DBSystemNamePostgreSQL),
),
)
srvc.RunAndExit(
sigmod.New(os.Interrupt),
db,
httpmod.New(
httpmod.WithAddr(":8080"),
httpmod.WithHandler(handler(db)),
),
)
}
func handler(db *sqlxmod.DB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var version string
if err := db.DB().GetContext(r.Context(), &version, "SELECT version()"); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "db version: %s\n", version)
})
}
Overview
Package sqlxmod wraps https://pkg.go.dev/github.com/jmoiron/sqlx as a module.
Constants
const (
ErrDBNotSet = errStr("db not set")
ErrFailedOpenDB = errStr("failed to open db")
)const ID = "sqlxmod"Types
type DB
type DB struct {
// contains filtered or unexported fields
}func New
func New(opts ...Opt) *DBNew creates new sqlx module with given options. Remember to import required driver for your database.
func (*DB) DB
func (d *DB) DB() *sqlx.DBDB returns the underlying *sqlx.DB. Only valid after Init has run.
func (*DB) ID
func (d *DB) ID() stringfunc (*DB) Init
func (d *DB) Init() errorfunc (*DB) Run
func (d *DB) Run() errorfunc (*DB) Stop
func (d *DB) Stop() errortype Opt
type Opt func(*DB) errorfunc WithDB
func WithDB(db *sql.DB, driver string) OptWithDB creates *sqlx.DB from *sql.DB.
func WithDBx
func WithDBx(dbx *sqlx.DB) OptWithDBx sets *sqlx.DB for module.
func WithDBxFn
func WithDBxFn(fn func() (*sqlx.DB, error)) OptWithDBxFn sets *sqlx.DB using value returned from fn.
func WithDSN
func WithDSN(driver, dsn string) OptWithDSN opens a *sqlx.DB from the given driver name and DSN.
func WithOtel
func WithOtel(driver, dsn string, opts ...otelsql.Option) OptWithOtel registers *sqlx.DB with OpenTelemetry.
Examples
ExampleNew
package main
import (
"github.com/XSAM/otelsql"
"github.com/go-srvc/mods/sqlxmod"
"github.com/go-srvc/srvc"
semconv "go.opentelemetry.io/otel/semconv/v1.30.0"
)
func main() {
srvc.RunAndExit(
sqlxmod.New(
sqlxmod.WithOtel("postgres", "user=foo dbname=bar sslmode=disable",
otelsql.WithAttributes(semconv.DBSystemNamePostgreSQL),
),
),
)
}