sqlmod

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 18, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

README

sqlmod

sqlmod takes care of gracefully closing connection pool when application exits.

package main

import (
	"context"
	"os"

	"github.com/XSAM/otelsql"
	"github.com/go-srvc/mods/sqlmod"
	"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 sqlmod.DB
type Store struct {
	*sqlmod.DB
}

func New() *Store {
	db := sqlmod.New(
		sqlmod.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)
}

Documentation

Overview

Package sqlmod wraps database/sql as a module.

Index

Examples

Constants

View Source
const (
	ErrDBNotSet     = errStr("db not set")
	ErrFailedOpenDB = errStr("failed to open db")
)
View Source
const ID = "sqlmod"

Variables

This section is empty.

Functions

This section is empty.

Types

type DB

type DB struct {
	// contains filtered or unexported fields
}

func New

func New(opts ...Opt) *DB

New creates new sql module with given options. Remember to import required driver for your database.

Example
package main

import (
	"github.com/XSAM/otelsql"
	"github.com/go-srvc/mods/sqlmod"
	"github.com/go-srvc/srvc"

	semconv "go.opentelemetry.io/otel/semconv/v1.30.0"
)

func main() {
	srvc.RunAndExit(
		sqlmod.New(
			sqlmod.WithOtel("postgres", "user=foo dbname=bar sslmode=disable",
				otelsql.WithAttributes(semconv.DBSystemNamePostgreSQL),
			),
		),
	)
}

func (*DB) DB

func (d *DB) DB() *sql.DB

DB returns *sql.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

func WithDB

func WithDB(db *sql.DB) Opt

WithDB sets *sql.DB for module.

func WithDBFn

func WithDBFn(fn func() (*sql.DB, error)) Opt

WithDBFn sets *sql.DB using value returned from fn.

func WithDSN

func WithDSN(driver, dsn string) Opt

func WithOtel

func WithOtel(driver, dsn string, opts ...otelsql.Option) Opt

WithOtel creates *sql.DB and instruments it with OpenTelemetry.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL