dbx

package
v1.67.2 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 12 Imported by: 2

README

Package dbx

Пакет dbx предоставляет функциональность для работы с базой данных PostgreSQL, включая настройку пула соединений, выполнение миграций через goose и возможностью создавать схемы БД.

Types

Client

Клиент для взаимодействия с базой данных PostgreSQL, расширяющий клиент из пакета db. По умолчанию максимальное количество открытых соединений равно CPU * 10.

Methods:

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

Open(ctx context.Context, config Config, opts ...Option) (*Client, error)

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

  • WithQueryTracer(tracers ...pgx.QueryTracer) Option – трассировка запросов с объектами реализующими интерфейс pgx.QueryTracer.
  • WithMigrationRunner(migrationDir string, logger log.Logger) Option – применить sql-скрипты для миграции, находящиеся в указанной директории.
  • WithCreateSchema(createSchema bool) Option – включить/выключить функцию создания схемы БД.
  • WithApplicationName(moduleName string) Option - указать название модуля в поле application_name таблицы серверных процессов

Usage

Default usage flow
package main

import (
	"context"
	"log"

	"github.com/txix-open/isp-kit/dbx"
	log2 "github.com/txix-open/isp-kit/log"
)

func main() {
	logger, err := log2.New()
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	cfg := dbx.Config{
		Host:     "127.0.0.1",
		Port:     5432,
		Database: "test",
		Username: "test",
		Password: "test", 
		MaxOpenConn: 10,
	}

	/* create client with migrations */
	cli, err := dbx.Open(
		ctx,
		cfg,
		dbx.WithMigrationRunner("./migrations", logger),
		dbx.WithQueryTracer(dbx.NewLogTracer(logger)),
	)
	if err != nil {
		log.Fatal(err)
    }

	var result int
	err = cli.SelectRow(ctx, &result, "SELECT COUNT(*) FROM users")
	if err != nil {
		log.Fatal(err)
	}
}

Connecting to db in slave mode
package main

import (
	"context"
	"log"

	"github.com/txix-open/isp-kit/dbx"
	log2 "github.com/txix-open/isp-kit/log"
)

func main() {
	/* create client with migrations */
	cli, err := dbx.Open(context.Background(), dbx.Config{
      Host:     "127.0.0.1",
      Port:     5432,
      Database: "test",
      Username: "test",
      Password: "test",
      Params: map[string]string{
        "target_session_attrs": "read-write",
      },
    })
    if err != nil {
        log.Fatal(err)
    }
}

Documentation

Overview

Package dbx extends the db package with additional features including automatic schema creation, database migrations via goose, and connection pool configuration. It provides a higher-level database client for PostgreSQL.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client wraps a db.Client with migration support and schema management. It is safe for concurrent use.

func Open

func Open(ctx context.Context, config Config, opts ...Option) (cli *Client, err error)

Open establishes a connection to a PostgreSQL database using the provided configuration. It applies connection pool settings, creates the schema if needed, and runs migrations. Returns an error if the connection fails, schema creation fails, or migrations fail. nolint:cyclop,nonamedreturns

type Config

type Config struct {
	Host        string            `validate:"required" schema:"Хост"`
	Port        int               `validate:"required" schema:"Порт"`
	Database    string            `validate:"required" schema:"База данных"`
	Username    string            `schema:"Логин"`
	Password    string            `schema:"Пароль"`
	Schema      string            `schema:"Схема"`
	MaxOpenConn int               `` /* 176-byte string literal not displayed */
	Params      map[string]string `schema:"Дополнительные параметры подключения"`
}

Config holds the configuration for establishing a database connection.

func (Config) Dsn

func (c Config) Dsn(applicationName string) string

Dsn generates a PostgreSQL connection string from the configuration. The applicationName parameter is included as a connection parameter.

type LogTracer

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

LogTracer is a pgx QueryTracer that logs queries at debug level.

func NewLogTracer

func NewLogTracer(logger log.Logger) LogTracer

NewLogTracer creates a new LogTracer with the provided logger.

func (LogTracer) TraceQueryEnd

func (l LogTracer) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData)

TraceQueryEnd is called when a query completes. Currently a no-op.

func (LogTracer) TraceQueryStart

func (l LogTracer) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context

TraceQueryStart logs the SQL query when a query starts.

type MigrationRunner

type MigrationRunner interface {
	Run(ctx context.Context, db *sql.DB, gooseOpts ...goose.ProviderOption) error
}

MigrationRunner defines the interface for running database migrations.

type Option

type Option func(db *Client)

Option is a function that configures a Client.

func WithApplicationName added in v1.52.2

func WithApplicationName(moduleName string) Option

WithApplicationName sets the application name connection parameter. This is used for identification in database logs and monitoring.

func WithCreateSchema added in v1.50.1

func WithCreateSchema(createSchema bool) Option

WithCreateSchema enables automatic creation of the database schema if it does not exist. This only applies to non-read-only connections with a custom schema.

func WithMigrationRunner

func WithMigrationRunner(migrationDir string, logger log.Logger) Option

WithMigrationRunner configures the client to run database migrations from the specified directory. The logger is used for migration-related logging.

func WithQueryTracer

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

WithQueryTracer registers one or more pgx QueryTracers for query lifecycle events.

Directories

Path Synopsis
Package migration provides database migration functionality using the goose library.
Package migration provides database migration functionality using the goose library.

Jump to

Keyboard shortcuts

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