Run a closure within an SQL transaction (`BEGIN .. COMMIT/ROLLBACK`).
(&mut self, mut callback: F)
| 870 | |
| 871 | /// Run a closure within an SQL transaction (`BEGIN .. COMMIT/ROLLBACK`). |
| 872 | pub fn transaction<F, T>(&mut self, mut callback: F) -> Result<T> |
| 873 | where |
| 874 | F: FnMut(&mut Transaction<'_>) -> Result<T>, |
| 875 | { |
| 876 | self.check_ready()?; |
| 877 | |
| 878 | // Begin transaction |
| 879 | self.run_exec_command("BEGIN")?; |
| 880 | self.in_transaction = true; |
| 881 | |
| 882 | let mut tx = Transaction::new(self); |
| 883 | let callback_result = callback(&mut tx); |
| 884 | |
| 885 | let txn_result = match callback_result { |
| 886 | Ok(value) => { |
| 887 | if !tx.closed { |
| 888 | tx.commit_internal()?; |
| 889 | } |
| 890 | Ok(value) |
| 891 | } |
| 892 | Err(err) => { |
| 893 | if !tx.closed { |
| 894 | tx.rollback_internal()?; |
| 895 | } |
| 896 | Err(err) |
| 897 | } |
| 898 | }; |
| 899 | |
| 900 | self.in_transaction = false; |
| 901 | txn_result |
| 902 | } |
| 903 | |
| 904 | /// Flush runtime writes to the underlying filesystem. |
| 905 | /// |