goapartment

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2022 License: MIT Imports: 5 Imported by: 0

README

Goapartment

goapartment implements multi-tenancy database connection for golang

Installation

go get github.com/minhquang4334/goapartment

Usage

Open Tenant Connection

// mysql
db, err := sqlx.Open("mysql", dsn)
if err != nil {
  return "", err
}
apartment := goapartment.ProvideApartment(db)
conn, err := apartment.TenantExecConn(ctx, "tenantName")
if err != nil {
  return "", errors.New("can not open sqlx.Conn")
}
query := "SELECT DATABASE()"
row := conn.QueryRowContext(ctx, query)
var dbName string
if err := row.Scan(&dbName); err != nil {
  return "", err
}
return dbName, nil

Open Tenant Transaction

// mysql
db, err := sqlx.Open("mysql", dsn)
if err != nil {
  return "", err
}
apartment := goapartment.ProvideApartment(db)
tx, err := apartment.TenantExecTx(ctx, "tenantName", nil)
if err != nil {
  return "", errors.New("can not open sqlx.Conn")
}
query := "SELECT DATABASE()"
row := tx.QueryRowContext(ctx, query)
var dbName string
if err := row.Scan(&dbName); err != nil {
  _ = tx.Rollback()
  return "", err
}
if err = tx.Commit(); err != nil {
  return "", err
}
return dbName, nil

License

Distributed under the MIT License. See LICENSE for more information.

Acknowledgements

I acknowledge gratitude to the following resources in creating this repo

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDBIsRequired は sqlx.DBを期待するのに、nilが渡された
	ErrDBIsRequired = errors.New("sqlx.DB is required")

	// ErrTenantIsRequired is a error type, that raise when expect tenant name as parameter but recieved empty string.
	ErrTenantIsRequired = errors.New("Tenant is required")
)

Functions

This section is empty.

Types

type Apartment

type Apartment struct {
	DB *sqlx.DB
}

Apartment structure have a implemented of AparmentDB interface

func ProvideApartment

func ProvideApartment(db *sqlx.DB) (*Apartment, error)

ProvideApartment initialize a Apartment struct and return it

func (*Apartment) TenantExecConn added in v1.0.2

func (ap *Apartment) TenantExecConn(ctx context.Context, tenant string) (*sqlx.Conn, error)

TenantExecConn open an connection on tenant DB and return a instance of *sqlx.Conn when error is raised, an error must be returned

func (*Apartment) TenantExecTx added in v1.0.2

func (ap *Apartment) TenantExecTx(ctx context.Context, tenant string, txOptions *sql.TxOptions) (*sqlx.Tx, error)

TenantExecTx open an transaction on tenant DB and return a instance of *sqlx.Tx when error is raised, an error must be returned

Jump to

Keyboard shortcuts

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