-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathStatementTest.java
More file actions
619 lines (556 loc) · 25 KB
/
Copy pathStatementTest.java
File metadata and controls
619 lines (556 loc) · 25 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
package integration.tests;
import com.firebolt.jdbc.connection.FireboltConnection;
import com.firebolt.jdbc.exception.FireboltException;
import com.firebolt.jdbc.testutils.TestTag;
import integration.ConnectionInfo;
import integration.EnvironmentCondition;
import integration.IntegrationTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import kotlin.collections.ArrayDeque;
import lombok.CustomLog;
import org.apache.commons.lang3.RandomStringUtils;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import static integration.EnvironmentCondition.Attribute.databaseVersion;
import static java.lang.String.format;
import static java.sql.Statement.SUCCESS_NO_INFO;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@CustomLog
class StatementTest extends IntegrationTest {
private static final long TEN_SECONDS_IN_MILLIS = TimeUnit.SECONDS.toMillis(10);
@BeforeEach
void beforeEach() {
executeStatementFromFile("/statements/statement/ddl.sql");
}
@AfterEach
void afterEach() {
executeStatementFromFile("/statements/statement/cleanup.sql");
}
@Test
void shouldSelect1() throws SQLException {
try (Connection connection = createConnection();
ResultSet rs = connection.createStatement().executeQuery("SELECT 1")) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
}
}
@Test
@EnabledIfSystemProperty(named = "engine", matches = ".+")
void shouldSelect1WithEngine() throws SQLException {
try (Connection connection = createConnection(System.getProperty("engine")); Statement statement = connection.createStatement()) {
statement.executeQuery("SELECT 1;");
assertNotNull(statement.executeQuery("SELECT 1;"));
}
}
@Test
void shouldSelect1WithQueryTimeout() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
statement.setQueryTimeout(10); // 10 seconds
statement.executeQuery("SELECT 1;");
assertNotNull(statement.executeQuery("SELECT 1;"));
}
}
@Test
void shouldReuseStatementWhenNotCloseOnCompletion() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
statement.executeQuery("SELECT 1;");
assertNotNull(statement.executeQuery("SELECT 1;"));
}
}
@Test
void shouldThrowExceptionWhenTryingToReuseStatementClosedOnCompletion() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
statement.closeOnCompletion();
statement.executeQuery("SELECT 1;");
assertTrue(statement.isCloseOnCompletion());
assertThrows(FireboltException.class, () -> statement.executeQuery("SELECT 1;"));
}
}
@Tag("v2")
@Test
void shouldThrowExceptionWhenExecutingWrongQuery() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
String errorMessage = assertThrows(FireboltException.class, () -> statement.executeQuery("select wrong query")).getMessage();
assertTrue(errorMessage.contains("Column 'wrong' does not exist."));
}
}
@Tag("v1")
@Test
void shouldThrowExceptionWhenExecutingWrongQueryV1() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
String errorMessage = assertThrows(FireboltException.class, () -> statement.executeQuery("select wrong query")).getMessage();
assertTrue(errorMessage.contains("wrong"));
assertTrue(errorMessage.contains("Line 1"));
assertTrue(errorMessage.contains("Column 8"));
}
}
@Test
@Tag("v2")
@EnvironmentCondition(value = "4.2.0", attribute = databaseVersion, comparison = EnvironmentCondition.Comparison.GE)
void shouldThrowExceptionWhenExecutingWrongQueryWithJsonError() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
statement.execute("set advanced_mode=1");
statement.execute("set enable_json_error_output_format=true");
String errorMessage = assertThrows(FireboltException.class, () -> statement.executeQuery("select wrong query")).getMessage();
assertTrue(errorMessage.contains("Column 'wrong' does not exist."));
assertTrue(errorMessage.contains("Line 1"));
assertTrue(errorMessage.contains("Column 8"));
}
}
@Test
void shouldReturnTrueWhenExecutingAStatementThatReturnsAResultSet() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
assertTrue(statement.execute("SELECT 1;"));
}
}
@Test
void shouldReturnTrueWhenExecutingMultiStatementWithFirstStatementReturningAResultSet() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
assertTrue(statement.execute("SELECT 1;"));
}
}
@Test
void shouldReturnFalseWhenExecutingMultiStatementWithFirstStatementNotReturningAResultSet() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
assertFalse(statement.execute("INSERT INTO statement_test(id) values (1); SELECT 1;"));
}
}
@Test
void shouldReturnLimitedNumberOfLines() throws SQLException {
try (Connection connection = createConnection(); Statement insert = connection.createStatement()) {
String valuesAsStr = IntStream.rangeClosed(1, 100).mapToObj(n -> format("(%d)", n)).collect(joining(","));
insert.execute("INSERT INTO statement_test(id) values " + valuesAsStr);
List<Integer> resultAll = IntStream.rangeClosed(1, 100).boxed().collect(toList());
assertEquals(resultAll, selectIntValues(connection, 0));
assertEquals(resultAll, selectIntValues(connection, 100));
assertEquals(resultAll, selectIntValues(connection, 101));
assertEquals(resultAll, selectIntValues(connection, 1000));
List<Integer> result99 = IntStream.rangeClosed(1, 99).boxed().collect(toList());
assertEquals(result99, selectIntValues(connection, 99));
assertEquals(List.of(1, 2), selectIntValues(connection, 2));
assertEquals(List.of(1), selectIntValues(connection, 1));
}
}
private List<Integer> selectIntValues(Connection connection, int limit) throws SQLException {
Statement select = connection.createStatement();
select.setMaxRows(limit);
List<Integer> result = new ArrayDeque<>();
try (ResultSet rs = select.executeQuery("select id from statement_test order by id")) {
while (rs.next()) {
result.add(rs.getInt(1));
}
}
return result;
}
@Test
void shouldExecuteBatch() throws SQLException {
int size = 10;
try (Connection connection = createConnection(); Statement insert = connection.createStatement()) {
for (int i = 0; i < size; i++) {
insert.addBatch(format("INSERT INTO statement_test(id) values (%d)", i));
}
assertArrayEquals(IntStream.generate(() -> SUCCESS_NO_INFO).limit(size).toArray(), insert.executeBatch());
}
}
@Test
void shouldThrowExceptionWhenTryingToExecuteQueryThatWouldReturnMultipleResultSets() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
assertThrows(FireboltException.class, () -> statement.executeQuery("SELECT 1; SELECT 2;"));
}
}
@Test
void shouldGetMultipleResultSets() throws SQLException {
String sql = " --Getting Multiple RS;\nSELECT 1; /* comment 1 ; ; ; */\n\n --Another comment ; \n -- ; \n SELECT 2; /* comment 2 */";
try (Connection connection = createConnection()) {
try (Statement statement = connection.createStatement()) {
statement.execute(sql);
ResultSet resultSet = statement.getResultSet();
resultSet.next();
assertEquals(1, resultSet.getInt(1));
resultSet.close();
assertTrue(statement.getMoreResults());
resultSet = statement.getResultSet();
resultSet.next();
assertEquals(2, resultSet.getInt(1));
}
}
}
@Test
void shouldNotCloseStatementWithCloseOnCompletionIfItHasMoreResults() throws SQLException {
String sql = "SELECT 1;SELECT 2;";
try (Connection connection = createConnection()) {
try (Statement statement = connection.createStatement()) {
statement.closeOnCompletion();
statement.execute(sql);
ResultSet resultSet = statement.getResultSet();
resultSet.close();
assertFalse(statement.isClosed());
statement.getMoreResults();
resultSet = statement.getResultSet();
resultSet.close();
assertTrue(statement.isClosed());
}
}
}
@Test
void shouldGetBooleans() throws SQLException {
try (Connection connection = createConnection()) {
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SELECT true, false, null::boolean;");
resultSet.next();
assertEquals(Boolean.TRUE, resultSet.getObject(1));
assertTrue(resultSet.getBoolean(1));
assertEquals(Boolean.FALSE, resultSet.getObject(2));
assertFalse(resultSet.getBoolean(2));
assertNull(resultSet.getObject(3));
assertFalse(resultSet.getBoolean(3));
}
}
}
@Test
void setWrongParameter() throws SQLException {
setWrongParameter("SET foo=bar", Map.of(), "foo");
}
@Test
void setCorrectThenWrongParameter() throws SQLException {
setWrongParameter("SET time_zone = 'EST';SET bar=tar", Map.of("time_zone", "EST"), "bar");
}
@Test
@Tag("v2")
@Tag("slow")
void canSetQueryLabelMultipleTimes() throws SQLException {
try (Connection connection = createConnection()) {
try (Statement statement = connection.createStatement()) {
String currentTime = getCurrentUTCTime();
String firstQueryLabel = "first query label " + RandomStringUtils.randomNumeric(4);
statement.execute(String.format("SET query_label = '%s'", firstQueryLabel));
String nextQueryAfterFirstLabelSet = "SELECT " + RandomStringUtils.randomNumeric(4) + ";";
statement.executeQuery(nextQueryAfterFirstLabelSet);
// set a new query label
String secondQueryLabel = "second query label " + RandomStringUtils.randomNumeric(4);
statement.execute(String.format("SET query_label = '%s'", secondQueryLabel));
String nextQueryAfterSecondLabelSet = "SELECT " + RandomStringUtils.randomNumeric(4) + ";";
statement.executeQuery(nextQueryAfterSecondLabelSet);
// sleep for some time to allow query history to execute
sleepForMillis(TEN_SECONDS_IN_MILLIS);
// check query history for both queries
assertQueryFound(statement, firstQueryLabel, currentTime, nextQueryAfterFirstLabelSet);
assertQueryFound(statement, secondQueryLabel, currentTime, nextQueryAfterSecondLabelSet);
}
}
}
@Test
@Tag("v2")
@Tag("slow")
void willUseRandomQueryLabelIfNoneExplicitlySet() throws SQLException {
try (Connection connection = createConnection()) {
try (Statement statement = connection.createStatement()) {
String currentTime = getCurrentUTCTime();
String statementWithoutExplicitQueryLabel = "SELECT " + RandomStringUtils.randomNumeric(3) + ";";
statement.executeQuery(statementWithoutExplicitQueryLabel);
// sleep for some time to allow query history to execute
sleepForMillis(TEN_SECONDS_IN_MILLIS);
String implicitQueryLabel = getQueryLabel(statement, currentTime, statementWithoutExplicitQueryLabel);
assertNotNull(implicitQueryLabel, "Expected the default query label to be non null");
}
}
}
/**
* looks up a query in the query history. Returns the query text
* @param statement
* @return
*/
private void assertQueryFound(Statement statement, String queryLabelValue, String afterTimestamp, String queryText) throws SQLException {
String queryHistoryQuery =
"SELECT query_text " +
"FROM information_schema.engine_query_history " +
"WHERE query_label = '%s' and submitted_time > '%s' and query_text = '%s'; ";
ResultSet resultSet = statement.executeQuery(String.format(queryHistoryQuery, queryLabelValue, afterTimestamp, queryText));
assertTrue(resultSet.next(), "Did not find query with the specified query label");
}
private String getQueryLabel(Statement statement, String afterTimestamp, String queryText) throws SQLException {
String queryHistoryQuery =
"SELECT query_label " +
"FROM information_schema.engine_query_history WHERE submitted_time > '%s' and query_text = '%s'; ";
ResultSet resultSet = statement.executeQuery(String.format(queryHistoryQuery, afterTimestamp, queryText));
assertTrue(resultSet.next(), "Did not find any query in history");
return resultSet.getString(1);
}
/**
* Connect to DB using {@code advanced_mode} sent in JDBC URL and set {@code force_pgdate_timestampntz} that requires advanced mode.
* @throws SQLException if connection fails
*/
@Test
void successfulSettingOfPropertyThatRequiresAdvancedModeConfiguredWhenConnectionIsCreated() throws SQLException {
ConnectionInfo current = integration.ConnectionInfo.getInstance();
String url = current.toJdbcUrl() + "&advanced_mode=1";
try (Connection connection = DriverManager.getConnection(url, current.getPrincipal(), current.getSecret())) {
setParam(connection, "force_pgdate_timestampntz", "1");
}
}
/**
* Connect to DB without {@code advanced_mode}. Then set {@code advanced_mode=1} and {@code force_pgdate_timestampntz} that requires advanced mode.
* @throws SQLException if connection fails
*/
@Test
void successfulSettingOfPropertyThatRequiresAdvancedModePreviouslySetAtRuntime() throws SQLException {
try (Connection connection = createConnection()) {
setParam(connection, "advanced_mode", "1");
setParam(connection, "force_pgdate_timestampntz", "1");
}
}
/**
* Try to set {@code force_pgdate_timestampntz} that requires advanced mode that was not set. This test will fail.
* @throws SQLException if connection fails
*/
@Test
void failedSettingPropertyThatRequiresAdvancedModeThatWasNotSet() throws SQLException {
try (Connection connection = createConnection()) {
assertFailingSet(connection, "force_pgdate_timestampntz");
}
}
/**
* Connect to DB using {@code advanced_mode} sent in JDBC URL. Then set {@code advanced_mode=0} and
* try to set {@code force_pgdate_timestampntz} that requires advanced mode and therefore fails.
* @throws SQLException if connection fails
*/
@Test
void failedSettingPropertyThatRequiresAdvancedModeThatWasUnset() throws SQLException {
ConnectionInfo current = integration.ConnectionInfo.getInstance();
String url = current.toJdbcUrl() + "&advanced_mode=1";
try (Connection connection = DriverManager.getConnection(url, current.getPrincipal(), current.getSecret())) {
setParam(connection, "advanced_mode", "0");
assertFailingSet(connection, "force_pgdate_timestampntz");
}
}
private void assertFailingSet(Connection connection, String paramName) {
FireboltException e = assertThrows(FireboltException.class, () -> setParam(connection, paramName, "1"));
assertTrue(e.getMessage().contains(paramName) && e.getMessage().contains("not allowed"), format("error message say that parameter %s is not allowed but was %s", paramName, e.getMessage()));
}
private void setWrongParameter(String set, Map<String, String> expectedAdditionalProperties, String expectedWrongPropertyName) throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
String message = assertThrows(SQLException.class, () -> statement.execute(set)).getMessage();
String expected1 = format("parameter %s is not allowed", expectedWrongPropertyName);
String expected2 = format("query param not allowed: %s", expectedWrongPropertyName);
assertTrue(message.contains(expected1) || message.contains(expected2),
format("Unexpected error message: '%s'. Message should contain statement: '%s' or '%s'", message, expected1, expected2));
assertEquals(expectedAdditionalProperties, ((FireboltConnection)connection).getSessionProperties().getAdditionalProperties());
}
}
@ParameterizedTest(name = "query:{0};")
@ValueSource(strings = {
"",
" ",
"--",
"-- SELECT 1",
"/* {\"app\": \"dbt\", \"dbt_version\": \"0.20.0\", \"profile_name\": \"jaffle_shop\", \"target_name\": \"fb_app\", \"connection_name\": \"macro_stage_external_sources\"} */"
})
void empty(String sql) throws SQLException {
try (Connection connection = createConnection()) {
assertFalse(connection.createStatement().execute(sql));
}
}
/**
* This test validates that null values are sorted last.
* @throws SQLException if something is going wrong
* see com.firebolt.jdbc.metadata.FireboltDatabaseMetadataTest#nullSorting
*/
@Test
void nullSortOrder() throws SQLException {
try (Connection connection = createConnection();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select x from (select null as x union all select '' as x union all select 'a' as x) order by x")) {
List<String> actuals = new ArrayList<>();
while(rs.next()) {
actuals.add(rs.getString(1));
}
assertEquals(Arrays.asList("", "a", null), actuals);
}
}
/**
* This test proves that unquoted query columns become lower case and quoted columns preserve case
* @throws SQLException if something is going wrong
* see com.firebolt.jdbc.metadata.FireboltDatabaseMetadataTest#identifiersCase
* see com.firebolt.jdbc.metadata.FireboltDatabaseMetadataTest#quotedIdentifiersCase
*/
@ParameterizedTest
@CsvSource(value = {
"select 1 as lower, 2 as UPPER, 3 AS MiXeD;lower,upper,mixed",
"select 1 as \"lower\", 2 as \"UPPER\", 3 AS \"MiXeD\";lower,UPPER,MiXeD"
}, delimiter = ';')
void mixedCaseSelect(String query, String expectedColumns) throws SQLException {
try (Connection connection = createConnection();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query)) {
ResultSetMetaData md = rs.getMetaData();
int n = md.getColumnCount();
List<String> names = new ArrayList<>();
for (int i = 1; i <= n; i++) {
names.add(md.getColumnName(i));
}
assertEquals(Arrays.asList(expectedColumns.split(",")), names);
}
}
/**
* This test proves that unquoted table name is stored in lower case and quoted in mixed case
* @throws SQLException if something is going wrong
* see com.firebolt.jdbc.metadata.FireboltDatabaseMetadataTest#identifiersCase
* see com.firebolt.jdbc.metadata.FireboltDatabaseMetadataTest#quotedIdentifiersCase
*/
@ParameterizedTest
@CsvSource(value = {
"CREATE FACT TABLE Case_Test (x long);case_test;Case_Test;case_test",
"CREATE FACT TABLE \"Case_Test\" (x long);Case_Test;case_test;\"Case_Test\""
}, delimiter = ';')
void mixedCaseTable(String createTable, String expectedTableName, String unexpectedTableName, String dropTableName) throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
try {
statement.executeUpdate(createTable);
try (ResultSet rs = statement.executeQuery(format("select table_name from information_schema.tables where table_name = '%s'", expectedTableName))) {
assertTrue(rs.next());
assertEquals(expectedTableName, rs.getString(1));
assertFalse(rs.next());
}
try (ResultSet rs = statement.executeQuery(format("select table_name from information_schema.tables where table_name = '%s'", unexpectedTableName))) {
assertFalse(rs.next());
}
} finally {
statement.executeUpdate("DROP TABLE IF EXISTS " + dropTableName);
}
}
}
/**
* Validates that specific statement fails because used function is not supported. If specific test fails, i.e.
* the query succeeds this means that used function is supported now. In this case corresponding unit test should be
* fixed too.
* @param query the SQL statement that should fail
* @throws SQLException if something is going wrong
*/
@ParameterizedTest
@ValueSource(strings = {
"SELECT CONVERT(varchar, 3.14)" //com.firebolt.jdbc.metadata.FireboltDatabaseMetadataTest#supportsConvert
})
void failingQuery(String query) throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
assertThrows(SQLException.class, () -> statement.execute(query));
}
}
@Test
void caseInsensitiveGetter() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select table_schema, table_name as NAME from information_schema.tables")) {
while(rs.next()) {
assertEquals(rs.getString("table_schema"), rs.getString("TABLE_SCHEMA"));
assertEquals(rs.getString("table_schema"), rs.getString("Table_Schema"));
assertEquals(rs.getString("table_schema"), rs.getString("TaBlE_ScHeMa"));
assertEquals(rs.getString("name"), rs.getString("NAME"));
assertEquals(rs.getString("name"), rs.getString("NaMe"));
}
}
}
@ParameterizedTest
@ValueSource(ints = {1, 3, 5, 50})
void maxFieldSize(int maxFieldSize) throws SQLException {
String query = "select table_name from information_schema.tables order by table_name";
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
statement.setMaxFieldSize(maxFieldSize);
readValues(statement, query, 1).forEach(table -> assertThat(table.length(), Matchers.lessThanOrEqualTo(maxFieldSize)));
}
}
@ParameterizedTest
@ValueSource(ints = {0, -1, 100})
void unlimitedMaxFieldSize(int maxFieldSize) throws SQLException {
String query = "select table_name from information_schema.tables order by table_name";
try (Connection connection = createConnection();
Statement unlimitedStatement = connection.createStatement();
Statement limitedStatement = connection.createStatement()) {
limitedStatement.setMaxFieldSize(maxFieldSize);
assertEquals(readValues(unlimitedStatement, query, 1), readValues(limitedStatement, query, 1));
}
}
@Test
@Tag(TestTag.V2)
@EnvironmentCondition(value = "4.16.0", attribute = databaseVersion, comparison = EnvironmentCondition.Comparison.GE)
void canUseStatementTimeout() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
statement.execute("set statement_timeout=1");
ResultSet resultSet = statement.executeQuery("SELECT * FROM GENERATE_SERIES(1, 10000000);");
boolean errorFound = false;
while (resultSet.next()) {
String object = resultSet.getString(1);
if (object.contains("Query was canceled with reason 'Query timeout expired (1 ms)")) {
errorFound = true;
}
}
assertTrue(errorFound, "Did not find the error for query timing out");
}
}
@Test
@Tag(TestTag.V2)
@EnvironmentCondition(value = "4.16.0", attribute = databaseVersion, comparison = EnvironmentCondition.Comparison.GE)
void canUseStatementQueryTimeout() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
statement.setQueryTimeout(1);
ResultSet resultSet = statement.executeQuery("SELECT * FROM GENERATE_SERIES(1, 10000000);");
boolean errorFound = false;
while (resultSet.next()) {
String object = resultSet.getString(1);
if (object.contains("Query was canceled with reason 'Query timeout expired (1 ms)")) {
errorFound = true;
}
}
assertTrue(errorFound, "Did not find the error for query timing out");
}
}
@Test
@Tag(TestTag.V2)
@EnvironmentCondition(value = "4.16.0", attribute = databaseVersion, comparison = EnvironmentCondition.Comparison.GE)
void canExecuteStatementWithoutTimeout() throws SQLException {
try (Connection connection = createConnection(); Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SELECT * FROM GENERATE_SERIES(1, 10000000);");
int lastNumberReturned = 0;
while (resultSet.next()) {
lastNumberReturned++;
}
assertEquals(1000000, lastNumberReturned);
}
}
private Collection<String> readValues(Statement statement, String query, int columnIndex) throws SQLException {
List<String> values = new ArrayList<>();
try (ResultSet rs = statement.executeQuery(query)) {
while(rs.next()) {
values.add(rs.getString(columnIndex));
}
}
return values;
}
}