-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDBConnection.java
More file actions
executable file
·277 lines (247 loc) · 11 KB
/
DBConnection.java
File metadata and controls
executable file
·277 lines (247 loc) · 11 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package com.github.collinalpert.java2db.database;
import com.github.collinalpert.java2db.mappers.FieldMapper;
import com.github.collinalpert.java2db.queries.*;
import com.github.collinalpert.java2db.queries.async.*;
import java.io.Closeable;
import java.sql.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import static com.github.collinalpert.java2db.utilities.Utilities.supplierHandling;
/**
* Wrapper around {@link Connection} which eases use of running queries.
* Also supports running functions and stored procedures.
*
* @author Collin Alpert
*/
public class DBConnection implements Closeable {
/**
* Constant which determines if the queries generated by Java2DB will be logged in the console.
*/
public static boolean LOG_QUERIES = true;
private final Connection underlyingConnection;
private boolean isConnectionValid;
public DBConnection(Connection underlyingConnection) {
this.underlyingConnection = underlyingConnection;
this.isConnectionValid = true;
}
/**
* Checks if the connection is valid/successful.
*
* @return True if connection was successful, false if not.
*/
public boolean isValid() {
return this.isConnectionValid;
}
/**
* Executes a DQL statement on the database without Java parameters.
*
* @param query The query to be executed.
* @return The {@link ResultSet} containing the result from the DQL statement.
* @throws SQLException if the query is malformed or cannot be executed.
*/
public ResultSet execute(String query) throws SQLException {
var statement = this.underlyingConnection.createStatement();
log(query);
var set = statement.executeQuery(query);
statement.closeOnCompletion();
return set;
}
/**
* Executes a DQL statement on the database with Java parameters.
*
* @param query The query to be executed.
* @param params The Java parameters to be inserted into the query.
* @return The {@link ResultSet} containing the result from the DQL statement.
* @throws SQLException if the query is malformed or cannot be executed.
*/
public ResultSet execute(String query, Object... params) throws SQLException {
var statement = this.underlyingConnection.prepareStatement(query);
for (int i = 0; i < params.length; i++) {
statement.setObject(i + 1, params[i]);
}
log(query);
var set = statement.executeQuery();
statement.closeOnCompletion();
return set;
}
/**
* This command is used for any DDL/DML queries.
*
* @param query The query to be executed.
* @return the last generated ID. This return value should only be used with INSERT statements.
* @throws SQLException if the query is malformed or cannot be executed.
*/
public int update(String query) throws SQLException {
var statement = this.underlyingConnection.createStatement();
log(query);
statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
return updateInternal(statement);
}
/**
* This command is used for any DDL/DML queries with Java parameters.
*
* @param query The query to be executed.
* @param params The Java parameters to be inserted into the query.
* @return the last generated ID. This return value should only be used with INSERT statements.
* @throws SQLException if the query is malformed or cannot be executed.
*/
public int update(String query, Object... params) throws SQLException {
var statement = this.underlyingConnection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < params.length; i++) {
statement.setObject(i + 1, params[i]);
}
log(query);
statement.executeUpdate();
return updateInternal(statement);
}
/**
* Determines if a connection to the database still exists or not.
*
* @return {@code True} if a connection exists, {@code false} if not.
* This method will return {@code false} if an exception occurs.
*/
public boolean isOpen() {
try {
return !this.underlyingConnection.isClosed();
} catch (SQLException e) {
System.err.println("Could not determine connection status");
return this.isConnectionValid = false;
}
}
/**
* Closes the connection to the database.
*/
@Override
public void close() {
try {
if (this.underlyingConnection != null) {
this.underlyingConnection.close();
}
} catch (SQLException e) {
System.err.println("Could not close database connection");
e.printStackTrace();
} finally {
this.isConnectionValid = false;
}
}
/**
* Calls an SQL function.
*
* @param returnType The Java equivalent of the SQL datatype the function returns.
* @param functionName The name of the function.
* @param arguments The arguments to be supplied to the function, if any.
* @param <T> The functions return type.
* @return The return value of the function, as a Java datatype.
* @throws SQLException In case there is an error communicating with the database, i.e. the function does not exist.
*/
public <T> Optional<T> callFunction(Class<T> returnType, String functionName, Object... arguments) throws SQLException {
var joiner = new StringJoiner(",");
for (int i = 0; i < arguments.length; i++) {
joiner.add("?");
}
try (var set = execute(String.format("select %s(%s);", functionName, joiner.toString()), arguments)) {
return new FieldMapper<>(returnType).map(set);
}
}
/**
* Calls an SQL function asynchronously.
*
* @param exceptionHandler The exception handler which handles the {@link SQLException} in case something goes wrong.
* @param returnType The Java type which the result will be mapped into. It needs to have a parameterless constructor available.
* @param functionName The name of the function to call.
* @param arguments The arguments to supply to the function, if any.
* @param <T> The functions return type.
* @return The return value of the function, as a Java datatype.
*/
public <T> CompletableFuture<Optional<T>> callFunctionAsync(Consumer<SQLException> exceptionHandler, Class<T> returnType, String functionName, Object... arguments) {
return CompletableFuture.supplyAsync(supplierHandling(() -> this.callFunction(returnType, functionName, arguments), exceptionHandler));
}
/**
* Calls an SQL function asynchronously. If an exception occurs, it gets printed to the console.
*
* @param returnType The Java type which the result will be mapped into. It needs to have a parameterless constructor available.
* @param functionName The name of the function to call.
* @param arguments The arguments to supply to the function, if any.
* @param <T> The functions return type.
* @return The return value of the function, as a Java datatype.
*/
public <T> CompletableFuture<Optional<T>> callFunctionAsync(Class<T> returnType, String functionName, Object... arguments) {
return CompletableFuture.supplyAsync(supplierHandling(() -> this.callFunction(returnType, functionName, arguments)));
}
/**
* Calls an SQL function asynchronously and applies a {@link Consumer} to the returned value.
*
* @param returnType The Java type which the result will be mapped into. It needs to have a parameterless constructor available.
* @param callback A consumer which specifies which action to perform once the function has been called.
* @param functionName The name of the function to call.
* @param arguments The arguments to supply to the function, if any.
* @param <T> The functions return type.
* @return The return value of the function, as a Java datatype.
*/
public <T> CompletableFuture<Void> callFunctionAsync(Class<T> returnType, Consumer<? super Optional<T>> callback, String functionName, Object... arguments) {
return CompletableFuture.supplyAsync(supplierHandling(() -> this.callFunction(returnType, functionName, arguments))).thenAcceptAsync(callback);
}
/**
* Calls an SQL function asynchronously and applies a {@link Consumer} to the returned value.
*
* @param exceptionHandler The exception handler which handles the {@link SQLException} in case something goes wrong.
* @param returnType The Java type which the result will be mapped into. If it is a complex type, it needs to have a parameterless constructor available.
* @param callback A consumer which specifies which action to perform once the function has been called.
* @param functionName The name of the function to call.
* @param arguments The arguments to supply to the function, if any.
* @param <T> The functions return type.
* @return The return value of the function, as a Java datatype.
*/
public <T> CompletableFuture<Void> callFunctionAsync(Consumer<SQLException> exceptionHandler, Class<T> returnType, Consumer<? super Optional<T>> callback, String functionName, Object... arguments) {
return CompletableFuture.supplyAsync(supplierHandling(() -> this.callFunction(returnType, functionName, arguments), exceptionHandler)).thenAcceptAsync(callback);
}
/**
* Calls a stored procedure and returns a {@link Queryable} to fetch the data in the desired format.
*
* @param returnType The Java type which the result will be mapped into. If it is a complex type, it needs to have a parameterless constructor available.
* @param storedProcedureName The name of the stored procedure to call.
* @param arguments The arguments to pass to the stored procedure.
* @param <T> The Java type to be returned?
* @return A {@link Queryable} to fetch the data in the desired format.
*/
public <T> Queryable<T> callStoredProcedure(Class<T> returnType, String storedProcedureName, Object... arguments) {
return new StoredProcedureQuery<>(returnType, this, storedProcedureName, arguments);
}
/**
* Calls a stored procedure asynchronously and returns a {@link Queryable} to fetch the data in the desired format.
*
* @param returnType The Java type which the result will be mapped into. If it is a complex type, it needs to have a parameterless constructor available.
* @param storedProcedureName The name of the stored procedure to call.
* @param arguments The arguments to pass to the stored procedure.
* @param <T> The Java type to be returned?
* @return An {@link AsyncQueryable} to fetch the data in the desired format.
*/
public <T> AsyncQueryable<T> callStoredProcedureAsync(Class<T> returnType, String storedProcedureName, Object... arguments) {
return new AsyncStoredProcedureQuery<>(returnType, this, storedProcedureName, arguments);
}
/**
* @return The {@link Connection} object this class uses to operate on.
*/
public Connection underlyingConnection() {
return this.underlyingConnection;
}
/**
* Prints queries to the console, while considering the {@link DBConnection#LOG_QUERIES} constant.
*
* @param text The message to print.
*/
private void log(String text) {
if (LOG_QUERIES) {
System.out.println(text);
}
}
private int updateInternal(Statement statement) throws SQLException {
statement.closeOnCompletion();
var set = statement.getGeneratedKeys();
if (set.next()) {
return set.getInt(1);
}
return -1;
}
}