Update executes a function within the context of a read-write managed transaction. If no error is returned from the function then the transaction is committed. If an error is returned then the entire transaction is rolled back. Any error that is returned from the function or returned from the commit
(fn func(*Tx) error)
| 903 | // |
| 904 | // Attempting to manually commit or rollback within the function will cause a panic. |
| 905 | func (db *DB) Update(fn func(*Tx) error) error { |
| 906 | t, err := db.Begin(true) |
| 907 | if err != nil { |
| 908 | return err |
| 909 | } |
| 910 | |
| 911 | // Make sure the transaction rolls back in the event of a panic. |
| 912 | defer func() { |
| 913 | if t.db != nil { |
| 914 | t.rollback() |
| 915 | } |
| 916 | }() |
| 917 | |
| 918 | // Mark as a managed tx so that the inner function cannot manually commit. |
| 919 | t.managed = true |
| 920 | |
| 921 | // If an error is returned from the function then rollback and return error. |
| 922 | err = fn(t) |
| 923 | t.managed = false |
| 924 | if err != nil { |
| 925 | _ = t.Rollback() |
| 926 | return err |
| 927 | } |
| 928 | |
| 929 | return t.Commit() |
| 930 | } |
| 931 | |
| 932 | // View executes a function within the context of a managed read-only transaction. |
| 933 | // Any error that is returned from the function is returned from the View() method. |