SQL transaction wrapper on golang

TxWrapper

TxWrapper is a sql transaction wrapper. It helps to exclude writing code for rollback and commit commands.

Usage

import (
    "context"
    "database/sql"
    "fmt"
    "io/ioutil"
    "os"

    _ "github.com/mattn/go-sqlite3"
    "github.com/imega/txwrapper"
)

func main() {
    file, err := ioutil.TempFile("", "db")
    if err != nil {
        log.Fatalf("failed to create tmp file, %w", err)
    }

    filename := file.Name()
    if err := file.Close(); err != nil {
        log.Fatalf("failed to close tmp file, %w", err)
    }

    db, err := sql.Open("sqlite3", filename)
    if err != nil {
        log.Fatalf("failed to open db, %w", err)
    }

    ctx := context.Background()
    w := txwrapper.New(db)
    err := w.Transaction(ctx, nil, func(ctx context.Context, tx *sql.Tx) error {
        if err := createEmailTable(ctx, tx); err != nil {
            return err
        }

        if err := addEmail(ctx, tx, "[email protected]"); err != nil {
            return err
        }

        return nil
    })
    if err != nil {
        log.Fatalf("failed to open db, %w", err)
    }

    errDB := db.Close()
    if err := os.Remove(filename); err != nil || errDB != nil {
        log.Fatalf("failed to close db or remove tmp file, %w, %w", errDB, err)
    }
}

func createEmailTable(ctx context.Context, tx *sql.Tx) error {
    q := `CREATE TABLE IF NOT EXISTS email (
        email VARCHAR(64) NOT NULL
    )`

    if _, err := tx.ExecContext(ctx, q); err != nil {
        return fmt.Errorf("failed to execute query, %w", err)
    }

    return nil
}

func addEmail(ctx context.Context, tx *sql.Tx, email string) error {
    q := `insert into email (email) values (?)`

    if _, err := tx.ExecContext(ctx, q, email); err != nil {
        return fmt.Errorf("failed to execute query, %w", err)
    }

    return nil
}
Owner
Similar Resources

Simple SQL escape and format for golang

sqlstring Simple SQL escape and format Escaping sql values //Format sql := sqlstring.Format("select * from users where name=? and age=? limit ?,?", "t

Sep 4, 2022

BigQuery database/sql golang driver

BigQuery SQL Driver This library is compatible with Go 1.17+ Please refer to CHA

Dec 7, 2022

Spansqlx - Spanner sql pkgs with golang

spansqlx spanner sql pkgs install go get github.com/reiot777/spansqlx usage Bel

Jan 15, 2022

Golang REST Layer SQL Storage Handler

This REST Layer resource storage backend stores data in a SQL Database using database/sql.

Feb 15, 2022

Database wrapper that manage read write connections

rwdb Database wrapper that manage read write connections Install go get github.com/andizzle/rwdb Create connections package main import "github.com/

Dec 10, 2022

Simple pgx wrapper to execute and scan query results

pig Simple pgx wrapper to execute and scan query results. Features All-in-one tool; Simple transactions management: You can set idle_in_transaction_se

Dec 5, 2022

A database connection wrapper to cache prepared statements by transforming queries to use with array arguments.

sqlpp sqlpp is a sql(MySQL and PostgreSQL) database connection wrapper to cache prepared statements by transforming queries ("...in (?)...", []) to us

Feb 9, 2022

Go package for sharding databases ( Supports every ORM or raw SQL )

Go package for sharding databases ( Supports every ORM or raw SQL )

Octillery Octillery is a Go package for sharding databases. It can use with every OR Mapping library ( xorm , gorp , gorm , dbr ...) implementing data

Dec 16, 2022

Prep finds all SQL statements in a Go package and instruments db connection with prepared statements

Prep Prep finds all SQL statements in a Go package and instruments db connection with prepared statements. It allows you to benefit from the prepared

Dec 10, 2022
a lightweight distributed transaction management service, support xa tcc saga
a lightweight distributed transaction management service, support xa tcc saga

a lightweight distributed transaction management service, support xa tcc saga

Dec 29, 2022
Otelsql - OpenTelemetry SQL database driver wrapper for Go
Otelsql - OpenTelemetry SQL database driver wrapper for Go

OpenTelemetry SQL database driver wrapper for Go Add a OpenTelemetry wrapper to

Dec 15, 2022
Package dbi implements an experimental database/sql wrapper.

dbi Package dbi implements a database/sql wrapper. This is an EXPERIMENTAL package used for experimenting. Installation The recommended way to install

Feb 8, 2022
write APIs using direct SQL queries with no hassle, let's rethink about SQL

SQLer SQL-er is a tiny portable server enables you to write APIs using SQL query to be executed when anyone hits it, also it enables you to define val

Jan 7, 2023
Parses a file and associate SQL queries to a map. Useful for separating SQL from code logic

goyesql This package is based on nleof/goyesql but is not compatible with it any more. This package introduces support for arbitrary tag types and cha

Oct 20, 2021
Go-sql-reader - Go utility to read the externalised sql with predefined tags

go-sql-reader go utility to read the externalised sql with predefined tags Usage

Jan 25, 2022
a golang library for sql builder

Gendry gendry is a Go library that helps you operate database. Based on go-sql-driver/mysql, it provides a series of simple but useful tools to prepar

Dec 26, 2022
Fluent SQL generation for golang

Squirrel is "complete". Bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork

Dec 29, 2022
convert sql to elasticsearch DSL in golang(go)

_____ _ _ ____ _____ ___ ____ ____ ___ _ | ____| | / \ / ___|_ _|_ _|/ ___|/ ___| / _ \ | | | _| | | / _ \ \___ \ |

Jan 7, 2023
GoTSQL : A Better Way to Organize SQL codebase using Templates in Golang

GoTSQL - A Better Way to Organize SQL codebase using Templates in Golang Installation through Go Get command $ go get github.com/migopsrepos/gotsql In

Aug 17, 2022