-
Notifications
You must be signed in to change notification settings - Fork 1
/
SyncDbInterpreter.java
64 lines (54 loc) · 1.79 KB
/
SyncDbInterpreter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.novarto.sanedbc.core.interpreter;
import fj.control.db.DB;
import fj.function.Try0;
import java.sql.Connection;
import java.sql.SQLException;
import static com.novarto.sanedbc.core.interpreter.InterpreterUtils.transactional;
/**
* An interpreter for DB operations which blocks the caller thread. In addition it rethrows any SQL Exceptions as runtime ones.
* Mostly useful for testing purposes.
*
*/
public class SyncDbInterpreter
{
private final Try0<Connection, SQLException> ds;
/**
* Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool,
* Driver Manager, etc.
* @param ds - the data source, which can spawn connections
*/
public SyncDbInterpreter(Try0<Connection, SQLException> ds)
{
this.ds = ds;
}
/**
* Attempt to run this operation and return its result
* @param doOp the operation to run
* @param <A> the result type of the operation
* @return the successful result
* @throws RuntimeException if an {@link SQLException} is encountered
*/
public <A> A submit(DB<A> doOp)
{
try (Connection c = ds.f())
{
return doOp.run(c);
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
}
/**
* Attempt to run this operation and return its result. The operation is run transactionally - i.e. if any error is
* encountered, the operation is rolled back.
* @param doOp the operation to run
* @param <A> the result type of the operation
* @return the successful result
* @throws RuntimeException if an {@link SQLException} is encountered
*/
public <A> A transact(DB<A> doOp)
{
return submit(transactional(doOp));
}
}