go-srvc / mods / sqlxmod

github.com/go-srvc/mods/sqlxmod

pkg.go.dev source
go get github.com/go-srvc/mods/sqlxmod@v0.1.4

README

sqlxmod

sqlxmod wraps jmoiron/sqlx and takes care of gracefully closing connection pool when application exits.

package main

import (
	"context"
	"os"

	"github.com/XSAM/otelsql"
	"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() {
	srvc.RunAndExit(
		New(),
	)
}

// Store embeds the sqlxmod.DB
type Store struct {
	*sqlxmod.DB
}

func New() *Store {
	db := sqlxmod.New(
		sqlxmod.WithOtel("pgx", os.Getenv("DSN"),
			otelsql.WithAttributes(semconv.DBSystemNamePostgreSQL),
		),
	)
	return &Store{DB: db}
}

func (s *Store) Healthy(ctx context.Context) error {
	return s.DB.DB().PingContext(ctx)
}

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 (*DB) DB

func (d *DB) DB() *sqlx.DB

DB returns *sqlx.DB instance. This should be only call after Init.

func (*DB) ID

func (d *DB) ID() string

func (*DB) Init

func (d *DB) Init() error

func (*DB) Run

func (d *DB) Run() error

func (*DB) Stop

func (d *DB) Stop() error

type Opt

type Opt func(*DB) error

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),
			),
		),
	)
}