Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prepare for publication #19

Merged
merged 1 commit into from
Nov 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 0 additions & 62 deletions .github/workflows/all.yaml

This file was deleted.

109 changes: 109 additions & 0 deletions .github/workflows/main.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
on:
push:
branches:
- main
- v1
pull_request:
branches:
- main
- v1
name: Test
env:
GO_TARGET_VERSION: 1.19
OS_TARGET: ubuntu-latest
jobs:
tests:
strategy:
matrix:
go-version:
# - '1.10' doesn't have go module
# - 1.11
# - 1.12 doesn't have errors pkg
- 1.13
- 1.14
- 1.15
- 1.16
- 1.17
- 1.18
- 1.19
os:
- ubuntu-latest
# - macos-latest
# - windows-latest
mongodb-version:
- '6.0'
runs-on: ${{ matrix.os }}
steps:
- name: Set environment by expression
run: |
echo "NEED_CODECOVERAGE=${{ matrix.go-version == env.GO_TARGET_VERSION && matrix.os == env.OS_TARGET }}" >> $GITHUB_ENV
- name: Checkout code
uses: actions/checkout@v3
- name: Install Go
uses: actions/setup-go@v3
with:
go-version: ${{ matrix.go-version }}
- uses: actions/cache@v3
with:
path: |
~/go/pkg/mod # Module download cache
~/.cache/go-build # Build cache (Linux)
~/Library/Caches/go-build # Build cache (Mac)
'%LocalAppData%\go-build' # Build cache (Windows)
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-

- name: Start MongoDB
if: ${{ fromJSON(env.NEED_CODECOVERAGE) }}
uses: supercharge/mongodb-github-action@1.8.0
with:
mongodb-version: ${{ matrix.mongodb-version }}
mongodb-replica-set: test-rs

- name: Tests
if: ${{ matrix.go-version != env.GO_TARGET_VERSION || matrix.os != env.OS_TARGET }}
run: make test

- name: Tests with real databases
if: ${{ fromJSON(env.NEED_CODECOVERAGE) }}
run: make test.coverage.with_real_db

- name: Code coverage data
if: ${{ fromJSON(env.NEED_CODECOVERAGE) }}
run: |
set -x
COVERAGE_TOTAL=`go tool cover -func=coverage.out | grep total | grep -Eo '[0-9]+\.[0-9]+'`
echo "COVERAGE_TOTAL=$COVERAGE_TOTAL" >> $GITHUB_ENV
- name: CodeCoverage the Badge
if: ${{ fromJSON(env.NEED_CODECOVERAGE) && github.ref == 'refs/heads/main' }}
uses: schneegans/dynamic-badges-action@v1.6.0
with:
auth: ${{ secrets.GIST_SECRET }}
gistID: ${{ secrets.GIST_ID }}
filename: ${{ secrets.GIST_FILENAME }}
label: coverage
message: ${{ env.COVERAGE_TOTAL }}%
valColorRange: ${{ env.COVERAGE_TOTAL }}
maxColorRange: 100
minColorRange: 0
# TODO turn on when repository will be published
# - uses: jandelgado/gcov2lcov-action@v1
# if: ${{ fromJSON(env.NEED_CODECOVERAGE) }}
# with:
# outfile: ./coverage.lcov
# - uses: romeovs/lcov-reporter-action@v0.2.16
# if: ${{ fromJSON(env.NEED_CODECOVERAGE) }}
# with:
# github-token: ${{ secrets.POST_COMMENT_TOKEN }}
# lcov-file: ./coverage.lcov
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
with:
go-version: ${{ env.GO_TARGET_VERSION }}
- uses: actions/checkout@v3
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
28 changes: 18 additions & 10 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,39 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [0.0.0] - 2022-10-24
## [1.0.0-beta] - 2022-11-05

### Added

- timeout and canceling of transaction
- badges.
- examples.
- test with real mongo db.

## [0.0.0] - 2022-10-20
## [1.0.0-beta] - 2022-10-24

### Added

- chained transaction
- timeout and canceling of transaction.

## [0.0.0] - 2022-10-17
## [1.0.0-beta] - 2022-10-20

### Added

- Propagation
- Settings
- chained transaction.

## [1.0.0-beta] - 2022-10-17

### Added

- propagation.
- settings.

## [0.0.0] - 2022-09-08

### Added

- Manager interface.
- Transaction interface.
- sqlx implementation.
- manager interface.
- transaction interface.
- mongo, sql implementations.

[0.0.0]: https://github.com/avito-tech/go-transaction-manager/
9 changes: 8 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
CVPKG=go list ./... | grep -v mocks | grep -v internal/
GO_TEST=go test `$(CVPKG)` -race
GO_TEST_WITH_REAL_DB=$(GO_TEST) --tags=with_real_db
COVERAGE_FILE="coverage.out"

test:
$(GO_TEST)

test.with_real_db:
$(GO_TEST_WITH_REAL_DB)

test.coverage:
$(GO_TEST) -covermode=atomic -coverprofile=$(COVERAGE_FILE)

test.coverage.with_real_db:
$(GO_TEST_WITH_REAL_DB) -covermode=atomic -coverprofile=$(COVERAGE_FILE)

fmt:
go fmt ./...

lint:
golangci-lint run -v
golangci-lint run -v --timeout=2m

generate:
go generate ./...
115 changes: 104 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
# Go transaction manager

[![Go Reference](https://pkg.go.dev/badge/github.com/avito-tech/go-transaction-manager.svg)](https://pkg.go.dev/github.com/github.com/avito-tech/go-transaction-manager)
[![Test Status](https://github.com/avito-tech/go-transaction-manager/actions/workflows/main.yaml/badge.svg)](https://github.com/avito-tech/go-transaction-manager/actions?query=branch%3Amain)
![Coverage Badge](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/maranqz/80b9d66a715738d2279ad93721986914/raw/badge.v1.json)
[![Go Report Card](https://goreportcard.com/badge/github.com/avito-tech/go-transaction-manager)](https://goreportcard.com/report/github.com/avito-tech/go-transaction-manager)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
<!-- #TODO add images
[![GoDoc][doc-img]][doc] [![Coverage Status][cov-img]][cov] ![test][test-img])
-->

Transaction manager is an abstraction to coordinate database transaction boundaries.

## Supported implementations

* [sqlx](https://github.com/jmoiron/sqlx) (Go 1.16)

<!-- #TODO:
* [sql](https://pkg.go.dev/database/sql) (Go 1.16)
* [mongo-go-driver](https://github.com/mongodb/mongo-go-driver) (Go 1.16)
-->
* [database/sql](https://pkg.go.dev/database/sql), [![go.dev sql docs](https://img.shields.io/badge/docs-sql-blue)](https://pkg.go.dev/https://github.com/avito-tech/go-transaction-manager/sql) (Go 1.13)
* [jmoiron/sqlx](https://github.com/jmoiron/sqlx), [![go.dev sqlx docs](https://img.shields.io/badge/docs-sqlx-blue)](https://pkg.go.dev/https://github.com/avito-tech/go-transaction-manager/sqlx) (Go 1.13)
* [mongo-go-driver](https://github.com/mongodb/mongo-go-driver), [![go.dev mong docs](https://img.shields.io/badge/docs-mongo-blue)](https://pkg.go.dev/https://github.com/avito-tech/go-transaction-manager/mongo) (Go 1.13)

## Installation

Expand All @@ -29,9 +27,104 @@ Compatibility beyond that is not guaranteed.

## Usage

Below is an example how to start transaction. Check [example_test.go](sqlx/example_test.go) for more usage.
**To use multiple transactions from different databases**, you need to set CtxKey in [Settings](trm/settings.go) by [WithCtxKey](trm/settings/option.go).

**For nested transactions with different transaction managers**, you need to use [ChainedMW](trm/manager/chain.go) ([docs](https://pkg.go.dev/github.com/github.com/avito-tech/go-transaction-manager)).

### Examples

* [database/sql](sql/example_test.go)
* [jmoiron/sqlx](sqlx/example_test.go)
* [mongo-go-driver](mongo/example_test.go)

Below is an example how to start usage to get ideal repository pattern.

<!-- #TODO: add example -->
```go
package main

import (
"context"
"fmt"

"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"

trmsqlx "github.com/avito-tech/go-transaction-manager/sqlx"
"github.com/avito-tech/go-transaction-manager/trm/manager"
)

func main() {
db, err := sqlx.Open("sqlite3", "file:test?mode=memory")
checkErr(err)
defer db.Close()

sqlStmt := `CREATE TABLE IF NOT EXISTS user (user_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT);`
_, err = db.Exec(sqlStmt)
checkErr(err, sqlStmt)

r := newRepo(db, trmsqlx.DefaultCtxGetter)
ctx := context.Background()
trManager := manager.Must(trmsqlx.NewDefaultFactory(db))
u := &user{Username: "username"}

err = trManager.Do(ctx, func(ctx context.Context) error {
checkErr(r.Save(ctx, u))

return trManager.Do(ctx, func(ctx context.Context) error {
u.Username = "new_username"
return r.Save(ctx, u)
})
})
checkErr(err)

userFromDB, err := r.GetByID(ctx, u.ID)
checkErr(err)

fmt.Println(userFromDB)
}

func checkErr(err error, args ...interface{}) {
if err != nil {
panic(fmt.Sprint(append([]interface{}{err}, args...)...))
}
}

type repo struct {
db *sqlx.DB
getter *trmsqlx.CtxGetter
}

func newRepo(db *sqlx.DB, c *trmsqlx.CtxGetter) *repo {
return &repo{db: db, getter: c}
}

type user struct {
ID int64 `db:"user_id"`
Username string `db:"username"`
}

func (r *repo) GetByID(ctx context.Context, id int64) (*user, error) {
query := "SELECT * FROM user WHERE user_id = ?;"
u := user{}

return &u, r.getter.DefaultTrOrDB(ctx, r.db).GetContext(ctx, &u, r.db.Rebind(query), id)
}

func (r *repo) Save(ctx context.Context, u *user) error {
query := `UPDATE user SET username = :username WHERE user_id = :user_id;`
if u.ID == 0 {
query = `INSERT INTO user (username) VALUES (:username);`
}

res, err := sqlx.NamedExecContext(ctx, r.getter.DefaultTrOrDB(ctx, r.db), r.db.Rebind(query), u)
if err != nil {
return err
} else if u.ID != 0 {
return nil
} else if u.ID, err = res.LastInsertId(); err != nil {
return err
}

return err
}
```
Loading