gothinkster / golang-gin-realworld-example-app

Exemplary real world application built with Golang + Gin
https://realworld.io
MIT License
2.52k stars 497 forks source link

Why using transaction when query find? #20

Closed w4-hanggi closed 4 years ago

w4-hanggi commented 4 years ago

like this:

func FindOneArticle(condition interface{}) (ArticleModel, error) {
    db := common.GetDB()
    var model ArticleModel
    tx := db.Begin()
    tx.Where(condition).First(&model)
    tx.Model(&model).Related(&model.Author, "Author")
    tx.Model(&model.Author).Related(&model.Author.UserModel)
    tx.Model(&model).Related(&model.Tags, "Tags")
    err := tx.Commit().Error
    return model, err
}

Can someone tell me why using transaction in this part?

Conight commented 4 years ago

database transaction isolation levels

w4-hanggi commented 4 years ago

@Conight But there is no write operation, it's just select operation isn't it?

wangzitian0 commented 4 years ago

@w4-hanggi In relational database:

  1. one transaction commit is faster than multiple transactions.
  2. Reduce the dirty read. More information could be search database Read uncommitted, read committed, repeatable read, serializable
w4-hanggi commented 4 years ago

@wangzitian0 @Conight Can I remove the transaction?

I mean, there are only read(select) operations, I don't need rollback, I don't care whether the data changed during multiple operations.

I just want to show the article at that moment, because it is not a critical data, right?

And, does what you said means wrap multiple select operations in single transaction is faster than without transaction? I'm not sure about that. Will this behave differently in different databases, like: MySQL or Postgres (Because I'm using Postgresql)?

w4-hanggi commented 4 years ago

I have asked the author of gorm, and got the answer that there is no need for wrapping a transaction with multiple select operations.

Of course, if you want something about reducing dirty read, please go on.