View executes a function within the context of a managed read-only transaction. Any error that is returned from the function is returned from the View() method. Attempting to manually rollback within the function will cause a panic.
(fn func(*Tx) error)
| 934 | // |
| 935 | // Attempting to manually rollback within the function will cause a panic. |
| 936 | func (db *DB) View(fn func(*Tx) error) error { |
| 937 | t, err := db.Begin(false) |
| 938 | if err != nil { |
| 939 | return err |
| 940 | } |
| 941 | |
| 942 | // Make sure the transaction rolls back in the event of a panic. |
| 943 | defer func() { |
| 944 | if t.db != nil { |
| 945 | t.rollback() |
| 946 | } |
| 947 | }() |
| 948 | |
| 949 | // Mark as a managed tx so that the inner function cannot manually rollback. |
| 950 | t.managed = true |
| 951 | |
| 952 | // If an error is returned from the function then pass it through. |
| 953 | err = fn(t) |
| 954 | t.managed = false |
| 955 | if err != nil { |
| 956 | _ = t.Rollback() |
| 957 | return err |
| 958 | } |
| 959 | |
| 960 | return t.Rollback() |
| 961 | } |
| 962 | |
| 963 | // Batch calls fn as part of a batch. It behaves similar to Update, |
| 964 | // except: |