Skip to content

Commit 12b6163

Browse files
committed
Merge pull request #267 from gliptak/dbexception1
Add DB.db method with Try1
2 parents efe666a + e87d5be commit 12b6163

File tree

2 files changed

+28
-13
lines changed

2 files changed

+28
-13
lines changed

core/src/main/java/fj/control/db/DB.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import fj.F;
44
import fj.Function;
5+
import fj.function.Try1;
56

67
import java.sql.Connection;
78
import java.sql.SQLException;
@@ -35,6 +36,21 @@ public A run(final Connection c) {
3536
};
3637
}
3738

39+
/**
40+
* Constructs a database action as a function from a database connection to a value.
41+
*
42+
* @param t A function from a database connection to a value allowed to throw
43+
* SQLException
44+
* @return A database action representing the given function.
45+
*/
46+
public static <A> DB<A> db(final Try1<Connection, A, SQLException> t){
47+
return new DB<A>() {
48+
public A run(final Connection c) throws SQLException {
49+
return t.f(c);
50+
}
51+
};
52+
}
53+
3854
/**
3955
* Returns the callable-valued function projection of this database action.
4056
*

core/src/test/java/fj/control/db/TestDbState.java

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import fj.Unit;
44
import fj.data.Option;
5+
import fj.function.Try1;
56
import org.apache.commons.dbutils.DbUtils;
67
import org.junit.Test;
78

@@ -16,20 +17,18 @@ public void testWriter() throws SQLException {
1617
final int TEN = 10;
1718
DbState writer = DbState.writer(DbState.driverManager("jdbc:h2:mem:"));
1819

19-
DB<Unit> setup = new DB<Unit>() {
20-
@Override
21-
public Unit run(Connection c) throws SQLException {
22-
Statement s = null;
23-
try {
24-
s = c.createStatement();
25-
assertThat(s.executeUpdate("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"), is(0));
26-
assertThat(s.executeUpdate("INSERT INTO TEST (ID, NAME) VALUES (" + TEN + ", 'FOO')"), is(1));
27-
} finally {
28-
DbUtils.closeQuietly(s);
29-
}
30-
return Unit.unit();
20+
DB<Unit> setup = DB.db((Try1<Connection, Unit, SQLException>) c -> {
21+
Statement s = null;
22+
try {
23+
s = c.createStatement();
24+
assertThat(s.executeUpdate("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"), is(0));
25+
assertThat(s.executeUpdate("INSERT INTO TEST (ID, NAME) VALUES (" + TEN + ", 'FOO')"), is(1));
26+
} finally {
27+
DbUtils.closeQuietly(s);
3128
}
32-
};
29+
return Unit.unit();
30+
});
31+
3332
DB<Option<Integer>> query = new DB<Option<Integer>>() {
3433
@Override
3534
public Option<Integer> run(Connection c) throws SQLException {

0 commit comments

Comments
 (0)