Help us shape the future of Go! Take the 2026 Go Developer Survey

db

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package db provides database abstractions and utilities. The main types (Connection, Repository, etc.) are defined in internal/repos/service.go which uses the db.Pool interface for database-agnostic operations.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoRows = errors.New("no rows in result set")

ErrNoRows is returned when a query returns no results. It wraps different driver-specific errors into a common error.

Functions

func Connect

func Connect(databaseURL string) (*pgxpool.Pool, error)

Connect creates a new database connection pool (convenience function). DEPRECATED: Use ConnectWithDriver for multi-database support.

func ConvertPlaceholders

func ConvertPlaceholders(query string, driver DriverType) string

ConvertPlaceholders converts PostgreSQL-style placeholders ($1, $2) to MySQL-style (?) when using MySQL driver.

func IsMySQLDuplicateError

func IsMySQLDuplicateError(err error) bool

IsMySQLDuplicateError checks if an error is a MySQL duplicate key error.

func IsNoRows

func IsNoRows(err error) bool

IsNoRows checks if an error is pgx.ErrNoRows.

func IsNoRowsError

func IsNoRowsError(err error) bool

IsNoRowsError checks if an error is a "no rows" error from any supported driver.

func NormalizeError

func NormalizeError(err error) error

NormalizeError converts driver-specific errors to common errors.

func PlaceholderStyle

func PlaceholderStyle(driver DriverType) string

PlaceholderStyle returns the placeholder style for a driver. PostgreSQL uses $1, $2, etc. MySQL uses ?

Types

type DB

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

DB wraps the database connection pool.

func New

func New(ctx context.Context, databaseURL string) (*DB, error)

New creates a new database connection.

func (*DB) Close

func (db *DB) Close()

Close closes the database connection pool.

func (*DB) Pool

func (db *DB) Pool() *pgxpool.Pool

Pool returns the underlying connection pool.

type DriverType

type DriverType string

DriverType represents the database driver type.

const (
	DriverPostgres DriverType = "postgres"
	DriverMySQL    DriverType = "mysql"
)

func DetectDriver

func DetectDriver(url string) DriverType

DetectDriver detects the database driver from the URL.

type MySQLPool

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

MySQLPool wraps sql.DB to implement the Pool interface for MySQL.

func TryGetMySQLPool

func TryGetMySQLPool(p Pool) (*MySQLPool, bool)

TryGetMySQLPool returns the underlying MySQLPool if available.

func (*MySQLPool) Begin

func (p *MySQLPool) Begin(ctx context.Context) (Tx, error)

Begin starts a new transaction.

func (*MySQLPool) Close

func (p *MySQLPool) Close() error

Close closes the connection pool.

func (*MySQLPool) Driver

func (p *MySQLPool) Driver() DriverType

Driver returns the driver type.

func (*MySQLPool) Exec

func (p *MySQLPool) Exec(ctx context.Context, sql string, args ...any) (Result, error)

Exec executes a query that doesn't return rows.

func (*MySQLPool) Ping

func (p *MySQLPool) Ping(ctx context.Context) error

Ping verifies the connection is alive.

func (*MySQLPool) Query

func (p *MySQLPool) Query(ctx context.Context, sql string, args ...any) (Rows, error)

Query executes a query that returns rows.

func (*MySQLPool) QueryRow

func (p *MySQLPool) QueryRow(ctx context.Context, sql string, args ...any) Row

QueryRow executes a query that returns at most one row.

func (*MySQLPool) Stats

func (p *MySQLPool) Stats() PoolStats

Stats returns connection pool statistics.

func (*MySQLPool) Underlying

func (p *MySQLPool) Underlying() *sql.DB

Underlying returns the underlying sql.DB.

type Pool

type Pool interface {
	// Query executes a query that returns rows.
	Query(ctx context.Context, sql string, args ...any) (Rows, error)

	// QueryRow executes a query that returns at most one row.
	QueryRow(ctx context.Context, sql string, args ...any) Row

	// Exec executes a query that doesn't return rows.
	Exec(ctx context.Context, sql string, args ...any) (Result, error)

	// Begin starts a new transaction.
	Begin(ctx context.Context) (Tx, error)

	// Ping verifies the connection is alive.
	Ping(ctx context.Context) error

	// Close closes the connection pool.
	Close() error

	// Driver returns the driver type.
	Driver() DriverType

	// Stats returns connection pool statistics.
	Stats() PoolStats
}

Pool is the common interface for database connection pools. It abstracts the differences between pgxpool.Pool and sql.DB.

func ConnectWithDriver

func ConnectWithDriver(ctx context.Context, databaseURL, driver string) (Pool, error)

ConnectWithDriver creates a new database connection pool with driver detection. The driver is auto-detected from the URL if not specified. Supported drivers: postgres, mysql.

func Open

func Open(ctx context.Context, url string, cfg PoolConfig) (Pool, error)

Open creates a new database connection pool based on the URL.

type PoolConfig

type PoolConfig struct {
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
}

PoolConfig contains common pool configuration.

func DefaultPoolConfig

func DefaultPoolConfig() PoolConfig

DefaultPoolConfig returns default pool configuration.

type PoolStats

type PoolStats struct {
	MaxOpenConnections int
	OpenConnections    int
	InUse              int
	Idle               int
}

PoolStats contains connection pool statistics.

type PostgresPool

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

PostgresPool wraps pgxpool.Pool to implement the Pool interface.

func MustGetPostgresPool

func MustGetPostgresPool(p Pool) *PostgresPool

MustGetPostgresPool panics if the pool is not a PostgresPool. This is useful for legacy code that requires pgxpool.Pool directly.

func TryGetPostgresPool

func TryGetPostgresPool(p Pool) (*PostgresPool, bool)

TryGetPostgresPool returns the underlying PostgresPool if available.

func (*PostgresPool) Begin

func (p *PostgresPool) Begin(ctx context.Context) (Tx, error)

Begin starts a new transaction.

func (*PostgresPool) Close

func (p *PostgresPool) Close() error

Close closes the connection pool.

func (*PostgresPool) Driver

func (p *PostgresPool) Driver() DriverType

Driver returns the driver type.

func (*PostgresPool) Exec

func (p *PostgresPool) Exec(ctx context.Context, sql string, args ...any) (Result, error)

Exec executes a query that doesn't return rows.

func (*PostgresPool) Ping

func (p *PostgresPool) Ping(ctx context.Context) error

Ping verifies the connection is alive.

func (*PostgresPool) Query

func (p *PostgresPool) Query(ctx context.Context, sql string, args ...any) (Rows, error)

Query executes a query that returns rows.

func (*PostgresPool) QueryRow

func (p *PostgresPool) QueryRow(ctx context.Context, sql string, args ...any) Row

QueryRow executes a query that returns at most one row.

func (*PostgresPool) Stats

func (p *PostgresPool) Stats() PoolStats

Stats returns connection pool statistics.

func (*PostgresPool) Underlying

func (p *PostgresPool) Underlying() *pgxpool.Pool

Underlying returns the underlying pgxpool.Pool for legacy code.

type Result

type Result interface {
	RowsAffected() (int64, error)
	LastInsertId() (int64, error)
}

Result is the common interface for exec results.

type Row

type Row interface {
	Scan(dest ...any) error
}

Row is the common interface for single row results.

type Rows

type Rows interface {
	Next() bool
	Scan(dest ...any) error
	Close()
	Err() error
}

Rows is the common interface for query results.

type SQLBuilder

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

SQLBuilder helps build database-agnostic SQL queries.

func NewSQLBuilder

func NewSQLBuilder(driver DriverType) *SQLBuilder

NewSQLBuilder creates a new SQL builder for the given driver.

func (*SQLBuilder) ArrayContains

func (b *SQLBuilder) ArrayContains(column string, pos int) string

ArrayContains checks if an array contains a value. PostgreSQL: $1 = ANY(column) MySQL: JSON_CONTAINS(column, JSON_QUOTE($1)).

func (*SQLBuilder) ArrayLength

func (b *SQLBuilder) ArrayLength(column string) string

ArrayLength returns the length of an array. PostgreSQL: cardinality(column) or array_length(column, 1) MySQL: JSON_LENGTH(column).

func (*SQLBuilder) Concat

func (b *SQLBuilder) Concat(parts ...string) string

Concat returns a string concatenation expression. PostgreSQL: a || b || c MySQL: CONCAT(a, b, c).

func (*SQLBuilder) CountFilter

func (b *SQLBuilder) CountFilter(condition string) string

CountFilter returns a conditional count expression. PostgreSQL: COUNT(*) FILTER (WHERE condition) MySQL: SUM(CASE WHEN condition THEN 1 ELSE 0 END).

func (*SQLBuilder) ForUpdateSkipLocked

func (b *SQLBuilder) ForUpdateSkipLocked() string

ForUpdateSkipLocked returns the appropriate locking clause. Both PostgreSQL and MySQL 8.0+ support this syntax.

func (*SQLBuilder) ILike

func (b *SQLBuilder) ILike(column string) string

ILike returns a case-insensitive LIKE condition. PostgreSQL: column ILIKE pattern MySQL: LOWER(column) LIKE LOWER(pattern).

func (*SQLBuilder) ILikeWithPos

func (b *SQLBuilder) ILikeWithPos(column string, pos int) string

ILikeArg returns the placeholder for ILIKE condition at given position.

func (*SQLBuilder) LikePattern

func (b *SQLBuilder) LikePattern(value string) string

LikePattern builds a LIKE pattern with wildcards.

func (*SQLBuilder) Now

func (b *SQLBuilder) Now() string

Now returns the current timestamp function.

func (*SQLBuilder) Placeholder

func (b *SQLBuilder) Placeholder(pos int) string

Placeholder returns the placeholder for the given position.

func (*SQLBuilder) Returning

func (b *SQLBuilder) Returning(columns ...string) string

Returning returns a RETURNING clause or empty string for MySQL.

func (*SQLBuilder) ReturningID

func (b *SQLBuilder) ReturningID() string

ReturningID returns a RETURNING clause or empty string for MySQL. For MySQL, you need to use LastInsertId() instead.

func (*SQLBuilder) TimestampLiteral

func (b *SQLBuilder) TimestampLiteral(ts string) string

TimestampLiteral converts a timestamp string to database-specific format. PostgreSQL: '1970-01-01'::timestamptz MySQL: '1970-01-01' (implicit conversion).

func (*SQLBuilder) UpsertQuery

func (b *SQLBuilder) UpsertQuery(
	table string,
	columns []string,
	conflictKey string,
	updateColumns []string,
) string

UpsertQuery builds an upsert query. PostgreSQL: INSERT ... ON CONFLICT (key) DO UPDATE SET ... MySQL: INSERT ... ON DUPLICATE KEY UPDATE ...

type StringArray

type StringArray []string

StringArray is a database-agnostic string array type. For PostgreSQL, it uses native TEXT[] type. For MySQL, it serializes to JSON.

func (*StringArray) Scan

func (a *StringArray) Scan(src any) error

Scan implements the sql.Scanner interface.

func (StringArray) Value

func (a StringArray) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type Tx

type Tx interface {
	// Query executes a query that returns rows.
	Query(ctx context.Context, sql string, args ...any) (Rows, error)

	// QueryRow executes a query that returns at most one row.
	QueryRow(ctx context.Context, sql string, args ...any) Row

	// Exec executes a query that doesn't return rows.
	Exec(ctx context.Context, sql string, args ...any) (Result, error)

	// Commit commits the transaction.
	Commit(ctx context.Context) error

	// Rollback aborts the transaction.
	Rollback(ctx context.Context) error
}

Tx is the common interface for database transactions.

type UnsupportedDriverError

type UnsupportedDriverError struct {
	Driver string
}

UnsupportedDriverError is returned when an unsupported database driver is specified.

func (*UnsupportedDriverError) Error

func (e *UnsupportedDriverError) Error() string

Jump to

Keyboard shortcuts

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