gorm

package module
v0.0.0-...-d6ccb58 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2022 License: LGPL-3.0-or-later Imports: 5 Imported by: 0

README

package: github.com/mikelue/go-misc/ioc/gorm GoDoc

Table of Content

This library depends on gorm, which provides some convenient features.

Features

Error-Free operator

DbTemplate and AssociationTemplate provides some error-free operators,
which would panic the caller with DbException.

DbTemplate

Usage example:

// Panic if something gets wrong
NewDbTemplate(db).Create(yourObject)
AssociationTemplate

Usage example:

// Panic if something gets wrong
NewAssociationTemplate(
    db.Model(parentObject).Association("SubObjects"),
).Find(&subObjects)

Test environment

This library uses gingkgo as underlying test framework.

The database used by tests is Sqlite.

Flags

Usage example:

# Run all tests
ginkgo -- -gorm.log-mode=true
# Run matched(by RegExp) tests
ginkgo --focus 'Create' -- -gorm.log-mode=true

gorm.log-mode - see gorm/DB.LogMode

  • true(1) - Verbose logging by gorm
  • false(0)(default) - For logging by gorm

Documentation

Overview

This package provides error-free methods over "*gorm.DB" object.

DbTemplate

You can use "NewDbTemplate()" to convert a "*gorm.DB" to use the error-free methods.

dbTmpl := NewDbTemplate(gormDb)
// Panic if something gets wrong
dbTmpl.Create(yourObj)

SoftTx

You can implements this interface to use "DbTemplate.SoftTransaction()".

"SoftTxFunc" is funcational style of "SoftTx".

DbException

The content of panic raised by this package is type of "DbException".

defer func() {
    if p := recover(); p != nil {
        dbException := p.(*DbException)

        // dbException.DetailError() - Source error/panic
        // dbException.GetCallerFile() - The source file of caller
        // dbException.GetCallerLine() - The line of caller in source file
    }
}()

// dbTmpl.Create(...)
// dbTmpl.Find(...)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AssociationTemplate

type AssociationTemplate interface {
	// As corresponding function of *gorm.Association
	Append(values ...interface{})
	// As corresponding function of *gorm.Association
	Clear()
	// As corresponding function of *gorm.Association
	Count() int
	// As corresponding function of *gorm.Association
	Delete(values ...interface{})
	// As corresponding function of *gorm.Association
	Find(value interface{})
	// As corresponding function of *gorm.Association
	Replace(values ...interface{})
}

Every function provided by this template would be PANIC with viable error after corresponding operation is executed.

func NewAssociationTemplate

func NewAssociationTemplate(association *gorm.Association) AssociationTemplate

type DbException

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

This exception implements "Error()/String()" interface to support error behaivor of GoLang

Example
db := exampleDb()

defer func() {
	if p := recover(); p != nil {
		dbException := p.(*DbException)

		fmt.Printf("DbException: Func[%s]. Content: %s",
			dbException.GetGormFuncName(),
			dbException.GetCause(),
		)
	}
}()

defer db.Close()
setupExampleSchema(db)

dbTmpl := NewDbTemplate(db)
dbTmpl.Create(&Company{Id: 6701, Name: "Green Inc."})
dbTmpl.Create(&Company{Id: 6702, Name: "Green Inc."})
Output:

DbException: Func[Create]. Content: UNIQUE constraint failed: ts_company.cp_name

func (*DbException) DetailError

func (self *DbException) DetailError() error

Builds the error with detailed information

func (*DbException) Error

func (self *DbException) Error() string

As output of "DetailError()"

func (*DbException) GetCallerFile

func (self *DbException) GetCallerFile() string

Gets the file name of caller

func (*DbException) GetCallerLine

func (self *DbException) GetCallerLine() int

Gets the file line of caller

func (*DbException) GetCause

func (self *DbException) GetCause() error

Gets the cause of error

func (*DbException) GetGormFuncName

func (self *DbException) GetGormFuncName() string

Gets the function/feature name of GORM

func (*DbException) String

func (self *DbException) String() string

As output of "DetailError()"

type DbTemplate

type DbTemplate interface {
	// Gets underlying object of *gorm.DB
	GetDb() *gorm.DB

	// As corresponding function of *gorm.DB
	Create(value interface{})
	// As corresponding function of *gorm.DB
	Delete(value interface{}, where ...interface{})
	// As corresponding function of *gorm.DB
	// Return values:
	// 	True - at least one row of data is found
	// 	False - nothing found
	First(out interface{}, where ...interface{}) bool
	// As corresponding function of *gorm.DB
	FirstOrCreate(out interface{}, where ...interface{})
	// As corresponding function of *gorm.DB
	FirstOrInit(out interface{}, where ...interface{})
	// As corresponding function of *gorm.DB
	Find(out interface{}, where ...interface{})
	// As corresponding function of *gorm.DB
	Related(value interface{}, foreignKeys ...string)
	// As corresponding function of *gorm.DB
	// Return values:
	// 	True - at least one row of data is found
	// 	False - nothing found
	Last(out interface{}, where ...interface{}) bool
	// As corresponding function of *gorm.DB
	Row() *sql.Row
	// As corresponding function of *gorm.DB
	Rows() *sql.Rows
	// As corresponding function of *gorm.DB
	Save(value interface{})
	// As corresponding function of *gorm.DB
	Scan(dest interface{})
	// As corresponding function of *gorm.DB
	ScanRows(rows *sql.Rows, result interface{})
	// As corresponding function of *gorm.DB
	Transaction(func(tx *gorm.DB))
	// As corresponding function of *gorm.DB
	Pluck(column string, value interface{})
	// Use returned value of "SoftTx.Tx(*gorm.DB)" to decide whether or not commit a transaction.
	// If something gets wrong, the transaction would be rollback either.
	SoftTransaction(SoftTx)
	// As corresponding function of *gorm.DB
	// Return values:
	// 	True - at least one row of data is found
	// 	False - nothing found
	Take(out interface{}, where ...interface{}) bool
	// As corresponding function of *gorm.DB
	Update(attrs ...interface{})
	// As corresponding function of *gorm.DB
	UpdateColumn(attrs ...interface{})
	// As corresponding function of *gorm.DB
	UpdateColumns(values interface{})
	// As corresponding function of *gorm.DB
	Updates(values interface{}, ignoreProtectedAttrs ...bool)
}

Every function provided by this template would be PANIC with viable error after corresponding operation is executed.

Example
db := exampleDb()

defer db.Close()
setupExampleSchema(db)

/**
 * Uses the template to perform operations to database
 */*/
tmpl := NewDbTemplate(db)
tmpl.Create(&Company{Id: 981, Name: "Green Inc.", EstablishTime: 1248954})

foundCompany := &Company{Id: 981}
tmpl.Take(foundCompany)
// :~)

fmt.Printf("Company: %s", foundCompany.Name)
Output:

Company: Green Inc.
Example (SoftTransaction)
db := exampleDb()

defer db.Close()
setupExampleSchema(db)

/**
 * Executes database operations in transaction
 */*/
NewDbTemplate(db).SoftTransaction(
	SoftTxFunc(func(db *gorm.DB) TxResult {
		dbTmpl := NewDbTemplate(db)

		dbTmpl.Create(&Company{Id: 4091, Name: "Yangmei Inc.", EstablishTime: 6644698})
		dbTmpl.Create(&Company{Id: 4092, Name: "Grapefruit Inc.", EstablishTime: 7086887})

		// Commits current transaction
		return TxCommit
	}),
)
// :~)

foundCompany := &Company{Id: 4092}
NewDbTemplate(db).Take(foundCompany)

fmt.Printf("Company: %s", foundCompany.Name)
Output:

Company: Grapefruit Inc.

func NewDbTemplate

func NewDbTemplate(targetDb *gorm.DB) DbTemplate

Constructs a wrapper over a *gorm.DB object

type SoftTx

type SoftTx interface {
	Tx(tx *gorm.DB) TxResult
}

The callback type used by "DbTemplate.SoftTransaction(SoftTx)"

func NewSoftTxWithContext

func NewSoftTxWithContext(
	softTxImpl SoftTx,
	ctx context.Context, opts *sql.TxOptions,
) SoftTx

Constructs a "SoftTx" with "context.Context" and "*sql.TxOptions"

Example
db := exampleDb()

defer db.Close()
setupExampleSchema(db)

/**
 * Executes database operations in transaction
 */*/
customizedTx := NewSoftTxWithContext(
	SoftTxFunc(func(db *gorm.DB) TxResult {
		dbTmpl := NewDbTemplate(db)

		dbTmpl.Create(&Company{Id: 1871, Name: "Yangmei Inc.", EstablishTime: 6644698})
		dbTmpl.Create(&Company{Id: 1872, Name: "Honeycrisp apple Inc.", EstablishTime: 7086887})

		// Commits current transaction
		return TxCommit
	}),
	context.Background(),
	&sql.TxOptions{Isolation: sql.LevelReadUncommitted},
)
NewDbTemplate(db).SoftTransaction(customizedTx)
// :~)

foundCompany := &Company{Id: 1872}
NewDbTemplate(db).Take(foundCompany)

fmt.Printf("Company: %s", foundCompany.Name)
Output:

Company: Honeycrisp apple Inc.

type SoftTxFunc

type SoftTxFunc func(*gorm.DB) TxResult

The functional type of "SoftTx"

func (SoftTxFunc) Tx

func (f SoftTxFunc) Tx(tx *gorm.DB) TxResult

Delegate the function "SoftTx.Tx(*gorm.DB)" to the fucntion self.

type TxResult

type TxResult int8

The result of transaction

const TxCommit TxResult = 1

Used to commit transaction

const TxRollback TxResult = 2

Used to rollback transaction

Jump to

Keyboard shortcuts

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