Categorygithub.com/acronis/go-dbkit
modulepackage
0.3.0
Repository: https://github.com/acronis/go-dbkit.git
Documentation: pkg.go.dev

# README

Toolkit for working with SQL databases in Go

GoDoc Widget

Installation

go get -u github.com/acronis/go-dbkit

Structure

/

Package dbkit provides helpers for working with different SQL databases (MySQL, PostgreSQL, SQLite and MSSQL).

/distrlock

Package distrlock contains DML (distributed lock manager) implementation (now DMLs based on MySQL and PostgreSQL are supported). Now only manager that uses SQL database (PostgreSQL and MySQL are currently supported) is available. Other implementations (for example, based on Redis) will probably be implemented in the future.

/migrate

Package migrate provides functionality for applying database migrations.

/mssql

Package mssql provides helpers for working with MSSQL. Should be imported explicitly. To register mssql as retryable func use side effect import like so:

import _ "github.com/acronis/go-dbkit/mssql"

/mysql

Package mysql provides helpers for working with MySQL. Should be imported explicitly. To register mysql as retryable func use side effect import like so:

import _ "github.com/acronis/go-dbkit/mysql"

/pgx

Package pgx provides helpers for working with Postgres via jackc/pgx driver. Should be imported explicitly. To register postgres as retryable func use side effect import like so:

import _ "github.com/acronis/go-dbkit/pgx"

/postgres

Package postgres provides helpers for working with Postgres via lib/pq driver. Should be imported explicitly. To register postgres as retryable func use side effect import like so:

import _ "github.com/acronis/go-dbkit/postgres"

/sqlite

Package sqlite provides helpers for working with SQLite. Should be imported explicitly. To register sqlite as retryable func use side effect import like so:

import _ "github.com/acronis/go-dbkit/sqlite"

/dbrutil

Package dbrutil provides utilities and helpers for dbr query builder.

/goquutil

Package goquutil provides auxiliary routines for working with goqu query builder.

Examples

Open database connection using the dbrutil package

func main() {
	// Create a new database configuration
	cfg := &db.Config{
		Driver:   db.DialectMySQL,
		Host:     "localhost",
		Port:     3306,
		Username: "your-username",
		Password: "your-password",
		Database: "your-database",
	}

	// Open a connection to the database
	conn, err := dbrutil.Open(cfg, true, nil)
	if err != nil {
		fmt.Println("Failed to open database connection:", err)
		return
	}
	defer conn.Close()

	// Create a new transaction runner
	runner := dbrutil.NewTxRunner(conn, &sql.TxOptions{}, nil)

	// Execute code inside a transaction
	err = runner.DoInTx(context.Background(), func(runner dbr.SessionRunner) error {
		// Perform database operations using the runner
		_, err := runner.InsertInto("users").
			Columns("name", "email").
			Values("Bob", "[email protected]").
			Exec()
		if err != nil {
			return err
		}

		// Return nil to commit the transaction
		return nil
	})
	if err != nil {
		fmt.Println("Failed to execute transaction:", err)
		return
	}
}

Usage of distrlock package

// Create a new DBManager with the MySQL dialect
dbManager, err := distrlock.NewDBManager(db.DialectMySQL)
if err != nil {
    log.Fatal(err)
}

// Open a connection to the MySQL database
dbConn, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database")
if err != nil {
    log.Fatal(err)
}
defer dbConn.Close()

// Create a new lock
lock, err := dbManager.NewLock(context.Background(), dbConn, "my_lock")
if err != nil {
    log.Fatal(err)
}

// Acquire the lock
err = lock.Acquire(context.Background(), dbConn, 5*time.Second)
if err != nil {
    log.Fatal(err)
}

// Do some work while holding the lock
fmt.Println("Lock acquired, doing some work...")

// Release the lock
err = lock.Release(context.Background(), dbConn)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Lock released")

License

Copyright © 2024 Acronis International GmbH.

Licensed under MIT License.

# Packages

Package dbrutil provides utilities and helpers for dbr query builder.
Package distrlock contains DML (distributed lock manager) implementation (now DMLs based on MySQL and PostgreSQL are supported).
Package goquutil provides auxiliary routines for working with goqu query builder.
Package migrate provides functionality for applying database migrations.
Package mssql provides helpers for working MSSQL database.
Package mysql provides helpers for working with the MySQL database using the github.com/go-sql-driver/mysql driver.
Package pgx provides helpers for working with the Postgres database using the github.com/jackc/pgx driver.
Package postgres provides helpers for working with the Postgres database using the github.com/lib/pq driver.
Package sqlite provides helpers for working SQLite database.

# Functions

DoInTx begins a new transaction, calls passed function and do commit or rollback depending on whether the function returns an error or not.
DoInTxWithOpts is a bit more configurable version of DoInTx that allows passing tx options.
GetIsRetryable returns a function that can tell for given driver if error is retryable.
InitOpenedDB initializes early opened *sql.DB instance.
MakeMSSQLDSN makes DSN for opening MSSQL database.
MakeMySQLDSN makes DSN for opening MySQL database.
MakePostgresDSN makes DSN for opening Postgres database.
MakeSQLiteDSN makes DSN for opening SQLite database.
NewConfig creates a new instance of the Config.
NewConfigWithKeyPrefix creates a new instance of the Config.
NewMetricsCollector creates a new metrics collector.
NewMetricsCollectorWithOpts is a more configurable version of creating MetricsCollector.
RegisterIsRetryableFunc registers callback to determinate specific DB error is retryable or not.

# Constants

Official recommendation from the DBA team.
Default values of connection parameters.
Default values of connection parameters.
SQL dialects.
SQL dialects.
SQL dialects.
SQL dialects.
SQL dialects.
Prometheus labels.
MSSQLDefaultTxLevel contains transaction isolation level which will be used by default for MSSQL.
MySQLDefaultTxLevel contains transaction isolation level which will be used by default for MySQL.
PgReadWriteParam read-write session attribute value name.
PgTargetSessionAttrs session attrs parameter name.
PostgresDefaultSSLMode contains Postgres SSL mode which will be used by default.
PostgresDefaultTxLevel contains transaction isolation level which will be used by default for Postgres.
Postgres SSL modes.
Postgres SSL modes.
Postgres SSL modes.
Postgres SSL modes.

# Variables

DefaultQueryDurationBuckets is default buckets into which observations of executing SQL queries are counted.

# Structs

Config represents a set of configuration parameters working with SQL databases.
MetricsCollector represents collector of metrics.
MetricsCollectorOpts represents an options for MetricsCollector.
MSSQLConfig represents a set of configuration parameters for working with MSSQL.
MySQLConfig represents a set of configuration parameters for working with MySQL.
Parameter represent DB connection parameter.
PostgresConfig represents a set of configuration parameters for working with Postgres.
SQLiteConfig represents a set of configuration parameters for working with SQLite.

# Type aliases

Dialect defines possible values for planned supported SQL dialects.
PostgresSSLMode defines possible values for Postgres sslmode connection parameter.