go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.93k stars 3.93k forks source link

Transaction using DBResolver (two databases) #4002

Open anshuljhawar opened 3 years ago

anshuljhawar commented 3 years ago

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?

jinzhu commented 3 years ago

sorry, it is not supported now.

anshuljhawar commented 3 years ago

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

SantoshSah commented 3 years ago

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

github-actions[bot] commented 3 years ago

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

anshuljhawar commented 3 years ago

@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?

github-actions[bot] commented 3 years ago

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

bruce0205 commented 2 years ago

@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.

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
github-actions[bot] commented 2 years ago

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

github-actions[bot] commented 1 year ago

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