-
Notifications
You must be signed in to change notification settings - Fork 1
/
BatchUpdateOp.java
65 lines (54 loc) · 1.88 KB
/
BatchUpdateOp.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
65
package com.novarto.sanedbc.core.ops;
import com.novarto.lang.Collections;
import com.novarto.sanedbc.core.SqlStringUtils;
import fj.F;
import fj.control.db.DB;
import fj.data.Option;
import fj.function.Try1;
import fj.function.TryEffect1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import static com.novarto.sanedbc.core.ops.Binders.batchBinder;
public class BatchUpdateOp<A> extends DB<Option<Integer>>
{
private final String sql;
private final Try1<PreparedStatement, Option<Integer>, SQLException> binder;
private final Iterable<A> as;
public BatchUpdateOp(String sql, F<A, TryEffect1<PreparedStatement, SQLException>> binder, Iterable<A> as)
{
this.binder = batchBinder(binder, as);
this.as = as;
this.sql = sql;
}
@Override
public Option<Integer> run(Connection c) throws SQLException
{
if (Collections.isEmpty(as))
{
return Option.none();
}
if (!isInsert(sql))
{
throwIfAutoCommit(c);
}
try (PreparedStatement preparedStatement = c.prepareStatement(sql))
{
return binder.f(preparedStatement);
}
}
public static void throwIfAutoCommit(Connection c) throws SQLException
{
if (c.getAutoCommit())
{
throw new RuntimeException("you are performing a batch update or delete operation, but auto commit is true." +
"This results in a drastic performance degradation under mysql, so i'm just going to stop you." +
"Use com.novarto.rubik.rulesdb.client.core.db.MySQL.withTransaction or " +
"com.novarto.test.db.DBTest.transact");
}
}
private boolean isInsert(String sql)
{
return SqlStringUtils.getStatementKind(sql).equals(SqlStringUtils.StatementKind.INSERT);
}
}