Your Question

I am trying to use transaction in a sharded database. So I have two databases master and shard1.

Following code is being used to start the transaction

// tx := repo.database.Begin() // transaction to be used for master database
tx := repo.database.Clauses(dbresolver.Use("shard1"), dbresolver.Write).Begin()

But still this transaction is creating entries in the master database.

The document you expected this should be explained

https://gorm.io/docs/dbresolver.html

Expected answer

Transaction should be allowed separately for both master and shard1

Are transactions allowed only in one database? Or can we have transactions for any database, is there a different syntax/way to achieve this?

Comment From: jinzhu

sorry, it is not supported now.

Comment From: anshuljhawar

@jinzhu thanks! .. any plans to pick it up soon?

Comment From: SantoshSah

@jinzhu Any update on this? Or any work around while using multiple databases and want to have transaction?

Comment From: github-actions[bot]

This issue has been automatically marked as stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 30 days

Comment From: anshuljhawar

@jinzhu ... Looking at the code found this piece of code in plugin -> dbresolver-> callbacks.go

func (dr *DBResolver) switchSource(db *gorm.DB) {
    if !isTransaction(db.Statement.ConnPool) {
        db.Statement.ConnPool = dr.resolve(db.Statement, Write)
    }
}

Is there any specific reason why switching source is disabled during a transaction?

Comment From: github-actions[bot]

This issue has been automatically marked as stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 30 days

Comment From: bruce0205

@jinzhu Any update on this? Or any work around while using multiple databases and want to have transaction?

I used dblink as my work around solution for mysql.

go= tx := db.Begin() if err := tx.Table(os.Getenv("app_db1") + ".test").Create(&test1).Error; err != nil { tx.Rollback() return err } if err := tx.Table(os.Getenv("app_db2") + ".test").Create(&test2).Error; err != nil { tx.Rollback() return err } tx.Commit() return nil

Comment From: github-actions[bot]

This issue has been automatically marked as stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 30 days

Comment From: github-actions[bot]

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days

Comment From: jinzhu

this should be supported for a while.