Skip to content

Commit

Permalink
Merge pull request #4 from vasayxtx/rename-package-db-to-dbkit
Browse files Browse the repository at this point in the history
Rename root package: db -> dbkit
  • Loading branch information
vasayxtx authored Oct 8, 2024
2 parents 5a84a73 + bb3d3a6 commit 0a5a7a5
Show file tree
Hide file tree
Showing 35 changed files with 159 additions and 160 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## Structure

### `/`
Package `db` provides helpers for working with different SQL databases (MySQL, PostgreSQL, SQLite and MSSQL).
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).
Expand Down
2 changes: 1 addition & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/

package db
package dbkit

import (
"database/sql"
Expand Down
2 changes: 1 addition & 1 deletion config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/

package db
package dbkit

import (
"bytes"
Expand Down
2 changes: 1 addition & 1 deletion constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/

package db
package dbkit

import (
"database/sql"
Expand Down
2 changes: 1 addition & 1 deletion db.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/

package db
package dbkit

import (
"context"
Expand Down
2 changes: 1 addition & 1 deletion db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/

package db
package dbkit

import (
"context"
Expand Down
6 changes: 3 additions & 3 deletions dbrutil/dbrutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ import (

// Open opens database (using dbr query builder) with specified configuration parameters
// and verifies (if ping argument is true) that connection can be established.
func Open(cfg *db.Config, ping bool, eventReceiver dbr.EventReceiver) (*dbr.Connection, error) {
func Open(cfg *dbkit.Config, ping bool, eventReceiver dbr.EventReceiver) (*dbr.Connection, error) {
driver, dsn := cfg.DriverNameAndDSN()
conn, err := dbr.Open(driver, dsn, eventReceiver)
if err != nil {
return nil, err
}

if err := db.InitOpenedDB(conn.DB, cfg, ping); err != nil {
if err := dbkit.InitOpenedDB(conn.DB, cfg, ping); err != nil {
return nil, err
}

Expand Down Expand Up @@ -183,7 +183,7 @@ func (s *RetryableTxSession) DoInTx(ctx context.Context, fn func(runner dbr.Sess
_ = s.log.EventErrKv("backoff", err, map[string]string{"duration_ms": strconv.Itoa(int(d.Milliseconds()))})
}
}
return retry.DoWithRetry(ctx, s.policy, db.GetIsRetryable(s.Driver()), notify, func(ctx context.Context) error {
return retry.DoWithRetry(ctx, s.policy, dbkit.GetIsRetryable(s.Driver()), notify, func(ctx context.Context) error {
return s.TxSession.DoInTx(ctx, fn)
})
}
Expand Down
14 changes: 7 additions & 7 deletions dbrutil/dbrutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ INSERT INTO users(name) VALUES("Albert"), ("Bob"), ("John"), ("Sam"), ("Sam");
func openAndSeedDB(t *testing.T) *dbr.Connection {
t.Helper()

cfg := &db.Config{
Dialect: db.DialectSQLite,
SQLite: db.SQLiteConfig{Path: "file::memory:?cache=shared"},
cfg := &dbkit.Config{
Dialect: dbkit.DialectSQLite,
SQLite: dbkit.SQLiteConfig{Path: "file::memory:?cache=shared"},
MaxOpenConns: 1,
MaxIdleConns: 1,
ConnMaxLifetime: 0,
Expand Down Expand Up @@ -146,25 +146,25 @@ func TestDbrQueryMetricsEventReceiver_TimingKv(t *testing.T) {
}()

t.Run("metrics for query with wrong annotation are not collected", func(t *testing.T) {
mc := db.NewMetricsCollector()
mc := dbkit.NewMetricsCollector()
metricsEventReceiver := NewQueryMetricsEventReceiver(mc, "query_")
dbSess := dbConn.NewSession(metricsEventReceiver)

countUsersByName(t, dbSess, "count_users_by_name", "Sam", 2)

labels := prometheus.Labels{db.MetricsLabelQuery: "count_users_by_name"}
labels := prometheus.Labels{dbkit.MetricsLabelQuery: "count_users_by_name"}
hist := mc.QueryDurations.With(labels).(prometheus.Histogram)
testutil.RequireSamplesCountInHistogram(t, hist, 0)
})

t.Run("metrics for query are collected", func(t *testing.T) {
mc := db.NewMetricsCollector()
mc := dbkit.NewMetricsCollector()
metricsEventReceiver := NewQueryMetricsEventReceiver(mc, "query_")
dbSess := dbConn.NewSession(metricsEventReceiver)

countUsersByName(t, dbSess, "query_count_users_by_name", "Sam", 2)

labels := prometheus.Labels{db.MetricsLabelQuery: "query_count_users_by_name"}
labels := prometheus.Labels{dbkit.MetricsLabelQuery: "query_count_users_by_name"}
hist := mc.QueryDurations.With(labels).(prometheus.Histogram)
testutil.RequireSamplesCountInHistogram(t, hist, 1)
})
Expand Down
8 changes: 4 additions & 4 deletions dbrutil/metric.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ type QueryMetricsEventReceiverOpts struct {
// To be collected SQL query should be annotated (comment starting with specified prefix).
type QueryMetricsEventReceiver struct {
*dbr.NullEventReceiver
metricsCollector *db.MetricsCollector
metricsCollector *dbkit.MetricsCollector
annotationPrefix string
annotationModifier func(string) string
}

// NewQueryMetricsEventReceiverWithOpts creates a new QueryMetricsEventReceiver with additinal options.
func NewQueryMetricsEventReceiverWithOpts(mc *db.MetricsCollector, options QueryMetricsEventReceiverOpts) *QueryMetricsEventReceiver {
func NewQueryMetricsEventReceiverWithOpts(mc *dbkit.MetricsCollector, options QueryMetricsEventReceiverOpts) *QueryMetricsEventReceiver {
return &QueryMetricsEventReceiver{
metricsCollector: mc,
annotationPrefix: options.AnnotationPrefix,
Expand All @@ -40,7 +40,7 @@ func NewQueryMetricsEventReceiverWithOpts(mc *db.MetricsCollector, options Query
}

// NewQueryMetricsEventReceiver creates a new QueryMetricsEventReceiver.
func NewQueryMetricsEventReceiver(mc *db.MetricsCollector, annotationPrefix string) *QueryMetricsEventReceiver {
func NewQueryMetricsEventReceiver(mc *dbkit.MetricsCollector, annotationPrefix string) *QueryMetricsEventReceiver {
options := QueryMetricsEventReceiverOpts{
AnnotationPrefix: annotationPrefix,
}
Expand All @@ -54,6 +54,6 @@ func (er *QueryMetricsEventReceiver) TimingKv(eventName string, nanoseconds int6
if annotation == "" {
return
}
labels := prometheus.Labels{db.MetricsLabelQuery: annotation}
labels := prometheus.Labels{dbkit.MetricsLabelQuery: annotation}
er.metricsCollector.QueryDurations.With(labels).Observe(time.Duration(nanoseconds).Seconds())
}
8 changes: 4 additions & 4 deletions dbrutil/retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import (

// Test that retriable errors stays retriable even wrapped in Tx structures
func TestTxErrorsIsRetriable(t *testing.T) {
retriable := []db.PostgresErrCode{
db.PgxErrCodeDeadlockDetected,
db.PgxErrCodeSerializationFailure,
retriable := []dbkit.PostgresErrCode{
dbkit.PgxErrCodeDeadlockDetected,
dbkit.PgxErrCodeSerializationFailure,
}

mkerr := func(code string) []error {
Expand All @@ -34,7 +34,7 @@ func TestTxErrorsIsRetriable(t *testing.T) {
}
}

check := db.GetIsRetryable(&pg.Driver{})
check := dbkit.GetIsRetryable(&pg.Driver{})

for _, c := range retriable {
for _, err := range mkerr(string(c)) {
Expand Down
16 changes: 8 additions & 8 deletions distrlock/db_lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ type DBManagerOpts struct {
}

// NewDBManager creates new distributed lock manager that uses SQL database as a backend.
func NewDBManager(dialect db.Dialect) (*DBManager, error) {
func NewDBManager(dialect dbkit.Dialect) (*DBManager, error) {
return NewDBManagerWithOpts(dialect, DBManagerOpts{TableName: defaultTableName})
}

// NewDBManagerWithOpts is a more configurable version of the NewDBManager.
func NewDBManagerWithOpts(dialect db.Dialect, opts DBManagerOpts) (*DBManager, error) {
func NewDBManagerWithOpts(dialect dbkit.Dialect, opts DBManagerOpts) (*DBManager, error) {
q, err := newDBQueries(dialect, opts.TableName)
if err != nil {
return nil, err
Expand Down Expand Up @@ -136,7 +136,7 @@ func (l *DBLock) DoExclusively(
logger log.FieldLogger,
fn func(ctx context.Context) error,
) error {
if acquireLockErr := db.DoInTx(ctx, dbConn, func(tx *sql.Tx) error {
if acquireLockErr := dbkit.DoInTx(ctx, dbConn, func(tx *sql.Tx) error {
return l.Acquire(ctx, tx, lockTTL)
}); acquireLockErr != nil {
return acquireLockErr
Expand All @@ -148,7 +148,7 @@ func (l *DBLock) DoExclusively(
// If the ctx is canceled, we should be able to release the lock.
releaseCtx, releaseCtxCancel := context.WithTimeout(context.Background(), releaseTimeout)
defer releaseCtxCancel()
if releaseLockErr := db.DoInTx(releaseCtx, dbConn, func(tx *sql.Tx) error {
if releaseLockErr := dbkit.DoInTx(releaseCtx, dbConn, func(tx *sql.Tx) error {
return l.Release(releaseCtx, tx)
}); releaseLockErr != nil {
logger.Error("failed to release db lock", log.Error(releaseLockErr))
Expand All @@ -172,7 +172,7 @@ func (l *DBLock) DoExclusively(
case <-periodicalExtensionDone:
return
case <-ticker.C:
if extendLockErr := db.DoInTx(ctx, dbConn, func(tx *sql.Tx) error {
if extendLockErr := dbkit.DoInTx(ctx, dbConn, func(tx *sql.Tx) error {
return l.Extend(ctx, tx)
}); extendLockErr != nil {
logger.Error("failed to extend db lock", log.Error(extendLockErr))
Expand Down Expand Up @@ -223,9 +223,9 @@ type dbQueries struct {
intervalMaker func(interval time.Duration) string
}

func newDBQueries(dialect db.Dialect, tableName string) (dbQueries, error) {
func newDBQueries(dialect dbkit.Dialect, tableName string) (dbQueries, error) {
switch dialect {
case db.DialectPostgres, db.DialectPgx:
case dbkit.DialectPostgres, dbkit.DialectPgx:
return dbQueries{
createTable: fmt.Sprintf(postgresCreateTableQuery, tableName),
dropTable: fmt.Sprintf(postgresDropTableQuery, tableName),
Expand All @@ -235,7 +235,7 @@ func newDBQueries(dialect db.Dialect, tableName string) (dbQueries, error) {
extendLock: fmt.Sprintf(postgresExtendLockQuery, tableName),
intervalMaker: postgresMakeInterval,
}, nil
case db.DialectMySQL:
case dbkit.DialectMySQL:
return dbQueries{
createTable: fmt.Sprintf(mySQLCreateTableQuery, tableName),
dropTable: fmt.Sprintf(mySQLDropTableQuery, tableName),
Expand Down
Loading

0 comments on commit 0a5a7a5

Please sign in to comment.