Your Question

During the first transaction, make a delete query twice and commit once. An error occurs when performing a query afterwards, and print error "invalid transaction"

This is my example source.

// execute delete query, not commit.
func (ar *Artist) DeleteArtistOne(trx *gorm.DB) error {
    if err := trx.Where(&models.Image{UID: ar.ImageUID}).Delete(&models.Image{}).Error; err != nil {
        return errors.Wrap(err, "delete image all")
    }

    if err := trx.Where(&models.Artist{UID: ar.UID}).Delete(&models.Artist{}).Error; err != nil {
        return errors.Wrap(err, "delete artist one")
    }

    return nil
}

// after delete query, commit one time
trx := rdbms.GetQuery(container.AppContainer)
if err := artist.DeleteArtistOne(trx); err != nil {
        log.Err.Printf("%+v", err)
        trx.Rollback()
        return
}

trx.Commit()

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: a631807682

Did you use trx.Begin?

Comment From: baiyutang

see docs https://gorm.io/docs/transactions.html 企业微信截图_17068423422362

// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
ErrInvalidTransaction = errors.New("invalid transaction")

// Rollback rollbacks the changes in a transaction
func (db *DB) Rollback() *DB {
    if committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil {
        if !reflect.ValueOf(committer).IsNil() {
            db.AddError(committer.Rollback())
        }
    } else {
        db.AddError(ErrInvalidTransaction)
    }
    return db
}

Comment From: baiyutang

this issue can be closed.