In Java, it's pretty easy to switch between auto commit and manual commit of a database transaction. When I say easy, I mean it doesn't need to change the connection interface. Simply setAutoCommit to be true or false will switch the transaction between auto/manual mode. However, Go uses different connection interface, sql.DB for auto mode, and sql.Tx for manual mode. It's not a problem for a one off use. The problem is I have a framework which uses sql.DB to do the db work, now I want some of them to join my new transaction, and it seems to be not that easy without modifying the existing framework to accept sql.Tx. I am wondering if there is really not an easy way to do the auto/manual switch in Go?
Transactional databases are optimized for running production systems—everything from websites to banks to retail stores. These databases excel at reading and writing individual rows of data very quickly while maintaining data integrity.
Transaction. To perform a set of operations within a transaction, the general flow is as below. db.Transaction(func(tx *gorm.DB) error { // do some database operations in the transaction (use 'tx' from this point, not 'db') if err := tx.Create(&Animal{Name: "Giraffe"
Go supports all of the most common relational database management systems, including MySQL, Oracle, Postgres, SQL Server, SQLite, and more.
Without knowing more about which framework you are using, I don't think there is a way to do it without modifying the framework. You should really try to get the modifications you do included in the framework because the main problem here is that the framework you are using is designed poorly. When writing for a new language (specially a library or framework) you should get to know the conventions and design your software accordingly.
In go, it is not to hard to accomplish this functionality you just have to declared the Queryer
(or however you want to call it) interface like this:
type Queryer interface {
Query(string, ...interface{}) (*sql.Rows, error)
QueryRow(string, ...interface{}) *sql.Row
Prepare(string) (*sql.Stmt, error)
Exec(string, ...interface{}) (sql.Result, error)
}
This interface is implemented implicitly by the sql.DB
and the sql.Tx
so after declaring it, you just have to modify the functions/methods to accept the Queryer
type instead of a sql.DB
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With