txdriver

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2020 License: MIT Imports: 7 Imported by: 0

README

txdriver

txdriver (pronounced: taxi driver) wraps a database connection in a transaction, so you can have clean database testing against a real database. Currently only works for MySQL.

Alternatives

go-txdb

Documentation

Overview

Package txdriver implements transactional isolation for SQL database connections.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type TransactionDBCreator

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

TransactionDBCreator creates DB instances that are scoped to a transaction.

func FromConnector

func FromConnector(ctx context.Context, connector driver.Connector) (*TransactionDBCreator, error)

FromConnector creates a TransactionDBCreator from a Connector

Example
package main

import (
	"context"
	"database/sql"
	"fmt"
	"math/rand"
	"time"

	"github.com/go-sql-driver/mysql"
)

func init() {
	rand.Seed(time.Now().Unix())
}

func main() {
	ctx := context.TODO()
	testDatabase := fmt.Sprintf("test_db_%d", rand.Int63())

	conf := mysql.NewConfig()
	conf.Addr = "127.0.0.1:14123"
	conf.User = "root"
	conf.MultiStatements = true

	createConn, _ := mysql.NewConnector(conf)
	createDB := sql.OpenDB(createConn)
	statement := fmt.Sprintf(`CREATE DATABASE %s`, testDatabase)
	createDB.ExecContext(ctx, statement)
	createDB.Close()

	conf.DBName = testDatabase
	conn, _ := mysql.NewConnector(conf)

	createDB = sql.OpenDB(conn)
	createDB.ExecContext(ctx, `CREATE TABLE users (id BIGINT PRIMARY KEY AUTO_INCREMENT)`)
	defer func() {
		defer createDB.Close()
		createDB.ExecContext(ctx, fmt.Sprintf("DROP DATABASE %s", testDatabase))
	}()

	txdb, _ := FromConnector(ctx, conn)

	db, _ := txdb.DB(ctx)
	db.Exec("INSERT INTO users VALUES ()")

	var n int
	db.QueryRow("SELECT COUNT(*) FROM users").Scan(&n)
	fmt.Println(n)
	db.Close()

	db, _ = txdb.DB(ctx)
	db.QueryRow("SELECT COUNT(*) FROM users").Scan(&n)
	fmt.Println(n)
	db.Close()

}
Output:

1
0

func FromDriver

func FromDriver(ctx context.Context, d driver.Driver, dsn string) (*TransactionDBCreator, error)

FromDriver creates a TransactionDBCreator from a driver.Driver

func (*TransactionDBCreator) DB

DB creates an *sql.DB that uses the transaction connection. Only one DB is created at any time, this is to ensure that only one test is interacting with the database at any moment.

Jump to

Keyboard shortcuts

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