diff --git a/src/test/java/net/snowflake/client/core/SFArrowResultSetIT.java b/src/test/java/net/snowflake/client/core/SFArrowResultSetIT.java index 8e034675d..af6ac5219 100644 --- a/src/test/java/net/snowflake/client/core/SFArrowResultSetIT.java +++ b/src/test/java/net/snowflake/client/core/SFArrowResultSetIT.java @@ -3,7 +3,6 @@ */ package net.snowflake.client.core; -import static net.snowflake.client.AbstractDriverIT.getConnection; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -16,7 +15,6 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.time.Instant; @@ -32,6 +30,7 @@ import net.snowflake.client.SkipOnThinJar; import net.snowflake.client.category.TestCategoryArrow; import net.snowflake.client.jdbc.ArrowResultChunk; +import net.snowflake.client.jdbc.BaseJDBCWithSharedConnectionIT; import net.snowflake.client.jdbc.ErrorCode; import net.snowflake.client.jdbc.SnowflakeResultChunk; import net.snowflake.client.jdbc.SnowflakeResultSet; @@ -70,7 +69,7 @@ import org.junit.rules.TemporaryFolder; @Category(TestCategoryArrow.class) -public class SFArrowResultSetIT { +public class SFArrowResultSetIT extends BaseJDBCWithSharedConnectionIT { /** Necessary to conditional ignore tests */ @Rule public ConditionalIgnoreRule rule = new ConditionalIgnoreRule(); @@ -595,155 +594,157 @@ private void writeTimestampStructToField( @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = SkipOnThinJar.class) public void testSortedResultChunkWithStructVectors() throws Throwable { - Connection con = getConnection(); - Statement statement = con.createStatement(); - statement.execute("create or replace table teststructtimestamp (t1 timestamp_ltz)"); - ResultSet rs = statement.executeQuery("select * from teststructtimestamp"); - List resultSetSerializables = - ((SnowflakeResultSet) rs).getResultSetSerializables(100 * 1024 * 1024); - SnowflakeResultSetSerializableV1 resultSetSerializable = - (SnowflakeResultSetSerializableV1) resultSetSerializables.get(0); + try (Statement statement = connection.createStatement()) { + statement.execute("create or replace table teststructtimestamp (t1 timestamp_ltz)"); + try (ResultSet rs = statement.executeQuery("select * from teststructtimestamp")) { + List resultSetSerializables = + ((SnowflakeResultSet) rs).getResultSetSerializables(100 * 1024 * 1024); + SnowflakeResultSetSerializableV1 resultSetSerializable = + (SnowflakeResultSetSerializableV1) resultSetSerializables.get(0); - Map customFieldMeta = new HashMap<>(); - customFieldMeta.put("logicalType", "TIMESTAMP_LTZ"); - customFieldMeta.put("scale", "38"); - // test normal date - FieldType fieldType = - new FieldType(true, Types.MinorType.BIGINT.getType(), null, customFieldMeta); - FieldType fieldType2 = - new FieldType(true, Types.MinorType.INT.getType(), null, customFieldMeta); + Map customFieldMeta = new HashMap<>(); + customFieldMeta.put("logicalType", "TIMESTAMP_LTZ"); + customFieldMeta.put("scale", "38"); + // test normal date + FieldType fieldType = + new FieldType(true, Types.MinorType.BIGINT.getType(), null, customFieldMeta); + FieldType fieldType2 = + new FieldType(true, Types.MinorType.INT.getType(), null, customFieldMeta); - StructVector structVector = StructVector.empty("testListVector", allocator); - List fieldList = new LinkedList(); - Field bigIntField = new Field("epoch", fieldType, null); + StructVector structVector = StructVector.empty("testListVector", allocator); + List fieldList = new LinkedList(); + Field bigIntField = new Field("epoch", fieldType, null); - Field intField = new Field("fraction", fieldType2, null); + Field intField = new Field("fraction", fieldType2, null); - fieldList.add(bigIntField); - fieldList.add(intField); + fieldList.add(bigIntField); + fieldList.add(intField); - FieldType structFieldType = - new FieldType(true, Types.MinorType.STRUCT.getType(), null, customFieldMeta); - Field structField = new Field("timestamp", structFieldType, fieldList); + FieldType structFieldType = + new FieldType(true, Types.MinorType.STRUCT.getType(), null, customFieldMeta); + Field structField = new Field("timestamp", structFieldType, fieldList); - structVector.initializeChildrenFromFields(fieldList); + structVector.initializeChildrenFromFields(fieldList); - List fieldListMajor = new LinkedList(); - fieldListMajor.add(structField); - Schema dataSchema = new Schema(fieldList); - Object[][] data = generateData(dataSchema, 1000); + List fieldListMajor = new LinkedList(); + fieldListMajor.add(structField); + Schema dataSchema = new Schema(fieldList); + Object[][] data = generateData(dataSchema, 1000); - Schema schema = new Schema(fieldListMajor); + Schema schema = new Schema(fieldListMajor); - File file = createArrowFile("testTimestamp", schema, data, 10); + File file = createArrowFile("testTimestamp", schema, data, 10); - int dataSize = (int) file.length(); - byte[] dataBytes = new byte[dataSize]; + int dataSize = (int) file.length(); + byte[] dataBytes = new byte[dataSize]; - InputStream is = new FileInputStream(file); - is.read(dataBytes, 0, dataSize); + InputStream is = new FileInputStream(file); + is.read(dataBytes, 0, dataSize); - resultSetSerializable.setRootAllocator(new RootAllocator(Long.MAX_VALUE)); - resultSetSerializable.setFirstChunkStringData(Base64.getEncoder().encodeToString(dataBytes)); - resultSetSerializable.setFirstChunkByteData(dataBytes); - resultSetSerializable.setChunkFileCount(0); + resultSetSerializable.setRootAllocator(new RootAllocator(Long.MAX_VALUE)); + resultSetSerializable.setFirstChunkStringData( + Base64.getEncoder().encodeToString(dataBytes)); + resultSetSerializable.setFirstChunkByteData(dataBytes); + resultSetSerializable.setChunkFileCount(0); - SFArrowResultSet resultSet = - new SFArrowResultSet(resultSetSerializable, new NoOpTelemetryClient(), true); + SFArrowResultSet resultSet = + new SFArrowResultSet(resultSetSerializable, new NoOpTelemetryClient(), true); - for (int i = 0; i < 1000; i++) { - resultSet.next(); + for (int i = 0; i < 1000; i++) { + resultSet.next(); + } + // We inserted a null row at the beginning so when sorted, the last row should be null + assertEquals(null, resultSet.getObject(1)); + assertFalse(resultSet.next()); + statement.execute("drop table teststructtimestamp;"); + } } - // We inserted a null row at the beginning so when sorted, the last row should be null - assertEquals(null, resultSet.getObject(1)); - assertFalse(resultSet.next()); - statement.execute("drop table teststructtimestamp;"); - con.close(); } /** Test that the first chunk can be sorted */ @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = SkipOnThinJar.class) public void testSortedResultChunk() throws Throwable { - Connection con = getConnection(); - Statement statement = con.createStatement(); - statement.execute( - "create or replace table alltypes (i1 int, d1 date, b1 bigint, f1 float, s1 smallint, t1 tinyint, b2 binary, t2 text, b3 boolean, d2 decimal)"); - ResultSet rs = statement.executeQuery("select * from alltypes"); - List resultSetSerializables = - ((SnowflakeResultSet) rs).getResultSetSerializables(100 * 1024 * 1024); - SnowflakeResultSetSerializableV1 resultSetSerializable = - (SnowflakeResultSetSerializableV1) resultSetSerializables.get(0); - - List fieldList = new ArrayList<>(); - Map customFieldMeta = new HashMap<>(); - customFieldMeta.put("logicalType", "FIXED"); - customFieldMeta.put("scale", "0"); - FieldType type = new FieldType(false, Types.MinorType.INT.getType(), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - customFieldMeta.put("logicalType", "DATE"); - type = new FieldType(false, Types.MinorType.DATEDAY.getType(), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - customFieldMeta.put("logicalType", "FIXED"); - type = new FieldType(false, Types.MinorType.BIGINT.getType(), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - customFieldMeta.put("logicalType", "REAL"); - type = new FieldType(false, Types.MinorType.FLOAT8.getType(), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - customFieldMeta.put("logicalType", "FIXED"); - type = new FieldType(false, Types.MinorType.SMALLINT.getType(), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - customFieldMeta.put("logicalType", "FIXED"); - type = new FieldType(false, Types.MinorType.TINYINT.getType(), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - customFieldMeta.put("logicalType", "BINARY"); - type = new FieldType(false, Types.MinorType.VARBINARY.getType(), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - customFieldMeta.put("logicalType", "TEXT"); - type = new FieldType(false, Types.MinorType.VARCHAR.getType(), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - customFieldMeta.put("logicalType", "BOOLEAN"); - type = new FieldType(false, Types.MinorType.BIT.getType(), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - customFieldMeta.put("logicalType", "REAL"); - type = new FieldType(false, new ArrowType.Decimal(38, 16, 128), null, customFieldMeta); - fieldList.add(new Field("", type, null)); - - Schema schema = new Schema(fieldList); - - Object[][] data = generateData(schema, 1000); - File file = createArrowFile("testVectorTypes", schema, data, 10); - - int dataSize = (int) file.length(); - byte[] dataBytes = new byte[dataSize]; - - InputStream is = new FileInputStream(file); - is.read(dataBytes, 0, dataSize); - - resultSetSerializable.setRootAllocator(new RootAllocator(Long.MAX_VALUE)); - resultSetSerializable.setFirstChunkStringData(Base64.getEncoder().encodeToString(dataBytes)); - resultSetSerializable.setFirstChunkByteData(dataBytes); - resultSetSerializable.setChunkFileCount(0); - - SFArrowResultSet resultSet = - new SFArrowResultSet(resultSetSerializable, new NoOpTelemetryClient(), true); - - for (int i = 0; i < 1000; i++) { - resultSet.next(); + try (Statement statement = connection.createStatement()) { + statement.execute( + "create or replace table alltypes (i1 int, d1 date, b1 bigint, f1 float, s1 smallint, t1 tinyint, b2 binary, t2 text, b3 boolean, d2 decimal)"); + try (ResultSet rs = statement.executeQuery("select * from alltypes")) { + List resultSetSerializables = + ((SnowflakeResultSet) rs).getResultSetSerializables(100 * 1024 * 1024); + SnowflakeResultSetSerializableV1 resultSetSerializable = + (SnowflakeResultSetSerializableV1) resultSetSerializables.get(0); + + List fieldList = new ArrayList<>(); + Map customFieldMeta = new HashMap<>(); + customFieldMeta.put("logicalType", "FIXED"); + customFieldMeta.put("scale", "0"); + FieldType type = new FieldType(false, Types.MinorType.INT.getType(), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + customFieldMeta.put("logicalType", "DATE"); + type = new FieldType(false, Types.MinorType.DATEDAY.getType(), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + customFieldMeta.put("logicalType", "FIXED"); + type = new FieldType(false, Types.MinorType.BIGINT.getType(), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + customFieldMeta.put("logicalType", "REAL"); + type = new FieldType(false, Types.MinorType.FLOAT8.getType(), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + customFieldMeta.put("logicalType", "FIXED"); + type = new FieldType(false, Types.MinorType.SMALLINT.getType(), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + customFieldMeta.put("logicalType", "FIXED"); + type = new FieldType(false, Types.MinorType.TINYINT.getType(), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + customFieldMeta.put("logicalType", "BINARY"); + type = new FieldType(false, Types.MinorType.VARBINARY.getType(), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + customFieldMeta.put("logicalType", "TEXT"); + type = new FieldType(false, Types.MinorType.VARCHAR.getType(), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + customFieldMeta.put("logicalType", "BOOLEAN"); + type = new FieldType(false, Types.MinorType.BIT.getType(), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + customFieldMeta.put("logicalType", "REAL"); + type = new FieldType(false, new ArrowType.Decimal(38, 16, 128), null, customFieldMeta); + fieldList.add(new Field("", type, null)); + + Schema schema = new Schema(fieldList); + + Object[][] data = generateData(schema, 1000); + File file = createArrowFile("testVectorTypes", schema, data, 10); + + int dataSize = (int) file.length(); + byte[] dataBytes = new byte[dataSize]; + + InputStream is = new FileInputStream(file); + is.read(dataBytes, 0, dataSize); + + resultSetSerializable.setRootAllocator(new RootAllocator(Long.MAX_VALUE)); + resultSetSerializable.setFirstChunkStringData( + Base64.getEncoder().encodeToString(dataBytes)); + resultSetSerializable.setFirstChunkByteData(dataBytes); + resultSetSerializable.setChunkFileCount(0); + + SFArrowResultSet resultSet = + new SFArrowResultSet(resultSetSerializable, new NoOpTelemetryClient(), true); + + for (int i = 0; i < 1000; i++) { + resultSet.next(); + } + // We inserted a null row at the beginning so when sorted, the last row should be null + assertEquals(null, resultSet.getObject(1)); + assertFalse(resultSet.next()); + statement.execute("drop table alltypes;"); + } } - // We inserted a null row at the beginning so when sorted, the last row should be null - assertEquals(null, resultSet.getObject(1)); - assertFalse(resultSet.next()); - statement.execute("drop table alltypes;"); - con.close(); } } diff --git a/src/test/java/net/snowflake/client/jdbc/BindingDataIT.java b/src/test/java/net/snowflake/client/jdbc/BindingDataIT.java index 858e308ed..c2a8bc3ee 100644 --- a/src/test/java/net/snowflake/client/jdbc/BindingDataIT.java +++ b/src/test/java/net/snowflake/client/jdbc/BindingDataIT.java @@ -9,7 +9,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -19,7 +18,6 @@ import java.sql.Types; import java.util.Calendar; import java.util.TimeZone; -import net.snowflake.client.AbstractDriverIT; import net.snowflake.client.category.TestCategoryOthers; import org.junit.Test; import org.junit.experimental.categories.Category; @@ -31,13 +29,12 @@ /** Integration tests for binding variable */ @RunWith(Theories.class) @Category(TestCategoryOthers.class) -public class BindingDataIT extends AbstractDriverIT { +public class BindingDataIT extends BaseJDBCWithSharedConnectionIT { @DataPoints public static short[] shortValues = {0, 1, -1, Short.MIN_VALUE, Short.MAX_VALUE}; @Theory public void testBindShort(short shortValue) throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_short(c1 number)"); @@ -63,8 +60,7 @@ public void testBindShort(short shortValue) throws SQLException { @Theory public void testBindShortViaSetObject(short shortValue) throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_short(c1 number)"); @@ -92,8 +88,7 @@ public void testBindShortViaSetObject(short shortValue) throws SQLException { @Theory public void testBindInt(int intValue) throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_int(c1 number)"); @@ -122,8 +117,7 @@ public void testBindInt(int intValue) throws SQLException { @Theory public void testBindByte(byte byteValue) throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_byte(c1 integer)"); @@ -149,8 +143,7 @@ public void testBindByte(byte byteValue) throws SQLException { @Test public void testBindNull() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_null(id number, val " + "number)"); @@ -204,8 +197,7 @@ public void testBindNull() throws SQLException { @Theory public void testBindTime(Time timeVal) throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_time(c1 time)"); @@ -238,8 +230,7 @@ public void testBindTimeWithCalendar(Time timeVal) throws SQLException { Calendar utcCal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); Calendar laCal = Calendar.getInstance(TimeZone.getTimeZone("PST")); - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_time_calendar(c1 " + "time)"); @@ -267,8 +258,7 @@ public void testBindTimeWithCalendar(Time timeVal) throws SQLException { @Theory public void testBindTimeViaSetObject(Time timeVal) throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_time(c1 time)"); @@ -294,8 +284,7 @@ public void testBindTimeViaSetObject(Time timeVal) throws SQLException { @Theory public void testBindTimeViaSetObjectCast(Time timeVal) throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_time(c1 time)"); @@ -332,8 +321,7 @@ public void testBindTimeViaSetObjectCast(Time timeVal) throws SQLException { @Theory public void testBindDate(Date dateValue) throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_date(c1 date)"); @@ -362,8 +350,7 @@ public void testBindDate(Date dateValue) throws SQLException { public void testBindDateWithCalendar(Date dateValue) throws SQLException { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_date(c1 date)"); @@ -390,8 +377,7 @@ public void testBindDateWithCalendar(Date dateValue) throws SQLException { @Theory public void testBindObjectWithScaleZero(int intValue) throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_bind_object_0(c1 number)"); @@ -419,8 +405,7 @@ public void testBindObjectWithScaleZero(int intValue) throws SQLException { /** Binding null as all types. */ @Test public void testBindNullForAllTypes() throws Throwable { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute( "create or replace table TEST_BIND_ALL_TYPES(C0 string," + "C1 number(20, 3), C2 INTEGER, C3 double, C4 varchar(1000)," diff --git a/src/test/java/net/snowflake/client/jdbc/MultiStatementIT.java b/src/test/java/net/snowflake/client/jdbc/MultiStatementIT.java index c090bab03..06ccc4196 100644 --- a/src/test/java/net/snowflake/client/jdbc/MultiStatementIT.java +++ b/src/test/java/net/snowflake/client/jdbc/MultiStatementIT.java @@ -12,7 +12,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -21,26 +20,25 @@ import net.snowflake.client.core.SFSession; import net.snowflake.common.core.SqlState; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; /** Multi Statement tests */ @Category(TestCategoryStatement.class) -public class MultiStatementIT extends BaseJDBCTest { +public class MultiStatementIT extends BaseJDBCWithSharedConnectionIT { protected static String queryResultFormat = "json"; - public static Connection getConnection() throws SQLException { - Connection conn = BaseJDBCTest.getConnection(); - try (Statement stmt = conn.createStatement()) { + @Before + public void setQueryResultFormat() throws SQLException { + try (Statement stmt = connection.createStatement()) { stmt.execute("alter session set jdbc_query_result_format = '" + queryResultFormat + "'"); } - return conn; } @Test public void testMultiStmtExecuteUpdateFail() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { String multiStmtQuery = "select 1;\n" + "create or replace temporary table test_multi (cola int);\n" @@ -60,8 +58,7 @@ public void testMultiStmtExecuteUpdateFail() throws SQLException { @Test public void testMultiStmtExecuteQueryFail() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { String multiStmtQuery = "create or replace temporary table test_multi (cola int);\n" + "insert into test_multi VALUES (1), (2);\n" @@ -80,8 +77,7 @@ public void testMultiStmtExecuteQueryFail() throws SQLException { @Test public void testMultiStmtSetUnset() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { // setting session variable should propagate outside of query statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); @@ -115,8 +111,7 @@ public void testMultiStmtSetUnset() throws SQLException { @Test public void testMultiStmtParseError() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute("set testvar = 1"); try { @@ -136,8 +131,7 @@ public void testMultiStmtParseError() throws SQLException { @Test public void testMultiStmtExecError() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 3); // fails during execution (javascript invokes statement where it gets typechecked) @@ -158,8 +152,7 @@ public void testMultiStmtExecError() throws SQLException { @Test public void testMultiStmtTempTable() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { String entry = "success"; statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); @@ -178,8 +171,7 @@ public void testMultiStmtTempTable() throws SQLException { @Test public void testMultiStmtUseStmt() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { SFSession session = statement.getConnection().unwrap(SnowflakeConnectionV1.class).getSfSession(); @@ -212,8 +204,7 @@ public void testMultiStmtUseStmt() throws SQLException { @Test public void testMultiStmtAlterSessionParams() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { SFSession session = statement.getConnection().unwrap(SnowflakeConnectionV1.class).getSfSession(); @@ -232,8 +223,7 @@ public void testMultiStmtAlterSessionParams() throws SQLException { @Test public void testMultiStmtMultiLine() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { // these statements should not fail statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); statement.execute("select 1;\nselect 2"); @@ -245,8 +235,7 @@ public void testMultiStmtMultiLine() throws SQLException { @Test public void testMultiStmtQuotes() throws SQLException { // test various quotation usage and ensure they succeed - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); statement.execute( "create or replace temporary table \"test_multi\" (cola string); select * from \"test_multi\""); @@ -259,53 +248,56 @@ public void testMultiStmtQuotes() throws SQLException { @Test public void testMultiStmtCommitRollback() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { - statement.execute("create or replace table test_multi (cola string)"); + statement.execute("create or replace table test_multi_commit_rollback (cola string)"); statement.execute("begin"); - statement.execute("insert into test_multi values ('abc')"); + statement.execute("insert into test_multi_commit_rollback values ('abc')"); // "commit" inside multistatement commits previous DML calls statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); - statement.execute("insert into test_multi values ('def'); commit"); + statement.execute("insert into test_multi_commit_rollback values ('def'); commit"); statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 1); statement.execute("rollback"); - try (ResultSet rs = statement.executeQuery("select count(*) from test_multi")) { + try (ResultSet rs = + statement.executeQuery("select count(*) from test_multi_commit_rollback")) { assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); } - statement.execute("create or replace table test_multi (cola string)"); + statement.execute("create or replace table test_multi_commit_rollback (cola string)"); statement.execute("begin"); - statement.execute("insert into test_multi values ('abc')"); + statement.execute("insert into test_multi_commit_rollback values ('abc')"); // "rollback" inside multistatement rolls back previous DML calls statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); - statement.execute("insert into test_multi values ('def'); rollback"); + statement.execute("insert into test_multi_commit_rollback values ('def'); rollback"); statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 1); statement.execute("commit"); - try (ResultSet rs = statement.executeQuery("select count(*) from test_multi")) { + try (ResultSet rs = + statement.executeQuery("select count(*) from test_multi_commit_rollback")) { assertTrue(rs.next()); assertEquals(0, rs.getInt(1)); } - statement.execute("create or replace table test_multi (cola string)"); + statement.execute("create or replace table test_multi_commit_rollback (cola string)"); // open transaction inside multistatement continues after statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); - statement.execute("begin; insert into test_multi values ('abc')"); + statement.execute("begin; insert into test_multi_commit_rollback values ('abc')"); statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 1); - statement.execute("insert into test_multi values ('def')"); + statement.execute("insert into test_multi_commit_rollback values ('def')"); statement.execute("commit"); - try (ResultSet rs = statement.executeQuery("select count(*) from test_multi")) { + try (ResultSet rs = + statement.executeQuery("select count(*) from test_multi_commit_rollback")) { assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); } - statement.execute("create or replace table test_multi (cola string)"); + statement.execute("create or replace table test_multi_commit_rollback (cola string)"); // open transaction inside multistatement continues after statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); - statement.execute("begin; insert into test_multi values ('abc')"); + statement.execute("begin; insert into test_multi_commit_rollback values ('abc')"); statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 1); - statement.execute("insert into test_multi values ('def')"); + statement.execute("insert into test_multi_commit_rollback values ('def')"); statement.execute("rollback"); - try (ResultSet rs = statement.executeQuery("select count(*) from test_multi")) { + try (ResultSet rs = + statement.executeQuery("select count(*) from test_multi_commit_rollback")) { assertTrue(rs.next()); assertEquals(0, rs.getInt(1)); } @@ -314,52 +306,55 @@ public void testMultiStmtCommitRollback() throws SQLException { @Test public void testMultiStmtCommitRollbackNoAutocommit() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { connection.setAutoCommit(false); - statement.execute("create or replace table test_multi (cola string)"); - statement.execute("insert into test_multi values ('abc')"); + statement.execute("create or replace table test_multi_commit_rollback (cola string)"); + statement.execute("insert into test_multi_commit_rollback values ('abc')"); // "commit" inside multistatement commits previous DML calls statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); - statement.execute("insert into test_multi values ('def'); commit"); + statement.execute("insert into test_multi_commit_rollback values ('def'); commit"); statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 1); statement.execute("rollback"); - try (ResultSet rs = statement.executeQuery("select count(*) from test_multi")) { + try (ResultSet rs = + statement.executeQuery("select count(*) from test_multi_commit_rollback")) { assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); } - statement.execute("create or replace table test_multi (cola string)"); - statement.execute("insert into test_multi values ('abc')"); + statement.execute("create or replace table test_multi_commit_rollback (cola string)"); + statement.execute("insert into test_multi_commit_rollback values ('abc')"); // "rollback" inside multistatement rolls back previous DML calls statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); - statement.execute("insert into test_multi values ('def'); rollback"); + statement.execute("insert into test_multi_commit_rollback values ('def'); rollback"); statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 1); statement.execute("commit"); - try (ResultSet rs = statement.executeQuery("select count(*) from test_multi")) { + try (ResultSet rs = + statement.executeQuery("select count(*) from test_multi_commit_rollback")) { assertTrue(rs.next()); assertEquals(0, rs.getInt(1)); } - statement.execute("create or replace table test_multi (cola string)"); + statement.execute("create or replace table test_multi_commit_rollback (cola string)"); // open transaction inside multistatement continues after statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); statement.execute( - "insert into test_multi values ('abc'); insert into test_multi values ('def')"); + "insert into test_multi_commit_rollback values ('abc'); insert into test_multi_commit_rollback values ('def')"); statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 1); statement.execute("commit"); - try (ResultSet rs = statement.executeQuery("select count(*) from test_multi")) { + try (ResultSet rs = + statement.executeQuery("select count(*) from test_multi_commit_rollback")) { assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); } - statement.execute("create or replace table test_multi (cola string)"); + statement.execute("create or replace table test_multi_commit_rollback (cola string)"); // open transaction inside multistatement continues after statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 2); statement.execute( - "insert into test_multi values ('abc'); insert into test_multi values ('def')"); + "insert into test_multi_commit_rollback values ('abc'); insert into test_multi_commit_rollback values ('def')"); statement.unwrap(SnowflakeStatement.class).setParameter("MULTI_STATEMENT_COUNT", 1); statement.execute("rollback"); - try (ResultSet rs = statement.executeQuery("select count(*) from test_multi")) { + try (ResultSet rs = + statement.executeQuery("select count(*) from test_multi_commit_rollback")) { assertTrue(rs.next()); assertEquals(0, rs.getInt(1)); } @@ -371,8 +366,7 @@ public void testMultiStmtLarge() throws SQLException { // this test verifies that multiple-statement support does not break // with many statements // it also ensures that results are returned in the correct order - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { StringBuilder multiStmtBuilder = new StringBuilder(); String query = "SELECT %d;"; for (int i = 0; i < 100; i++) { @@ -401,8 +395,7 @@ public void testMultiStmtLarge() throws SQLException { @Test public void testMultiStmtCountNotMatch() throws SQLException { - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("select 1; select 2; select 3"); fail(); @@ -429,8 +422,7 @@ public void testMultiStmtCountNotMatch() throws SQLException { public void testInvalidParameterCount() throws SQLException { String userName = null; String accountName = null; - try (Connection connection = getConnection(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try (ResultSet rs = statement.executeQuery("select current_account_locator()")) { assertTrue(rs.next()); diff --git a/src/test/java/net/snowflake/client/jdbc/ResultSet0IT.java b/src/test/java/net/snowflake/client/jdbc/ResultSet0IT.java index 62148327d..90cc98aa6 100644 --- a/src/test/java/net/snowflake/client/jdbc/ResultSet0IT.java +++ b/src/test/java/net/snowflake/client/jdbc/ResultSet0IT.java @@ -20,15 +20,6 @@ public class ResultSet0IT extends BaseJDBCWithSharedConnectionIT { private final String queryResultFormat; - // TODO: Clean up init() methods when updating other test classes to use a common connection. - public Connection init() throws SQLException { - Connection conn = BaseJDBCTest.getConnection(BaseJDBCTest.DONT_INJECT_SOCKET_TIMEOUT); - try (Statement stmt = conn.createStatement()) { - stmt.execute("alter session set jdbc_query_result_format = '" + queryResultFormat + "'"); - } - return conn; - } - public Connection init(Properties paramProperties) throws SQLException { Connection conn = BaseJDBCTest.getConnection(DONT_INJECT_SOCKET_TIMEOUT, paramProperties, false, false); @@ -42,6 +33,7 @@ public Connection init(Properties paramProperties) throws SQLException { public void setUp() throws SQLException { try (Statement statement = connection.createStatement()) { + statement.execute("alter session set jdbc_query_result_format = '" + queryResultFormat + "'"); // TEST_RS statement.execute("create or replace table test_rs (colA string)"); statement.execute("insert into test_rs values('rowOne')"); diff --git a/src/test/java/net/snowflake/client/jdbc/ResultSetIT.java b/src/test/java/net/snowflake/client/jdbc/ResultSetIT.java index 3e5343117..193246368 100644 --- a/src/test/java/net/snowflake/client/jdbc/ResultSetIT.java +++ b/src/test/java/net/snowflake/client/jdbc/ResultSetIT.java @@ -57,8 +57,7 @@ public ResultSetIT() { @Test public void testFindColumn() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement(); + try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(selectAllSQL)) { assertEquals(1, resultSet.findColumn("COLA")); } @@ -66,8 +65,7 @@ public void testFindColumn() throws SQLException { @Test public void testGetColumnClassNameForBinary() throws Throwable { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table bintable (b binary)"); statement.execute("insert into bintable values ('00f1f2')"); @@ -100,72 +98,68 @@ public void testGetMethod() throws Throwable { double bigDouble = Double.MAX_VALUE; float bigFloat = Float.MAX_VALUE; - try (Connection connection = init()) { - Clob clob = connection.createClob(); - clob.setString(1, "hello world"); - try (Statement statement = connection.createStatement()) { - try { - statement.execute( - "create or replace table test_get(colA integer, colB number, colC number, " - + "colD string, colE double, colF float, colG boolean, colH text)"); - - try (PreparedStatement prepStatement = connection.prepareStatement(prepInsertString)) { - prepStatement.setInt(1, bigInt); - prepStatement.setLong(2, bigLong); - prepStatement.setLong(3, bigShort); - prepStatement.setString(4, str); - prepStatement.setDouble(5, bigDouble); - prepStatement.setFloat(6, bigFloat); - prepStatement.setBoolean(7, true); - prepStatement.setClob(8, clob); - prepStatement.execute(); - - statement.execute("select * from test_get"); - try (ResultSet resultSet = statement.getResultSet()) { - assertTrue(resultSet.next()); - assertEquals(bigInt, resultSet.getInt(1)); - assertEquals(bigInt, resultSet.getInt("COLA")); - assertEquals(bigLong, resultSet.getLong(2)); - assertEquals(bigLong, resultSet.getLong("COLB")); - assertEquals(bigShort, resultSet.getShort(3)); - assertEquals(bigShort, resultSet.getShort("COLC")); - assertEquals(str, resultSet.getString(4)); - assertEquals(str, resultSet.getString("COLD")); - Reader reader = resultSet.getCharacterStream("COLD"); - char[] sample = new char[str.length()]; - - assertEquals(str.length(), reader.read(sample)); - assertEquals(str.charAt(0), sample[0]); - assertEquals(str, new String(sample)); - - // assertEquals(bigDouble, resultSet.getDouble(5), 0); - // assertEquals(bigDouble, resultSet.getDouble("COLE"), 0); - assertEquals(bigFloat, resultSet.getFloat(6), 0); - assertEquals(bigFloat, resultSet.getFloat("COLF"), 0); - assertTrue(resultSet.getBoolean(7)); - assertTrue(resultSet.getBoolean("COLG")); - assertEquals("hello world", resultSet.getClob("COLH").toString()); - - // test getStatement method - assertEquals(statement, resultSet.getStatement()); - } + Clob clob = connection.createClob(); + clob.setString(1, "hello world"); + try (Statement statement = connection.createStatement()) { + try { + statement.execute( + "create or replace table test_get(colA integer, colB number, colC number, " + + "colD string, colE double, colF float, colG boolean, colH text)"); + + try (PreparedStatement prepStatement = connection.prepareStatement(prepInsertString)) { + prepStatement.setInt(1, bigInt); + prepStatement.setLong(2, bigLong); + prepStatement.setLong(3, bigShort); + prepStatement.setString(4, str); + prepStatement.setDouble(5, bigDouble); + prepStatement.setFloat(6, bigFloat); + prepStatement.setBoolean(7, true); + prepStatement.setClob(8, clob); + prepStatement.execute(); + + statement.execute("select * from test_get"); + try (ResultSet resultSet = statement.getResultSet()) { + assertTrue(resultSet.next()); + assertEquals(bigInt, resultSet.getInt(1)); + assertEquals(bigInt, resultSet.getInt("COLA")); + assertEquals(bigLong, resultSet.getLong(2)); + assertEquals(bigLong, resultSet.getLong("COLB")); + assertEquals(bigShort, resultSet.getShort(3)); + assertEquals(bigShort, resultSet.getShort("COLC")); + assertEquals(str, resultSet.getString(4)); + assertEquals(str, resultSet.getString("COLD")); + Reader reader = resultSet.getCharacterStream("COLD"); + char[] sample = new char[str.length()]; + + assertEquals(str.length(), reader.read(sample)); + assertEquals(str.charAt(0), sample[0]); + assertEquals(str, new String(sample)); + + // assertEquals(bigDouble, resultSet.getDouble(5), 0); + // assertEquals(bigDouble, resultSet.getDouble("COLE"), 0); + assertEquals(bigFloat, resultSet.getFloat(6), 0); + assertEquals(bigFloat, resultSet.getFloat("COLF"), 0); + assertTrue(resultSet.getBoolean(7)); + assertTrue(resultSet.getBoolean("COLG")); + assertEquals("hello world", resultSet.getClob("COLH").toString()); + + // test getStatement method + assertEquals(statement, resultSet.getStatement()); } - } finally { - statement.execute("drop table if exists table_get"); } + } finally { + statement.execute("drop table if exists table_get"); } } } @Test public void testGetObjectOnDatabaseMetadataResultSet() throws SQLException { - try (Connection connection = init()) { - DatabaseMetaData databaseMetaData = connection.getMetaData(); - try (ResultSet resultSet = databaseMetaData.getTypeInfo()) { - assertTrue(resultSet.next()); - // SNOW-21375 "NULLABLE" Column is a SMALLINT TYPE - assertEquals(DatabaseMetaData.typeNullable, resultSet.getObject("NULLABLE")); - } + DatabaseMetaData databaseMetaData = connection.getMetaData(); + try (ResultSet resultSet = databaseMetaData.getTypeInfo()) { + assertTrue(resultSet.next()); + // SNOW-21375 "NULLABLE" Column is a SMALLINT TYPE + assertEquals(DatabaseMetaData.typeNullable, resultSet.getObject("NULLABLE")); } } @@ -377,8 +371,7 @@ public void testGetDouble() throws SQLException { @Test public void testGetBigDecimal() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute("create or replace table test_get(colA number(38,9))"); try (PreparedStatement preparedStatement = connection.prepareStatement("insert into test_get values(?)")) { @@ -435,8 +428,7 @@ public void testGetBigDecimal() throws SQLException { @Test public void testGetBigDecimalNegative() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_dec(colA time)"); try (PreparedStatement preparedStatement = @@ -464,8 +456,7 @@ public void testGetBigDecimalNegative() throws SQLException { @Test public void testCursorPosition() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute(selectAllSQL); try (ResultSet resultSet = statement.getResultSet()) { assertTrue(resultSet.next()); @@ -568,8 +559,7 @@ public void testGetBytesInBase64() throws Exception { // SNOW-31647 @Test public void testColumnMetaWithZeroPrecision() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute( "create or replace table testColDecimal(cola number(38, 0), " + "colb number(17, 5))"); @@ -590,8 +580,7 @@ public void testColumnMetaWithZeroPrecision() throws SQLException { @Test public void testGetObjectOnFixedView() throws Exception { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute( "create or replace table testFixedView" @@ -628,8 +617,7 @@ public void testGetObjectOnFixedView() throws Exception { @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testGetColumnDisplaySizeAndPrecision() throws SQLException { ResultSetMetaData resultSetMetaData = null; - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try (ResultSet resultSet = statement.executeQuery("select cast(1 as char)")) { resultSetMetaData = resultSet.getMetaData(); @@ -679,8 +667,7 @@ public void testGetColumnDisplaySizeAndPrecision() throws SQLException { @Test public void testGetBoolean() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute("create or replace table testBoolean(cola boolean)"); statement.execute("insert into testBoolean values(false)"); try (ResultSet resultSet = statement.executeQuery("select * from testBoolean")) { @@ -748,8 +735,7 @@ public void testGetBoolean() throws SQLException { @Test public void testGetClob() throws Throwable { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute("create or replace table testClob(cola text)"); statement.execute("insert into testClob values('hello world')"); statement.execute("insert into testClob values('hello world1')"); @@ -788,8 +774,7 @@ public void testGetClob() throws Throwable { @Test public void testFetchOnClosedResultSet() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { ResultSet resultSet = statement.executeQuery(selectAllSQL); assertFalse(resultSet.isClosed()); resultSet.close(); @@ -800,23 +785,21 @@ public void testFetchOnClosedResultSet() throws SQLException { @Test public void testReleaseDownloaderCurrentMemoryUsage() throws SQLException { - try (Connection connection = init()) { - final long initialMemoryUsage = SnowflakeChunkDownloader.getCurrentMemoryUsage(); + final long initialMemoryUsage = SnowflakeChunkDownloader.getCurrentMemoryUsage(); - try (Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { - statement.executeQuery( - "select current_date(), true,2345234, 2343.0, 'testrgint\\n\\t' from table(generator(rowcount=>1000000))"); + statement.executeQuery( + "select current_date(), true,2345234, 2343.0, 'testrgint\\n\\t' from table(generator(rowcount=>1000000))"); - assertThat( - "hold memory usage for the resultSet before close", - SnowflakeChunkDownloader.getCurrentMemoryUsage() - initialMemoryUsage >= 0); - } assertThat( - "closing statement didn't release memory allocated for result", - SnowflakeChunkDownloader.getCurrentMemoryUsage(), - equalTo(initialMemoryUsage)); + "hold memory usage for the resultSet before close", + SnowflakeChunkDownloader.getCurrentMemoryUsage() - initialMemoryUsage >= 0); } + assertThat( + "closing statement didn't release memory allocated for result", + SnowflakeChunkDownloader.getCurrentMemoryUsage(), + equalTo(initialMemoryUsage)); } @Test @@ -866,8 +849,7 @@ private void subTestResultColumnSearchCaseSensitive(String parameterName) throws @Test public void testInvalidColumnIndex() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement(); + try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(selectAllSQL)) { assertTrue(resultSet.next()); @@ -889,13 +871,13 @@ public void testInvalidColumnIndex() throws SQLException { /** SNOW-28882: wasNull was not set properly */ @Test public void testWasNull() throws Exception { - try (Connection con = init(); - ResultSet ret = - con.createStatement() - .executeQuery( - "select cast(1/nullif(0,0) as double)," - + "cast(1/nullif(0,0) as int), 100, " - + "cast(1/nullif(0,0) as number(8,2))")) { + try (ResultSet ret = + connection + .createStatement() + .executeQuery( + "select cast(1/nullif(0,0) as double)," + + "cast(1/nullif(0,0) as int), 100, " + + "cast(1/nullif(0,0) as number(8,2))")) { assertTrue(ret.next()); assertThat("Double value cannot be null", ret.getDouble(1), equalTo(0.0)); assertThat("wasNull should be true", ret.wasNull()); @@ -911,8 +893,7 @@ public void testWasNull() throws Exception { /** SNOW-28390 */ @Test public void testParseInfAndNaNNumber() throws Exception { - try (Connection con = init(); - Statement statement = con.createStatement()) { + try (Statement statement = connection.createStatement()) { try (ResultSet ret = statement.executeQuery("select to_double('inf'), to_double('-inf')")) { assertTrue(ret.next()); assertThat("Positive Infinite Number", ret.getDouble(1), equalTo(Double.POSITIVE_INFINITY)); @@ -932,8 +913,7 @@ public void testParseInfAndNaNNumber() throws Exception { @Test public void testTreatDecimalAsInt() throws Exception { ResultSetMetaData metaData; - try (Connection con = init(); - Statement statement = con.createStatement()) { + try (Statement statement = connection.createStatement()) { try (ResultSet ret = statement.executeQuery("select 1")) { metaData = ret.getMetaData(); @@ -945,13 +925,13 @@ public void testTreatDecimalAsInt() throws Exception { metaData = ret.getMetaData(); assertThat(metaData.getColumnType(1), equalTo(Types.DECIMAL)); } + statement.execute("alter session set jdbc_treat_decimal_as_int = true"); } } @Test public void testIsLast() throws Exception { - try (Connection con = init(); - Statement statement = con.createStatement()) { + try (Statement statement = connection.createStatement()) { try (ResultSet ret = statement.executeQuery("select * from orders_jdbc")) { assertTrue("should be before the first", ret.isBeforeFirst()); assertFalse("should not be the first", ret.isFirst()); @@ -1002,8 +982,7 @@ public void testIsLast() throws Exception { @Test public void testUpdateCountOnCopyCmd() throws Exception { - try (Connection con = init(); - Statement statement = con.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table testcopy(cola string)"); @@ -1024,8 +1003,7 @@ public void testUpdateCountOnCopyCmd() throws Exception { @Test public void testGetTimeNullTimestampAndTimestampNullTime() throws Throwable { - try (Connection con = init(); - Statement statement = con.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table testnullts(c1 timestamp, c2 time)"); statement.execute("insert into testnullts(c1, c2) values(null, null)"); @@ -1042,26 +1020,23 @@ public void testGetTimeNullTimestampAndTimestampNullTime() throws Throwable { @Test public void testNextNegative() throws SQLException { - try (Connection con = init()) { - try (ResultSet rs = con.createStatement().executeQuery("select 1")) { + try (ResultSet rs = connection.createStatement().executeQuery("select 1")) { + assertTrue(rs.next()); + System.setProperty("snowflake.enable_incident_test2", "true"); + try { assertTrue(rs.next()); - System.setProperty("snowflake.enable_incident_test2", "true"); - try { - assertTrue(rs.next()); - fail(); - } catch (SQLException ex) { - assertEquals(200014, ex.getErrorCode()); - } - System.setProperty("snowflake.enable_incident_test2", "false"); + fail(); + } catch (SQLException ex) { + assertEquals(200014, ex.getErrorCode()); } + System.setProperty("snowflake.enable_incident_test2", "false"); } } /** SNOW-1416051; Added in > 3.16.0 */ @Test public void shouldSerializeArrayAndObjectAsStringOnGetObject() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement(); + try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery( "select ARRAY_CONSTRUCT(1,2,3), OBJECT_CONSTRUCT('a', 4, 'b', 'test')")) { diff --git a/src/test/java/net/snowflake/client/jdbc/ResultSetLatestIT.java b/src/test/java/net/snowflake/client/jdbc/ResultSetLatestIT.java index efd185926..d82cd9ff2 100644 --- a/src/test/java/net/snowflake/client/jdbc/ResultSetLatestIT.java +++ b/src/test/java/net/snowflake/client/jdbc/ResultSetLatestIT.java @@ -217,59 +217,57 @@ public void testChunkDownloaderSetRetry() throws SQLException { @Test public void testMetadataAPIMetricCollection() throws SQLException, ExecutionException, InterruptedException { - try (Connection con = init()) { - Telemetry telemetry = - con.unwrap(SnowflakeConnectionV1.class).getSfSession().getTelemetryClient(); - DatabaseMetaData metadata = con.getMetaData(); - // Call one of the DatabaseMetadata API functions but for simplicity, ensure returned - // ResultSet - // is empty - metadata.getColumns("fakecatalog", "fakeschema", null, null); - LinkedList logs = ((TelemetryClient) telemetry).logBuffer(); - // No result set has been downloaded from server so no chunk downloader metrics have been - // collected - // Logs should contain 1 item: the data about the getColumns() parameters - assertEquals(logs.size(), 1); - // Assert the log is of type client_metadata_api_metrics - assertEquals( - logs.get(0).getMessage().get(TelemetryUtil.TYPE).textValue(), - TelemetryField.METADATA_METRICS.toString()); - // Assert function name and params match and that query id exists - assertEquals(logs.get(0).getMessage().get("function_name").textValue(), "getColumns"); - TestUtil.assertValidQueryId(logs.get(0).getMessage().get("query_id").textValue()); - JsonNode parameterValues = logs.get(0).getMessage().get("function_parameters"); - assertEquals(parameterValues.get("catalog").textValue(), "fakecatalog"); - assertEquals(parameterValues.get("schema").textValue(), "fakeschema"); - assertNull(parameterValues.get("general_name_pattern").textValue()); - assertNull(parameterValues.get("specific_name_pattern").textValue()); - - // send data to clear log for next test - telemetry.sendBatchAsync().get(); - assertEquals(0, ((TelemetryClient) telemetry).logBuffer().size()); - - String catalog = con.getCatalog(); - String schema = con.getSchema(); - metadata.getColumns(catalog, schema, null, null); - logs = ((TelemetryClient) telemetry).logBuffer(); - assertEquals(logs.size(), 2); - // first item in log buffer is metrics on time to consume first result set chunk - assertEquals( - logs.get(0).getMessage().get(TelemetryUtil.TYPE).textValue(), - TelemetryField.TIME_CONSUME_FIRST_RESULT.toString()); - // second item in log buffer is metrics on getProcedureColumns() parameters - // Assert the log is of type client_metadata_api_metrics - assertEquals( - logs.get(1).getMessage().get(TelemetryUtil.TYPE).textValue(), - TelemetryField.METADATA_METRICS.toString()); - // Assert function name and params match and that query id exists - assertEquals(logs.get(1).getMessage().get("function_name").textValue(), "getColumns"); - TestUtil.assertValidQueryId(logs.get(1).getMessage().get("query_id").textValue()); - parameterValues = logs.get(1).getMessage().get("function_parameters"); - assertEquals(parameterValues.get("catalog").textValue(), catalog); - assertEquals(parameterValues.get("schema").textValue(), schema); - assertNull(parameterValues.get("general_name_pattern").textValue()); - assertNull(parameterValues.get("specific_name_pattern").textValue()); - } + Telemetry telemetry = + connection.unwrap(SnowflakeConnectionV1.class).getSfSession().getTelemetryClient(); + DatabaseMetaData metadata = connection.getMetaData(); + // Call one of the DatabaseMetadata API functions but for simplicity, ensure returned + // ResultSet + // is empty + metadata.getColumns("fakecatalog", "fakeschema", null, null); + LinkedList logs = ((TelemetryClient) telemetry).logBuffer(); + // No result set has been downloaded from server so no chunk downloader metrics have been + // collected + // Logs should contain 1 item: the data about the getColumns() parameters + assertEquals(logs.size(), 1); + // Assert the log is of type client_metadata_api_metrics + assertEquals( + logs.get(0).getMessage().get(TelemetryUtil.TYPE).textValue(), + TelemetryField.METADATA_METRICS.toString()); + // Assert function name and params match and that query id exists + assertEquals(logs.get(0).getMessage().get("function_name").textValue(), "getColumns"); + TestUtil.assertValidQueryId(logs.get(0).getMessage().get("query_id").textValue()); + JsonNode parameterValues = logs.get(0).getMessage().get("function_parameters"); + assertEquals(parameterValues.get("catalog").textValue(), "fakecatalog"); + assertEquals(parameterValues.get("schema").textValue(), "fakeschema"); + assertNull(parameterValues.get("general_name_pattern").textValue()); + assertNull(parameterValues.get("specific_name_pattern").textValue()); + + // send data to clear log for next test + telemetry.sendBatchAsync().get(); + assertEquals(0, ((TelemetryClient) telemetry).logBuffer().size()); + + String catalog = connection.getCatalog(); + String schema = connection.getSchema(); + metadata.getColumns(catalog, schema, null, null); + logs = ((TelemetryClient) telemetry).logBuffer(); + assertEquals(logs.size(), 2); + // first item in log buffer is metrics on time to consume first result set chunk + assertEquals( + logs.get(0).getMessage().get(TelemetryUtil.TYPE).textValue(), + TelemetryField.TIME_CONSUME_FIRST_RESULT.toString()); + // second item in log buffer is metrics on getProcedureColumns() parameters + // Assert the log is of type client_metadata_api_metrics + assertEquals( + logs.get(1).getMessage().get(TelemetryUtil.TYPE).textValue(), + TelemetryField.METADATA_METRICS.toString()); + // Assert function name and params match and that query id exists + assertEquals(logs.get(1).getMessage().get("function_name").textValue(), "getColumns"); + TestUtil.assertValidQueryId(logs.get(1).getMessage().get("query_id").textValue()); + parameterValues = logs.get(1).getMessage().get("function_parameters"); + assertEquals(parameterValues.get("catalog").textValue(), catalog); + assertEquals(parameterValues.get("schema").textValue(), schema); + assertNull(parameterValues.get("general_name_pattern").textValue()); + assertNull(parameterValues.get("specific_name_pattern").textValue()); } /** @@ -280,8 +278,7 @@ public void testMetadataAPIMetricCollection() */ @Test public void testGetCharacterStreamNull() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute("create or replace table JDBC_NULL_CHARSTREAM (col1 varchar(16))"); statement.execute("insert into JDBC_NULL_CHARSTREAM values(NULL)"); try (ResultSet rs = statement.executeQuery("select * from JDBC_NULL_CHARSTREAM")) { @@ -298,8 +295,7 @@ public void testGetCharacterStreamNull() throws SQLException { */ @Test public void testMultipleChunks() throws Exception { - try (Connection con = init(); - Statement statement = con.createStatement(); + try (Statement statement = connection.createStatement(); // 10000 rows should be enough to force result into multiple chunks ResultSet resultSet = @@ -311,7 +307,7 @@ public void testMultipleChunks() throws Exception { } assertTrue(cnt >= 0); Telemetry telemetry = - con.unwrap(SnowflakeConnectionV1.class).getSfSession().getTelemetryClient(); + connection.unwrap(SnowflakeConnectionV1.class).getSfSession().getTelemetryClient(); LinkedList logs = ((TelemetryClient) telemetry).logBuffer(); // there should be a log for each of the following fields @@ -352,8 +348,7 @@ public void testMultipleChunks() throws Exception { @Test public void testResultSetMetadata() throws SQLException { final Map params = getConnectionParameters(); - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("create or replace table test_rsmd(colA number(20, 5), colB string)"); statement.execute("insert into test_rsmd values(1.00, 'str'),(2.00, 'str2')"); @@ -403,8 +398,7 @@ public void testResultSetMetadata() throws SQLException { */ @Test public void testEmptyResultSet() throws SQLException { - try (Connection con = init(); - Statement statement = con.createStatement(); + try (Statement statement = connection.createStatement(); // the only function that returns ResultSetV1.emptyResultSet() ResultSet rs = statement.getGeneratedKeys()) { assertFalse(rs.next()); @@ -546,8 +540,7 @@ public void testBytesCrossTypeTests() throws Exception { // 30s for timeout. This test usually finishes in around 10s. @Test(timeout = 30000) public void testResultChunkDownloaderException() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { // The generated resultSet must be big enough for triggering result chunk downloader String query = @@ -585,8 +578,7 @@ public void testResultChunkDownloaderException() throws SQLException { */ @Test public void testGetObjectWithBigInt() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute("alter session set jdbc_query_result_format ='json'"); // test with greatest possible number and greatest negative possible number String[] extremeNumbers = { @@ -618,8 +610,7 @@ private byte[] floatToByteArray(float i) { */ @Test public void testGetBigDecimalWithScale() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute("create or replace table test_get(colA number(38,9))"); try (PreparedStatement preparedStatement = connection.prepareStatement("insert into test_get values(?)")) { @@ -680,30 +671,28 @@ public void testGetDataTypeWithTimestampTz() throws Exception { */ @Test public void testGetEmptyOrNullClob() throws SQLException { - try (Connection connection = init()) { - Clob clob = connection.createClob(); - clob.setString(1, "hello world"); - Clob emptyClob = connection.createClob(); - emptyClob.setString(1, ""); - try (Statement statement = connection.createStatement()) { - statement.execute( - "create or replace table test_get_clob(colA varchar, colNull varchar, colEmpty text)"); - try (PreparedStatement preparedStatement = - connection.prepareStatement("insert into test_get_clob values(?, ?, ?)")) { - preparedStatement.setClob(1, clob); - preparedStatement.setString(2, null); - preparedStatement.setClob(3, emptyClob); - preparedStatement.execute(); - } - try (ResultSet resultSet = statement.executeQuery("select * from test_get_clob")) { - assertTrue(resultSet.next()); - assertEquals("hello world", resultSet.getClob(1).toString()); - assertEquals("hello world", resultSet.getClob("COLA").toString()); - assertNull(resultSet.getClob(2)); - assertNull(resultSet.getClob("COLNULL")); - assertEquals("", resultSet.getClob(3).toString()); - assertEquals("", resultSet.getClob("COLEMPTY").toString()); - } + Clob clob = connection.createClob(); + clob.setString(1, "hello world"); + Clob emptyClob = connection.createClob(); + emptyClob.setString(1, ""); + try (Statement statement = connection.createStatement()) { + statement.execute( + "create or replace table test_get_clob(colA varchar, colNull varchar, colEmpty text)"); + try (PreparedStatement preparedStatement = + connection.prepareStatement("insert into test_get_clob values(?, ?, ?)")) { + preparedStatement.setClob(1, clob); + preparedStatement.setString(2, null); + preparedStatement.setClob(3, emptyClob); + preparedStatement.execute(); + } + try (ResultSet resultSet = statement.executeQuery("select * from test_get_clob")) { + assertTrue(resultSet.next()); + assertEquals("hello world", resultSet.getClob(1).toString()); + assertEquals("hello world", resultSet.getClob("COLA").toString()); + assertNull(resultSet.getClob(2)); + assertNull(resultSet.getClob("COLNULL")); + assertEquals("", resultSet.getClob(3).toString()); + assertEquals("", resultSet.getClob("COLEMPTY").toString()); } } } @@ -716,21 +705,19 @@ public void testGetEmptyOrNullClob() throws SQLException { */ @Test public void testSetNullClob() throws SQLException { - try (Connection connection = init()) { - Clob clob = null; - try (Statement statement = connection.createStatement()) { - statement.execute("create or replace table test_set_clob(colNull varchar)"); - try (PreparedStatement preparedStatement = - connection.prepareStatement("insert into test_set_clob values(?)")) { - preparedStatement.setClob(1, clob); - preparedStatement.execute(); - } + Clob clob = null; + try (Statement statement = connection.createStatement()) { + statement.execute("create or replace table test_set_clob(colNull varchar)"); + try (PreparedStatement preparedStatement = + connection.prepareStatement("insert into test_set_clob values(?)")) { + preparedStatement.setClob(1, clob); + preparedStatement.execute(); + } - try (ResultSet resultSet = statement.executeQuery("select * from test_set_clob")) { - assertTrue(resultSet.next()); - assertNull(resultSet.getClob(1)); - assertNull(resultSet.getClob("COLNULL")); - } + try (ResultSet resultSet = statement.executeQuery("select * from test_set_clob")) { + assertTrue(resultSet.next()); + assertNull(resultSet.getClob(1)); + assertNull(resultSet.getClob("COLNULL")); } } } @@ -808,8 +795,7 @@ public void testCallStatementType() throws SQLException { */ @Test public void testNewFeaturesNotSupportedExeceptions() throws SQLException { - try (Connection con = init(); - Statement statement = con.createStatement(); + try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("select 1")) { expectSnowflakeLoggedFeatureNotSupportedException( rs.unwrap(SnowflakeResultSet.class)::getQueryErrorMessage); @@ -857,8 +843,7 @@ public void testNewFeaturesNotSupportedExeceptions() throws SQLException { @Test public void testInvalidUnWrap() throws SQLException { - try (Connection con = init(); - ResultSet rs = con.createStatement().executeQuery("select 1")) { + try (ResultSet rs = connection.createStatement().executeQuery("select 1")) { try { rs.unwrap(SnowflakeUtil.class); } catch (SQLException ex) { @@ -871,8 +856,7 @@ public void testInvalidUnWrap() throws SQLException { @Test public void testGetObjectJsonResult() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { try { statement.execute("alter session set jdbc_query_result_format ='json'"); statement.execute("create or replace table testObj (colA double, colB boolean)"); @@ -896,8 +880,7 @@ public void testGetObjectJsonResult() throws SQLException { @Test public void testMetadataIsCaseSensitive() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { String sampleCreateTableWithAllColTypes = "CREATE or replace TABLE case_sensitive (" @@ -1159,8 +1142,7 @@ public void testGetObjectForJSONResultFormatUsingJDBCDecimalAsInt() throws SQLEx @Test public void testGetObjectWithType() throws SQLException { - try (Connection connection = init(); - Statement statement = connection.createStatement()) { + try (Statement statement = connection.createStatement()) { statement.execute( " CREATE OR REPLACE TABLE test_all_types (" + " string VARCHAR, "