Should I commit or rollback a read transaction?

后端 未结 12 1198
臣服心动
臣服心动 2020-12-02 10:42

I have a read query that I execute within a transaction so that I can specify the isolation level. Once the query is complete, what should I do?

  • Commit the tr
12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 11:19

    Consider nested transactions.

    Most RDBMSes do not support nested transactions, or try to emulate them in a very limited way.

    For example, in MS SQL Server, a rollback in an inner transaction (which is not a real transaction, MS SQL Server just counts transaction levels!) will rollback the everything which has happened in the outmost transaction (which is the real transaction).

    Some database wrappers might consider a rollback in an inner transaction as an sign that an error has occured and rollback everything in the outmost transaction, regardless whether the outmost transaction commited or rolled back.

    So a COMMIT is the safe way, when you cannot rule out that your component is used by some software module.

    Please note that this is a general answer to the question. The code example cleverly works around the issue with an outer transaction by opening a new database connection.

    Regarding performance: depending on the isolation level, SELECTs may require a varying degree of LOCKs and temporary data (snapshots). This is cleaned up when the transaction is closed. It does not matter whether this is done via COMMIT or ROLLBACK. There might be a insignificant difference in CPU time spent - a COMMIT is probably faster to parse than a ROLLBACK (two characters less) and other minor differences. Obviously, this is only true for read-only operations!

    Totally not asked for: another programmer who might get to read the code might assume that a ROLLBACK implies an error condition.

提交回复
热议问题