You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am using GIN framework and Gorm to write restful APIs with Clean Architecture pattern in different layers (controller, usecase, repository, domain) but facing a problem that single connection use in all functions. Once I use transaction begin and commit/ rollback in one function. Then client request another api will cause sql transaction has already been committed or rolled back (I know that a transaction can be only used once) so how to handle in this use case? Thanks
Case:
call api/dummy/update
call api/dummy/list
Result: app/repositories/dummy_repository.go:46 sql: transaction has already been committed or rolled back
main.go
package main
import (
"myapp/app/di"
"myapp/app/repositories/db"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
func main() {
// Set the router as the default one provided by Gin
route_engine = gin.Default()
// initial database connection - mysql
dbConn := db.ConnectMysqlGormDatabase()
// depdency injection
di.InitializeAPIs(dbConn, route_engine)
// Start serving the application
route_engine.Run(viper.GetString("server.address"))
}
Can you provide a simpler repro code? Or put the appeal file into a git repository and make sure it works.
Actually, I don't have enough time to watch the business code if you don't do that.
This has nothing to do with gorm. In fact, you should not reuse dummyRepo. First, WithTrx will modify the referenced db instance. Usually, the http framework will create goroutine for each connection, which will also cause data race.
Your Question
I am using GIN framework and Gorm to write restful APIs with Clean Architecture pattern in different layers (controller, usecase, repository, domain) but facing a problem that single connection use in all functions. Once I use transaction begin and commit/ rollback in one function. Then client request another api will cause sql transaction has already been committed or rolled back (I know that a transaction can be only used once) so how to handle in this use case? Thanks
Case:
Result:
app/repositories/dummy_repository.go:46 sql: transaction has already been committed or rolled back
main.go
dbconnection.go
// for connect mysql
di.go
// declare all repositories, usecases, controllers and routes
dummy_handler.go
// controller
dummy_usecase.go
// dummy_repository.go
The document you expected this should be explained
Expected answer
The text was updated successfully, but these errors were encountered: