Should I commit or rollback a read transaction?

后端 未结 12 1177
臣服心动
臣服心动 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:36

    ROLLBACK is mostly used in case of an error or exceptional circumstances, and COMMIT in the case of successful completion.

    We should close transactions with COMMIT (for success) and ROLLBACK (for failure), even in the case of read-only transactions where it doesn't seem to matter. In fact it does matter, for consistency and future-proofing.

    A read-only transaction can logically "fail" in many ways, for example:

    • a query does not return exactly one row as expected
    • a stored procedure raises an exception
    • data fetched is found to be inconsistent
    • user aborts the transaction because it's taking too long
    • deadlock or timeout

    If COMMIT and ROLLBACK are used properly for a read-only transaction, it will continue to work as expected if DB write code is added at some point, e.g. for caching, auditing or statistics.

    Implicit ROLLBACK should only be used for "fatal error" situations, when the application crashes or exits with an unrecoverable error, network failure, power failure, etc.

提交回复
热议问题