zergrepo

package module
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2020 License: MIT Imports: 14 Imported by: 0

README

= zerg-repo.

https://pkg.go.dev/github.com/ZergsLaw/zerg-repo?tab=doc[image:https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square[go.dev
reference])]

== Link
:hide-uri-scheme:
If you have questions about this application, there was a bug or there are suggestions for improvement, then you can ask it in Issues, or in link:telegram[https://t.me/zergsLaw]

== Migration cli.

Thin and lightweight client for performing migrations supports commands for migrations and their rollback.

[source]
----
USAGE:
   zergrepo command [command options] [arguments...]
----

== Install.
----
go get github.com/ZergsLaw/zerg-repo/zergrepo
----

=== Basic commands.

[source]
----
COMMANDS:
   version  get version
   migrate  exec migrate
   create   create migrate file
   help, h  Shows a list of commands or help for one command
----

== Creating a migration file.

[source]
----
USAGE:
    zergrepo create [command options]

OPTIONS:
   --migrate-name value, -M value  migration file name
   --dir value, -D value           migration file location
   --help, -h                      show help (default: false)
----

== Starting migration.

[source]
----
NAME:
   zergrepo migrate - exec migrate

USAGE:
   zergrepo migrate [command options]

DESCRIPTION:
   Migrate the DB to the most recent version available

OPTIONS:
   --db-driver value, -d value  database driver one of (postgres,mysql) (default: "postgres") [$DB_DRIVER]
   --operation value, -o value  migration command one of (up,up-to,up-one,down,down-to,reset)
   --to value, -t value         on what element to migrate (default: 0)
   --dir value, -D value        migration file location
   --db-name value, -n value    database name (default: "postgres") [$DB_NAME]
   --db-user value, -u value    database user (default: "postgres") [$DB_USER]
   --db-pass value, -p value    database password (default: "postgres") [$DB_PASS]
   --db-host value, -H value    database host (default: "localhost") [$DB_HOST]
   --db-port value, -P value    database port (default: 5432) [$DB_PORT]
   --help, -h                   show help (default: false)
----

== Example:

[source,bash]
----
// Also note that there are many default parameters for a convenient start.
zergrepo create --dir migrates --migrate-name create_user_table
// Up migrate
zergrepo migrate --opration up --dir migrates --db-host <host> --db-name <name> etc...
// Rollback all migrates
zergrepo migrate --opration reset --dir migrates --db-host <host> --db-name <name> etc...
----

== Library for create repo package.
=== Quick start.

[source,go]
----
// Get default config.
cfg := zergrepo.DefaultConfig()

ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Helper for connect database and ping by context.
db, err := zergrepo.ConnectByCfg(ctx, "postgres", cfg)
if err != nil {
	log.Fatal(fmt.Errorf("connect db: %w", err))
}

l, err := zap.NewDevelopment()
if err != nil {
	log.Fatal(fmt.Errorf("init zap: %w", err))
}

// Init default metric.
metric := zergrepo.MustMetric("namespace", "subsystem")

// Example error business logic.
ErrNotFound := errors.New("not found")
// Create mapper for convert database error to error business logic.
mapper := zergrepo.NewMapper(zergrepo.NewConvert(ErrNotFound, sql.ErrNoRows))

Repo = zergrepo.New(db, l.Named("zergrepo").Sugar(), metric, mapper)
defer Repo.Close()

// Example query.
err = Repo.Do(func(db *sql.DB) error {
	err := db.Ping()
	if err != nil {
		return err
	}

	return nil
})
// Example query by tx.
err = Repo.Tx(ctx, func(tx *sql.Tx) error {
	err = tx.QueryRowContext(ctx, "query").Scan(&val)
	if err != nil {
		// Return error just return the errors, the roolback will automatically happen.
		return err
	}
	// It will also automatically call commit for the transaction if nil is returned.
	return nil
})
----

=== Additional features.

Functional parameters.

[source,go]
-----
// The functional parameters for connecting to the database are also supported.
db, err := zergrepo.Connect(ctx, "postgres", zergrepo.Host("localhost"))
if err != nil {
	log.Fatal(fmt.Errorf("connect db: %w", err))
}
-----

Migration.

[source,go]
-----
// Create you migrate objects.
migrateUser := zergrepo.Migrate{
    Version: 1,
    Up:      zergrepo.Query(upTableUserQuery),
    Down:    zergrepo.Query(downTableUserQuery),
}

migrateProduct := zergrepo.Migrate{
    Version: 2,
    Up:      zergrepo.Query(upTableProductQuery),
    Down:    zergrepo.Query(downTableProductQuery),
}

// Register you migration.
err := zergrepo.RegisterMetric(migrateUser, migrateProduct)
if err != nil {
	log.Fatal(err)
}

// Migration to a specific version.
err = Repo.UpTo(ctx, 1)
if err != nil {
	log.Fatal(err)
}

// Starting migration of the next version.
err = Repo.UpOne(ctx)
if err != nil {
	log.Fatal(err)
}

// Rollback to a specific version.
err = Repo.DownTo(ctx, 2)
if err != nil {
	log.Fatal(err)
}

// Rollback current migration.
err = Repo.Down(ctx)
if err != nil {
	log.Fatal(err)
}

// Up all migration.
err = Repo.Up(ctx)
if err != nil {
	log.Fatal(err)
}

// Rollback all migration.
err = Repo.Reset(ctx)
if err != nil {
	log.Fatal(err)
}

-----

Documentation

Index

Constants

View Source
const (
	DBHost     = "localhost"
	DBPort     = 5432
	DBUser     = "postgres"
	DBPassword = "postgres"
	DBName     = "postgres"
	DBSSLMode  = "disable"
)

Default values.

Variables

View Source
var (
	ErrDuplicateVersion  = errors.New("duplicate version")
	ErrNotCorrectVersion = errors.New("version must be above 0")
	ErrNotSetUp          = errors.New("not set up function")
	ErrNotSetDown        = errors.New("not set down function")
)

Functions

func Connect

func Connect(ctx context.Context, driver string, options ...Option) (*sqlx.DB, error)

Connect to connect to the database using default values.

func ConnectByCfg

func ConnectByCfg(ctx context.Context, driver string, cfg Cfg) (*sqlx.DB, error)

ConnectByCfg connect to database by config.

func RegisterMetric added in v0.3.1

func RegisterMetric(m ...Migrate) error

RegisterMetric records your migrations. Also validates for errors if multiple migrations have the same version or if no up or down logic was specified.

Types

type Cfg added in v0.4.1

type Cfg interface {
	DSN() string
}

Cfg for convent replace for custom config.

type Config

type Config struct {
	Host     string `json:"host" yaml:"host" toml:"host" dsn:"host"`
	Port     int    `json:"port" yaml:"port" toml:"port" dsn:"port"`
	User     string `json:"user" yaml:"user" toml:"user" dsn:"user"`
	Password string `json:"password" yaml:"password" toml:"password" dsn:"password"`
	DBName   string `json:"db_name" yaml:"db_name" toml:"db_name" dsn:"dbname"`
	SSLMode  string `json:"ssl_mode" yaml:"ssl_mode" toml:"ssl_mode" dsn:"sslmode"`
}

Config contains basic data for connecting to the database. The basic tags for convenient data collection are placed.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig create instance Config by default data.

func (Config) DSN

func (c Config) DSN() string

Cfg returns a formatted string in Cfg format.

type ErrMapFunc added in v0.2.0

type ErrMapFunc func(error) error

ErrMapFunc converts certain errors into others. It is necessary for an opportunity not to lift errors of a database in the top layers.

func NewConvert added in v0.2.0

func NewConvert(target error, variables ...error) ErrMapFunc

NewConvert returns the converter function.

func PQConstraint added in v0.2.0

func PQConstraint(target error, constraint string) ErrMapFunc

PQConstraint returns a postgres oriented converter.

type Logger added in v0.3.1

type Logger interface {
	Warnf(format string, args ...interface{})
	Infof(format string, args ...interface{})
}

Logger for logging :).

type Mapper added in v0.2.0

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

Mapper is implements Mapperer.

func NewMapper added in v0.2.0

func NewMapper(converters ...ErrMapFunc) *Mapper

NewMapper create a new instance Mapper.

func (*Mapper) Map added in v0.2.0

func (m *Mapper) Map(err error) error

Map looking for one of all the functions that can convert an error. If it is not found, it will return the original error.

type Mapperer added in v0.2.0

type Mapperer interface {
	Map(err error) error
}

Mapperer responsible for converting some types of errors into others.

type Metric

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

Metric is responsible for collecting metrics and registering them.

func MustMetric

func MustMetric(namespace, subsystem string) *Metric

MustMetric collects a new metric instance and automatically registers the metrics. If it fails to register a metric, a panic will occur.

func NewMetric

func NewMetric(namespace, subsystem string, reg prometheus.Registerer) (*Metric, error)

NewMetric is gathering a new metric instantiation. Returns an error if a metric failed to be registered.

type Migrate added in v0.2.0

type Migrate struct {
	Version uint
	Up      MigrateFunc
	Down    MigrateFunc
}

Migrate migration object, stores information about the migration version, as well as functions for their execution and rollback.

type MigrateFunc added in v0.2.0

type MigrateFunc func(context.Context, *sqlx.Tx) error

MigrateFunc migration function.

func Query added in v0.2.0

func Query(query string) MigrateFunc

Query helper for convenient create MigrateFunc.

type Option

type Option func(*Config)

Option to connect to the database.

func Host

func Host(host string) Option

Host sets the connection parameters.

func Name

func Name(name string) Option

Name sets the connection parameters.

func Pass

func Pass(pass string) Option

Pass sets the connection parameters.

func Port

func Port(port int) Option

Port sets the connection parameters.

func SSLMode

func SSLMode(sslMode string) Option

SSLMode sets the connection parameters.

func User

func User(user string) Option

User sets the connection parameters.

type Repo

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

Repo The wrapper around *sql.DB. Provides a number of convenient methods for starting a transaction and starting functions and wrapping returnable errors.

func New

func New(db *sqlx.DB, log Logger, m *Metric, mapper Mapperer) *Repo

New return new instance Repo.

func (*Repo) Close

func (r *Repo) Close()

Close database connection.

func (*Repo) Do

func (r *Repo) Do(fn func(*sqlx.DB) error) error

Do a wrapper for database requests. If the callback returns the error, it will be wrapped and enriched with information about where the transaction was called from. Automatically collects metrics for function calls.

func (*Repo) Down added in v0.2.0

func (r *Repo) Down(ctx context.Context) error

Down rollback current migration.

func (*Repo) DownTo added in v0.3.1

func (r *Repo) DownTo(ctx context.Context, versionTo uint) error

DownTo rollback to a specific version.

func (*Repo) Reset added in v0.3.1

func (r *Repo) Reset(ctx context.Context) error

Reset rolls back all the migrations we've received.

func (*Repo) Tx

func (r *Repo) Tx(ctx context.Context, fn func(*sqlx.Tx) error) error

Tx automatically starts a transaction according to the parameters. If the callback returns the error, it will be wrapped and enriched with information about where the transaction was called from. Automatically collects metrics for function calls.

func (*Repo) TxByCfg added in v0.3.1

func (r *Repo) TxByCfg(ctx context.Context, opts *sql.TxOptions, fn func(*sqlx.Tx) error) error

TxByCfg automatically starts a transaction according to the parameters. If the callback returns the error, it will be wrapped and enriched with information about where the transaction was called from. Automatically collects metrics for function calls.

func (*Repo) Up added in v0.2.0

func (r *Repo) Up(ctx context.Context) error

Up performs all the migrations received.

func (*Repo) UpOne added in v0.3.1

func (r *Repo) UpOne(ctx context.Context) error

UpOne starting migration of the next version.

func (*Repo) UpTo added in v0.3.1

func (r *Repo) UpTo(ctx context.Context, versionTo uint) error

UpTo migration to a specific version.

func (*Repo) WarnIfFail

func (r *Repo) WarnIfFail(fn func() error)

WarnIfFail logs a function error if an error occurs.

Directories

Path Synopsis
cmd
core
Package core contains business logic application.
Package core contains business logic application.
fs
Package fs is responsible for migrating files.
Package fs is responsible for migrating files.
migrater
Package migrater contains logic for migrate data in database.
Package migrater contains logic for migrate data in database.

Jump to

Keyboard shortcuts

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