dbrx

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: 14 Imported by: 2

README

Package dbrx

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

Types

Client

Клиент для взаимодействия с базой данных PostgreSQL, расширяющий клиент из пакета dbx.

Methods:

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

New(logger log.Logger, opts ...dbx.Option) *Client

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

  • 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 таблицы серверных процессов
(c *Client) Upgrade(ctx context.Context, config dbx.Config) error

Обновить конфигурацию подключения к базе данных.

(c *Client) DB() (*dbx.Client, error)

Получить родительский клиент из пакета dbx.

(c *Client) Healthcheck(ctx context.Context) error

Проверить доступность соединения с бд.

Usage

Default usage flow
package main

import (
	"context"
	"log"

	"github.com/txix-open/isp-kit/dbrx"
	"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)
	}
	cli := dbrx.New(logger)

	ctx := context.Background()
	cfg := dbx.Config{
		Host:     "127.0.0.1",
		Port:     5432,
		Database: "test",
		Username: "test",
		Password: "test",
		Schema:   "test",
	}
	err = dbrx.Upgrade(ctx, cfg)
	if err != nil {
		log.Fatal(err)
    }

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

Documentation

Overview

Package dbrx provides a dynamic database client that supports runtime configuration updates. It wraps dbx.Client with atomic pointer access, automatic metrics and tracing integration, and hot-reload capability.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrClientIsNotInitialized = errors.New("client is not initialized")
)

ErrClientIsNotInitialized is returned when the client has not been initialized.

Functions

This section is empty.

Types

type Client

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

Client provides dynamic database client management with hot-reload support. It wraps a dbx.Client and allows configuration updates at runtime. It is safe for concurrent use.

func New

func New(logger log.Logger, opts ...dbx.Option) *Client

New creates a new Client with the provided logger and options. The client is not initialized until Upgrade is called.

func (*Client) Close

func (c *Client) Close() error

Close closes the database connection and resets the client configuration. Returns an error if the underlying client fails to close.

func (*Client) DB

func (c *Client) DB() (*dbx.Client, error)

DB returns the underlying database client. Returns an error if the client has not been initialized.

func (*Client) Exec

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

Exec executes a query that does not return rows. Returns an error if the client is not initialized or if the query fails.

func (*Client) ExecNamed

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

ExecNamed executes a named-parameter query that does not return rows. Returns an error if the client is not initialized or if the query fails.

func (*Client) Healthcheck

func (c *Client) Healthcheck(ctx context.Context) error

Healthcheck verifies that the database connection is alive. Executes a simple query with a 500ms timeout. Returns an error if the client is not initialized or if the query fails.

func (*Client) RunInTransaction

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

RunInTransaction executes the provided function within a database transaction. Returns an error if the client is not initialized or if the transaction fails.

func (*Client) Select

func (c *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. Returns an error if the client is not initialized or if the query fails.

func (*Client) SelectRow

func (c *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 client is not initialized or if the query fails.

func (*Client) Upgrade

func (c *Client) Upgrade(ctx context.Context, config dbx.Config) error

Upgrade initializes or reinitializes the database client with the provided configuration. If the new configuration is identical to the previous one, initialization is skipped. It automatically adds metrics tracing, schema creation, and application name options. Returns an error if the connection fails or if the client is in read-only mode.

Jump to

Keyboard shortcuts

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