GoooQo v0.2.3
HomeGitHubDemo
English
English
  • Introduction
  • Quickstart
  • API
    • Connection
    • Transaction
    • CRUD
    • Association Service
  • Entity Mapping
    • Entity Object
    • Related Entities
  • Query Mapping
    • Query Object
      • Predicate-Suffix Field
      • Logic-Suffix Field
      • Subquery Field
      • E-R Query Field
      • Custom Condition Field
    • Page Query
  • Aggregate Query
    • View Object
    • Having
    • Natural Join
    • Outer Join
    • Nested View
  • Advanced
    • Dialect
    • Locking
  • Related Resources
    • Articles
      • From ORM to OQM: An Object-Only SQL Construction Solution
      • Introduction to GoooQo
      • How to express `select * from user where id = ? or name = ? and age = ?` in GoooQo
Powered by GitBook
On this page
  • Definition
  • Usages

Was this helpful?

Edit on GitHub
  1. API

Transaction

Definition

After creating the database connection, we use the database connection to create a transaction manager.

Transaction management in GoooQo is accomplished through the cooperation of TransactionManager and TransactionContext (TC for short).

package core

import (
	"context"
	"database/sql/driver"
)

type TransactionManager interface {
	GetClient() any
	StartTransaction(ctx context.Context) (TransactionContext, error)
	SubmitTransaction(ctx context.Context, callback func(tc TransactionContext) error) error
}

type TransactionContext interface {
	context.Context
	driver.Tx
	Parent() context.Context
	SavePoint(name string) error
	RollbackTo(name string) error
}

The method TransactionManager#StartTransaction is responsible for starting a transaction and returning TC; TC combines driver.Tx and is responsible for transaction commit and rollback.

The TxDataAccess interface combines TransactionManager and DataAccess, which can conveniently manage transactions while providing the database operations.

type TxDataAccess[E Entity] interface {
	TransactionManager
	DataAccess[E]
}

Usages

Use StartTransaction to start a transaction and manually commit or rollback the transaction:

tc, err := userDataAccess.StartTransaction(ctx)
userQuery := UserQuery{ScoreLt: P(80)}
cnt, err := userDataAccess.DeleteByQuery(tc, userQuery)
if err != nil {
	err = RollbackFor(tc, err)
	return 0
}
err = tc.Commit()
return cnt

Or use SubmitTransaction to submit the transaction via callback:

err := tm.SubmitTransaction(ctx, func(tc TransactionContext) (err error) {
    // transaction body
    return
})
PreviousConnectionNextCRUD

Last updated 8 months ago

Was this helpful?