db

package
v0.0.3 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetDBFromCtx

func GetDBFromCtx(ctx context.Context) *gorm.DB

GetDBFromCtx try to get gorm.DB from context, if not found then return DB with context.Background

func IsInTransaction

func IsInTransaction(ctx context.Context) bool

IsInTransaction return true if current operation within a transaction

func Transaction

func Transaction(ctx context.Context, f func(context.Context) error) error

Transaction get gorm.DB from ctx and run Transaction Operation with ctx How to use:

	// 所有 db 操作的第一参数为 context.Context, 然后通过 ctx 读取 DB 对象
	if err := db.Transaction(context.Background(), func(ctx context.Context) error {
		if err := d.Create(ctx); err != nil {
			return err
		}

		d.Name = "123"
		return d.Update(ctx)
	}); err != nil {
		return
	}

 func (d *Domain) Create(ctx context.Context) error {
	  return GetDBFromCtx(ctx).Create(d).Error
 }

 func (d *Domain) Update(ctx context.Context) error {
	  return GetDBFromCtx(ctx).Updates(d).Error
 }

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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