MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+110
@@ -0,0 +1,110 @@
|
||||
# Package `dbx`
|
||||
|
||||
Пакет `dbx` предоставляет функциональность для работы с базой данных PostgreSQL, включая настройку пула соединений,
|
||||
выполнение миграций через goose и возможностью создавать схемы БД.
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Клиент для взаимодействия с базой данных PostgreSQL, расширяющий клиент из [пакета `db`](../db/db.go). По умолчанию
|
||||
максимальное количество открытых соединений равно `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
|
||||
|
||||
```go
|
||||
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
|
||||
|
||||
```go
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package dbx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// Config holds the configuration for establishing a database connection.
|
||||
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 `schema:"Максимально количество соединений,если <=0 - используется значение по умолчанию равное cpu * 10"`
|
||||
MaxConnIdleTimeSec int `schema:"Максимальное время простоя подключения в секундах,если <=0 - используется значения по умолчанию равное 90"`
|
||||
Params map[string]string `schema:"Дополнительные параметры подключения"`
|
||||
}
|
||||
|
||||
// Dsn generates a PostgreSQL connection string from the configuration.
|
||||
// The applicationName parameter is included as a connection parameter.
|
||||
func (c Config) Dsn(applicationName string) string {
|
||||
u := url.URL{
|
||||
Scheme: "postgresql",
|
||||
User: nil,
|
||||
Host: fmt.Sprintf("%s:%d", c.Host, c.Port),
|
||||
Path: c.Database,
|
||||
}
|
||||
if c.Username != "" {
|
||||
u.User = url.UserPassword(c.Username, c.Password)
|
||||
}
|
||||
query := url.Values{}
|
||||
if c.Schema != "" {
|
||||
query.Set("search_path", c.Schema)
|
||||
}
|
||||
|
||||
if applicationName != "" {
|
||||
query.Set("application_name", applicationName)
|
||||
}
|
||||
|
||||
for key, value := range c.Params {
|
||||
query.Set(key, value)
|
||||
}
|
||||
u.RawQuery = query.Encode()
|
||||
return u.String()
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
// 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.
|
||||
package dbx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
)
|
||||
|
||||
// nolint:gochecknoglobals
|
||||
var (
|
||||
defaultMaxOpenConn = runtime.NumCPU() * 10
|
||||
)
|
||||
|
||||
const (
|
||||
minIdleConns = 2
|
||||
defaultMaxConnIdleTime = 90 * time.Second
|
||||
)
|
||||
|
||||
// MigrationRunner defines the interface for running database migrations.
|
||||
type MigrationRunner interface {
|
||||
Run(ctx context.Context, db *sql.DB, gooseOpts ...goose.ProviderOption) error
|
||||
}
|
||||
|
||||
// Client wraps a db.Client with migration support and schema management.
|
||||
// It is safe for concurrent use.
|
||||
type Client struct {
|
||||
*db.Client
|
||||
|
||||
migrationRunner MigrationRunner
|
||||
queryTraces []pgx.QueryTracer
|
||||
createSchema bool
|
||||
applicationName string
|
||||
}
|
||||
|
||||
// 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
|
||||
func Open(ctx context.Context, config Config, opts ...Option) (cli *Client, err error) {
|
||||
cli = &Client{}
|
||||
for _, opt := range opts {
|
||||
opt(cli)
|
||||
}
|
||||
|
||||
maxOpenConn := defaultMaxOpenConn
|
||||
if config.MaxOpenConn > 0 {
|
||||
maxOpenConn = config.MaxOpenConn
|
||||
}
|
||||
|
||||
maxConnIdleTime := defaultMaxConnIdleTime
|
||||
if config.MaxConnIdleTimeSec > 0 {
|
||||
maxConnIdleTime = time.Duration(config.MaxConnIdleTimeSec) * time.Second
|
||||
}
|
||||
|
||||
dbCli, err := db.Open(
|
||||
ctx,
|
||||
config.Dsn(cli.applicationName),
|
||||
db.WithQueryTracer(cli.queryTraces...),
|
||||
db.WithMaxOpenConns(int32(maxOpenConn)), //nolint:gosec
|
||||
db.WithMinIdleConns(int32(minIdleConns)), //nolint:gosec
|
||||
db.WithMaxConnIdleTime(maxConnIdleTime),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "open db")
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
_ = dbCli.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
isReadOnly, err := dbCli.IsReadOnly(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "check is read only connection")
|
||||
}
|
||||
|
||||
isCustomSchema := config.Schema != "public" && config.Schema != ""
|
||||
if !isReadOnly && cli.createSchema && isCustomSchema {
|
||||
_, err = dbCli.Exec(ctx, fmt.Sprintf("CREATE SCHEMA IF NOT EXISTS %s", config.Schema))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "exec create schema query")
|
||||
}
|
||||
}
|
||||
|
||||
if isCustomSchema {
|
||||
err = checkSchemaExistence(ctx, config.Schema, dbCli)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "check schema existence")
|
||||
}
|
||||
}
|
||||
|
||||
if !isReadOnly && cli.migrationRunner != nil {
|
||||
err = cli.migrationRunner.Run(ctx, dbCli.DB.DB)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "migration run")
|
||||
}
|
||||
}
|
||||
|
||||
cli.Client = dbCli
|
||||
return cli, nil
|
||||
}
|
||||
|
||||
// checkSchemaExistence verifies that the specified schema exists in the database.
|
||||
// Returns an error if the schema does not exist or if the query fails.
|
||||
func checkSchemaExistence(ctx context.Context, schema string, dbCli *db.Client) error {
|
||||
query := `SELECT EXISTS (
|
||||
SELECT 1 FROM pg_namespace WHERE nspname = $1
|
||||
)`
|
||||
var exists bool
|
||||
err := dbCli.QueryRowContext(ctx, query, schema).Scan(&exists)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "check schema existence")
|
||||
}
|
||||
if !exists {
|
||||
return errors.Errorf("schema '%s' does not exist", schema)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package dbx
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// LogTracer is a pgx QueryTracer that logs queries at debug level.
|
||||
type LogTracer struct {
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
// NewLogTracer creates a new LogTracer with the provided logger.
|
||||
func NewLogTracer(logger log.Logger) LogTracer {
|
||||
return LogTracer{
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// TraceQueryStart logs the SQL query when a query starts.
|
||||
func (l LogTracer) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
l.logger.Debug(ctx, "sql: log tracer", log.String("query", data.SQL))
|
||||
return ctx
|
||||
}
|
||||
|
||||
// TraceQueryEnd is called when a query completes. Currently a no-op.
|
||||
func (l LogTracer) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
// Package migration provides database migration functionality using the goose
|
||||
// library. It manages schema evolution by applying pending SQL or Go migrations
|
||||
// from a specified directory and tracks migration versions.
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// DialectPostgreSQL represents the PostgreSQL dialect for migrations.
|
||||
const (
|
||||
DialectPostgreSQL = goose.DialectPostgres
|
||||
// DialectSqlite3 represents the SQLite3 dialect for migrations.
|
||||
DialectSqlite3 = goose.DialectSQLite3
|
||||
// DialectClickhouse represents the ClickHouse dialect for migrations.
|
||||
DialectClickhouse = goose.DialectClickHouse
|
||||
)
|
||||
|
||||
// Runner manages database migrations using the goose library.
|
||||
// It applies pending migrations from a specified directory and tracks migration versions.
|
||||
type Runner struct {
|
||||
dialect goose.Dialect
|
||||
migrationDir string
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
// NewRunner creates a new migration Runner with the specified dialect,
|
||||
// migration directory, and logger.
|
||||
func NewRunner(
|
||||
dialect goose.Dialect,
|
||||
migrationDir string,
|
||||
logger log.Logger,
|
||||
) Runner {
|
||||
return Runner{
|
||||
dialect: dialect,
|
||||
migrationDir: migrationDir,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Run applies all pending migrations to the database.
|
||||
// It logs the current database version, lists all migrations with their status, and applies any pending migrations.
|
||||
// Returns an error if the migration directory does not exist, migrations cannot be loaded, or if applying migrations fails.
|
||||
func (r Runner) Run(ctx context.Context, db *sql.DB, gooseOpts ...goose.ProviderOption) error {
|
||||
ctx = log.ToContext(ctx, log.String("worker", "goose_db_migration"))
|
||||
|
||||
_, err := os.Stat(r.migrationDir)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get file info")
|
||||
}
|
||||
|
||||
provider, err := goose.NewProvider(r.dialect, db, os.DirFS(r.migrationDir), gooseOpts...)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get goose provider")
|
||||
}
|
||||
|
||||
dbVersion, err := provider.GetDBVersion(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get db version")
|
||||
}
|
||||
r.logger.Info(ctx, fmt.Sprintf("current db version: %d", dbVersion))
|
||||
|
||||
migrations, err := provider.Status(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get status migrations")
|
||||
}
|
||||
r.logger.Info(ctx, "print migration list")
|
||||
if len(migrations) == 0 {
|
||||
r.logger.Info(ctx, "no migrations")
|
||||
}
|
||||
for _, migration := range migrations {
|
||||
appliedAt := "Pending"
|
||||
if !migration.AppliedAt.IsZero() {
|
||||
appliedAt = migration.AppliedAt.Format(time.RFC3339)
|
||||
}
|
||||
msg := fmt.Sprintf(
|
||||
"migration: %s %s %s",
|
||||
filepath.Base(migration.Source.Path),
|
||||
strings.ToUpper(string(migration.State)),
|
||||
appliedAt,
|
||||
)
|
||||
r.logger.Info(ctx, msg)
|
||||
}
|
||||
|
||||
result, err := provider.Up(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "apply pending migrations")
|
||||
}
|
||||
for _, migrationResult := range result {
|
||||
r.logger.Info(ctx, fmt.Sprintf("applied migration: %s", migrationResult.String()))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package dbx
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/txix-open/isp-kit/dbx/migration"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// Option is a function that configures a Client.
|
||||
type Option func(db *Client)
|
||||
|
||||
// WithMigrationRunner configures the client to run database migrations from the specified directory.
|
||||
// The logger is used for migration-related logging.
|
||||
func WithMigrationRunner(migrationDir string, logger log.Logger) Option {
|
||||
return func(db *Client) {
|
||||
db.migrationRunner = migration.NewRunner(migration.DialectPostgreSQL, migrationDir, logger)
|
||||
}
|
||||
}
|
||||
|
||||
// WithQueryTracer registers one or more pgx QueryTracers for query lifecycle events.
|
||||
func WithQueryTracer(tracers ...pgx.QueryTracer) Option {
|
||||
return func(db *Client) {
|
||||
db.queryTraces = append(db.queryTraces, tracers...)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 WithCreateSchema(createSchema bool) Option {
|
||||
return func(db *Client) {
|
||||
db.createSchema = createSchema
|
||||
}
|
||||
}
|
||||
|
||||
// WithApplicationName sets the application name connection parameter.
|
||||
// This is used for identification in database logs and monitoring.
|
||||
func WithApplicationName(moduleName string) Option {
|
||||
return func(db *Client) {
|
||||
db.applicationName = moduleName
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user