db

package
v1.67.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 8 Imported by: 1

README

Package db

Пакет db предоставляет клиент-обёртку над библиотекой sqlx с интеграцией pgx для работы с PostgreSQL. Реализует функциональность подключения к базе данных, выполнения запросов, транзакций и настройки трассировки запросов

Types

Client

Основная структура-клиент для взаимодействия с базой данных PostgreSQL

Methods:

Содержит все методы клиента-предшественника из sqlx.

Open(ctx context.Context, dsn string, opts ...Option) (*Client, error)

Создать подключение к базе данных по переданному dsn. Доступные опции:

  • WithQueryTracer(tracers ...pgx.QueryTracer) Option – трассировка запросов с объектами реализующими интерфейс pgx.QueryTracer.
(db *Client) Select(ctx context.Context, ptr any, query string, args ...any) error

Выполнить sql-запрос с возвращением данных из БД. Использует стандартные плейсхолдеры для позиционирования параметров.

(db *Client) SelectRow(ctx context.Context, ptr any, query string, args ...any) error

Выполнить sql-запрос с возвращением одной строки данных из БД. Использует стандартные плейсхолдеры для позиционирования параметров.

(db *Client) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

Выполнить sql-запрос без возврата данных из БД. Использует стандартные плейсхолдеры для позиционирования параметров.

(db *Client) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error)

Выполнить sql-запрос без возврата данных из БД. Позволяет использовать имена полей вместо плейсхолдеров для позиционирования параметров в sql-запросе.

(db *Client) RunInTransaction(ctx context.Context, txFunc TxFunc, opts ...TxOption) (err error)

Выполнить функцию txFunc в рамках транзакции. Доступны опции:

  • IsolationLevel(level sql.IsolationLevel) TxOption – изменить уровень изоляции транзакции
  • ReadOnly() TxOption – режим транзакции только на чтение

Usage

Default usage flow
package main

import (
	"context"
	"database/sql"
	"log"

	"github.com/txix-open/isp-kit/db"
)

type user struct {
	Name     string
	IsActive bool
}

func main() {
	ctx := context.Background()
	client, err := db.Open(ctx, "postgres://user:pass@localhost:5432/db")
	if err != nil {
		log.Fatal(err)
	}

	var users []user
	err = client.Select(ctx, &users, "SELECT * FROM users WHERE is_active = $1", true) /* read data */

	/* transaction */
	err = client.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
		res, err := tx.Exec(ctx, "UPDATE accounts SET balance = balance - $1", 100)
		if err != nil {
			return err
		}
		/* put here some business logic */
		return nil
	}, db.IsolationLevel(sql.LevelRepeatableRead))
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Overview

Package db provides a PostgreSQL database client wrapper that integrates sqlx with pgx, offering transaction support, query tracing, and automatic snake_case field mapping for struct tags.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ToSnakeCase

func ToSnakeCase(s string) string

ToSnakeCase converts a string from camelCase or PascalCase to snake_case. This is used for automatic mapping of struct field names to database column names.

Types

type Client

type Client struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

Client wraps a sqlx.DB instance with additional functionality for query tracing and transaction management. It is safe for concurrent use.

func Open

func Open(ctx context.Context, dsn string, opts ...Option) (*Client, error)

Open establishes a connection to a PostgreSQL database using the provided DSN. It applies the given options, validates the connection, and returns a Client. Returns an error if the configuration cannot be parsed or the connection fails.

func (*Client) Exec

func (db *Client) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

Exec executes a query that does not return rows, such as INSERT, UPDATE, or DELETE. Returns the sql.Result and any error that occurs during execution.

func (*Client) ExecNamed

func (db *Client) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error)

ExecNamed executes a named-parameter query that does not return rows. The arg parameter should be a struct or map that provides values for named placeholders. Returns the sql.Result and any error that occurs during execution.

func (*Client) IsReadOnly added in v1.50.1

func (db *Client) IsReadOnly(ctx context.Context) (bool, error)

IsReadOnly checks whether the current database connection is in read-only mode. Returns true if the connection is read-only, false otherwise. Returns an error if the query fails.

func (*Client) RunInTransaction

func (db *Client) RunInTransaction(ctx context.Context, txFunc TxFunc, opts ...TxOption) (err error)

RunInTransaction executes the provided function within a database transaction. It automatically commits on success and rolls back on error or panic. Transaction options can be provided to configure isolation level and other settings. Returns an error if the transaction cannot be started, committed, or rolled back.

func (*Client) Select

func (db *Client) Select(ctx context.Context, ptr any, query string, args ...any) error

Select executes a query that returns multiple rows and scans them into the provided pointer. The pointer must be a slice or a type that sqlx can scan into. Returns an error if the query fails or the scan is unsuccessful.

func (*Client) SelectRow

func (db *Client) SelectRow(ctx context.Context, ptr any, query string, args ...any) error

SelectRow executes a query that returns a single row and scans it into the provided pointer. Returns an error if the query fails, no rows are returned, or the scan is unsuccessful.

type DB

type DB interface {
	Select(ctx context.Context, ptr any, query string, args ...any) error
	SelectRow(ctx context.Context, ptr any, query string, args ...any) error
	Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
	ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error)
}

DB defines the interface for basic database operations.

type Option

type Option func(db *Client)

Option is a function that configures a Client.

func WithQueryTracer

func WithQueryTracer(tracers ...pgx.QueryTracer) Option

WithQueryTracer registers one or more pgx QueryTracers for query lifecycle events. Multiple tracers are invoked sequentially for each query.

type Transactional

type Transactional interface {
	RunInTransaction(ctx context.Context, txFunc TxFunc, opts ...TxOption) error
}

Transactional defines the interface for transactional database operations.

type Tx

type Tx struct {
	*sqlx.Tx
}

Tx wraps a sqlx.Tx with convenience methods for database operations.

func (*Tx) Exec

func (t *Tx) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

Exec executes a query that does not return rows.

func (*Tx) ExecNamed

func (t *Tx) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error)

ExecNamed executes a named-parameter query that does not return rows.

func (*Tx) Select

func (t *Tx) Select(ctx context.Context, ptr any, query string, args ...any) error

Select executes a query that returns multiple rows and scans them into the provided pointer.

func (*Tx) SelectRow

func (t *Tx) SelectRow(ctx context.Context, ptr any, query string, args ...any) error

SelectRow executes a query that returns a single row and scans it into the provided pointer.

type TxFunc

type TxFunc func(ctx context.Context, tx *Tx) error

TxFunc is a function that executes within a transaction.

type TxOption

type TxOption func(options *txOptions)

TxOption is a function that configures transaction options.

func IsolationLevel

func IsolationLevel(level sql.IsolationLevel) TxOption

IsolationLevel sets the transaction isolation level.

func MetricsLabel added in v1.55.0

func MetricsLabel(name string) TxOption

MetricsLabel sets a label for transaction metrics.

func ReadOnly

func ReadOnly() TxOption

ReadOnly marks the transaction as read-only.

Directories

Path Synopsis
Package jsonb provides a custom type for handling JSONB data in PostgreSQL.
Package jsonb provides a custom type for handling JSONB data in PostgreSQL.
Package query provides a fluent query builder for PostgreSQL using the Masterminds/squirrel library with dollar-sign placeholder formatting.
Package query provides a fluent query builder for PostgreSQL using the Masterminds/squirrel library with dollar-sign placeholder formatting.

Jump to

Keyboard shortcuts

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