1 package org.davidmoten.rx.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.ResultSet;
5
6 import javax.annotation.Nonnull;
7
8 import com.github.davidmoten.guavamini.Preconditions;
9
10 import io.reactivex.Completable;
11 import io.reactivex.Flowable;
12 import io.reactivex.Single;
13
14 public final class UpdateBuilder extends ParametersBuilder<UpdateBuilder> implements DependsOn<UpdateBuilder> {
15
16 static final int DEFAULT_BATCH_SIZE = 1;
17
18 final String sql;
19 final Single<Connection> connections;
20 private final Database db;
21 Flowable<?> dependsOn;
22 int batchSize = DEFAULT_BATCH_SIZE;
23 int queryTimeoutSec = Util.QUERY_TIMEOUT_NOT_SET;
24
25 UpdateBuilder(String sql, Single<Connection> connections, Database db) {
26 super(sql);
27 this.sql = sql;
28 this.connections = connections;
29 this.db = db;
30 }
31
32 @Override
33 public UpdateBuilder dependsOn(Flowable<?> flowable) {
34 Preconditions.checkArgument(dependsOn == null, "dependsOn can only be set once");
35 dependsOn = flowable;
36 return this;
37 }
38
39 public UpdateBuilder batchSize(int batchSize) {
40 this.batchSize = batchSize;
41 return this;
42 }
43
44 public UpdateBuilder queryTimeoutSec(int queryTimeoutSec) {
45 Preconditions.checkArgument(queryTimeoutSec >= 0);
46 this.queryTimeoutSec = queryTimeoutSec;
47 return this;
48 }
49
50
51
52
53
54
55
56
57
58
59 public ReturnGeneratedKeysBuilder returnGeneratedKeys() {
60 Preconditions.checkArgument(batchSize == 1, "Cannot return generated keys if batchSize > 1");
61 return new ReturnGeneratedKeysBuilder(this);
62 }
63
64 public Flowable<Integer> counts() {
65 return startWithDependency(
66 Update.create(connections, super.parameterGroupsToFlowable(), sql, batchSize, true, queryTimeoutSec).dematerialize());
67 }
68
69 <T> Flowable<T> startWithDependency(@Nonnull Flowable<T> f) {
70 if (dependsOn != null) {
71 return dependsOn.ignoreElements().andThen(f);
72 } else {
73 return f;
74 }
75 }
76
77 public TransactedUpdateBuilder transacted() {
78 return new TransactedUpdateBuilder(this, db);
79 }
80
81 public Flowable<Tx<?>> transaction() {
82 return transacted().tx();
83 }
84
85 public Completable complete() {
86 return counts().ignoreElements();
87 }
88
89 }