MSP-8172 Add vendor

This commit is contained in:
Синельник Тимур Романович committed 2026-07-29 12:52:27 +03:00
1 parent 5175d87e08
commit eb066cb055
2619 files changed
+757077 -2

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
# Package `db`
Пакет `db` предоставляет клиент-обёртку над библиотекой [`sqlx`](https://github.com/jmoiron/sqlx) с интеграцией `pgx` для работы с PostgreSQL. Реализует
функциональность подключения к базе данных, выполнения запросов, транзакций и настройки трассировки запросов
## Types
### Client
Основная структура-клиент для взаимодействия с базой данных PostgreSQL
**Methods:**
Содержит все методы клиента-предшественника из [`sqlx`](https://github.com/jmoiron/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
```go
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)
}
}
```
+9
View File
@@ -0,0 +1,9 @@
package db
import "time"
type ConnectionSettings struct {
maxConns int32
minIdleConns int32
maxConnsIdleTime time.Duration
}
+157
View File
@@ -0,0 +1,157 @@
// 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.
package db
import (
"context"
"database/sql"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
)
// Client wraps a sqlx.DB instance with additional functionality for query
// tracing and transaction management. It is safe for concurrent use.
type Client struct {
*sqlx.DB
pool *pgxpool.Pool
queryTracers tracers
connSettings ConnectionSettings
}
// 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 Open(ctx context.Context, dsn string, opts ...Option) (*Client, error) {
db := &Client{}
for _, opt := range opts {
opt(db)
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, errors.WithMessage(err, "parse config")
}
cfg.ConnConfig.Tracer = db.queryTracers
cfg.MaxConns = db.connSettings.maxConns
cfg.MinIdleConns = db.connSettings.minIdleConns
cfg.MaxConnIdleTime = db.connSettings.maxConnsIdleTime
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, errors.WithMessage(err, "create pool")
}
sqlDb := stdlib.OpenDBFromPool(pool)
pgDb := sqlx.NewDb(sqlDb, "pgx")
pgDb.MapperFunc(ToSnakeCase)
err = pgDb.PingContext(ctx)
if err != nil {
return nil, errors.WithMessage(err, "ping database")
}
db.DB = pgDb
db.pool = pool
return db, nil
}
// Close closes SQL wrapper and underlying connection pool.
func (db *Client) Close() error {
err := db.DB.Close()
db.pool.Close()
return err
}
// 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 (db *Client) RunInTransaction(ctx context.Context, txFunc TxFunc, opts ...TxOption) (err error) {
options := &txOptions{}
for _, opt := range opts {
opt(options)
}
tx, err := db.BeginTxx(
txContext(ctx, options.metricsLabel),
options.nativeOpts,
)
if err != nil {
return errors.WithMessage(err, "begin transaction")
}
defer func() {
p := recover()
if p != nil { // rollback and repanic
_ = tx.Rollback()
panic(p)
}
if err != nil {
rbErr := tx.Rollback()
if rbErr != nil {
err = errors.WithMessage(err, rbErr.Error())
}
return
}
err = tx.Commit()
if err != nil {
err = errors.WithMessage(err, "commit tx")
}
}()
return txFunc(ctx, &Tx{tx})
}
// 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 (db *Client) Select(ctx context.Context, ptr any, query string, args ...any) error {
return db.SelectContext(ctx, ptr, query, args...)
}
// 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.
func (db *Client) SelectRow(ctx context.Context, ptr any, query string, args ...any) error {
return db.GetContext(ctx, ptr, query, args...)
}
// 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 (db *Client) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
return db.ExecContext(ctx, query, args...)
}
// 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 (db *Client) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error) {
return db.NamedExecContext(ctx, query, arg)
}
// 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 (db *Client) IsReadOnly(ctx context.Context) (bool, error) {
var isReadOnly string
err := db.QueryRowContext(ctx, "SHOW transaction_read_only").Scan(&isReadOnly)
if err != nil {
return false, err
}
return isReadOnly == "on", nil
}
func (db *Client) Stat() *pgxpool.Stat {
return db.pool.Stat()
}
func txContext(ctx context.Context, label string) context.Context {
if label == "" {
return ctx
}
return sql_metrics.OperationLabelToContext(ctx, label)
}
+19
View File
@@ -0,0 +1,19 @@
package db
import (
"context"
"database/sql"
)
// DB defines the interface for basic database operations.
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)
}
// Transactional defines the interface for transactional database operations.
type Transactional interface {
RunInTransaction(ctx context.Context, txFunc TxFunc, opts ...TxOption) error
}
+9
View File
@@ -0,0 +1,9 @@
package db
import "github.com/iancoleman/strcase"
// 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.
func ToSnakeCase(s string) string {
return strcase.ToSnake(s)
}
+36
View File
@@ -0,0 +1,36 @@
package db
import (
"time"
"github.com/jackc/pgx/v5"
)
// Option is a function that configures a Client.
type Option func(db *Client)
// WithQueryTracer registers one or more pgx QueryTracers for query lifecycle events.
// Multiple tracers are invoked sequentially for each query.
func WithQueryTracer(tracers ...pgx.QueryTracer) Option {
return func(db *Client) {
db.queryTracers = append(db.queryTracers, tracers...)
}
}
func WithMaxOpenConns(maxConns int32) Option {
return func(db *Client) {
db.connSettings.maxConns = maxConns
}
}
func WithMinIdleConns(minIdleConns int32) Option {
return func(db *Client) {
db.connSettings.minIdleConns = minIdleConns
}
}
func WithMaxConnIdleTime(maxIdleTime time.Duration) Option {
return func(db *Client) {
db.connSettings.maxConnsIdleTime = maxIdleTime
}
}
+17
View File
@@ -0,0 +1,17 @@
// Package query provides a fluent query builder for PostgreSQL using the
// Masterminds/squirrel library with dollar-sign placeholder formatting.
package query
import "github.com/Masterminds/squirrel"
// Query is a fluent query builder that wraps squirrel.StatementBuilderType
// with PostgreSQL-compatible dollar-sign placeholders ($1, $2, etc.).
type Query struct {
squirrel.StatementBuilderType
}
// New creates a new Query instance configured for PostgreSQL with dollar
// sign placeholders. Use this to build SQL queries with a fluent API.
func New() Query {
return Query{squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)}
}
+27
View File
@@ -0,0 +1,27 @@
package db
import (
"context"
"github.com/jackc/pgx/v5"
)
// tracers is a slice of pgx QueryTracers that are invoked sequentially.
type tracers []pgx.QueryTracer
// TraceQueryStart invokes all registered tracers when a query starts.
// It passes the context through each tracer and returns the final context.
// nolint:fatcontext
func (t tracers) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
for _, tracer := range t {
ctx = tracer.TraceQueryStart(ctx, conn, data)
}
return ctx
}
// TraceQueryEnd invokes all registered tracers when a query completes.
func (t tracers) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) {
for _, tracer := range t {
tracer.TraceQueryEnd(ctx, conn, data)
}
}
+72
View File
@@ -0,0 +1,72 @@
package db
import (
"context"
"database/sql"
"github.com/jmoiron/sqlx"
)
// txOptions holds configuration for database transactions.
type txOptions struct {
nativeOpts *sql.TxOptions
metricsLabel string
}
// TxOption is a function that configures transaction options.
type TxOption func(options *txOptions)
// IsolationLevel sets the transaction isolation level.
func IsolationLevel(level sql.IsolationLevel) TxOption {
return func(options *txOptions) {
if options.nativeOpts == nil {
options.nativeOpts = &sql.TxOptions{}
}
options.nativeOpts.Isolation = level
}
}
// ReadOnly marks the transaction as read-only.
func ReadOnly() TxOption {
return func(options *txOptions) {
if options.nativeOpts == nil {
options.nativeOpts = &sql.TxOptions{}
}
options.nativeOpts.ReadOnly = true
}
}
// MetricsLabel sets a label for transaction metrics.
func MetricsLabel(name string) TxOption {
return func(options *txOptions) {
options.metricsLabel = name
}
}
// TxFunc is a function that executes within a transaction.
type TxFunc func(ctx context.Context, tx *Tx) error
// Tx wraps a sqlx.Tx with convenience methods for database operations.
type Tx struct {
*sqlx.Tx
}
// Select executes a query that returns multiple rows and scans them into the provided pointer.
func (t *Tx) Select(ctx context.Context, ptr any, query string, args ...any) error {
return t.SelectContext(ctx, ptr, query, args...)
}
// SelectRow executes a query that returns a single row and scans it into the provided pointer.
func (t *Tx) SelectRow(ctx context.Context, ptr any, query string, args ...any) error {
return t.GetContext(ctx, ptr, query, args...)
}
// Exec executes a query that does not return rows.
func (t *Tx) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
return t.ExecContext(ctx, query, args...)
}
// ExecNamed executes a named-parameter query that does not return rows.
func (t *Tx) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error) {
return t.NamedExecContext(ctx, query, arg)
}