Passed
Push — master ( 6628e1...2db758 )
by Christoph
23:37 queued 08:44
created

TTransactional   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 31
rs 10
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A atomic() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * @copyright 2022 Christoph Wurst <[email protected]>
7
 *
8
 * @author 2022 Christoph Wurst <[email protected]>
9
 *
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
 */
25
26
namespace OCP\AppFramework\Db;
27
28
use OCP\DB\Exception;
29
use OCP\IDBConnection;
30
use Throwable;
31
32
/**
33
 * Helper trait for transactional operations
34
 *
35
 * @since 24.0.0
36
 */
37
trait TTransactional {
38
39
	/**
40
	 * Run an atomic database operation
41
	 *
42
	 * - Commit if no exceptions are thrown, return the callable result
43
	 * - Revert otherwise and rethrows the exception
44
	 *
45
	 * @template T
46
	 * @param callable $fn
47
	 * @psalm-param callable():T $fn
48
	 * @param IDBConnection $db
49
	 *
50
	 * @return mixed the result of the passed callable
51
	 * @psalm-return T
52
	 *
53
	 * @throws Exception for possible errors of commit or rollback or the custom operations within the closure
54
	 * @throws Throwable any other error caused by the closure
55
	 *
56
	 * @since 24.0.0
57
	 * @see https://docs.nextcloud.com/server/latest/developer_manual/basics/storage/database.html#transactions
58
	 */
59
	protected function atomic(callable $fn, IDBConnection $db) {
60
		$db->beginTransaction();
61
		try {
62
			$result = $fn();
63
			$db->commit();
64
			return $result;
65
		} catch (Throwable $e) {
66
			$db->rollBack();
67
			throw $e;
68
		}
69
	}
70
}
71