diff --git a/src/test/java/net/snowflake/client/jdbc/ServiceNameTest.java b/src/test/java/net/snowflake/client/jdbc/ServiceNameTest.java index f32af5470..bd51ef533 100644 --- a/src/test/java/net/snowflake/client/jdbc/ServiceNameTest.java +++ b/src/test/java/net/snowflake/client/jdbc/ServiceNameTest.java @@ -127,16 +127,21 @@ public void testAddServiceNameToRequestHeader() throws Throwable { props.setProperty(SFSessionProperty.USER.getPropertyKey(), "fakeuser"); props.setProperty(SFSessionProperty.PASSWORD.getPropertyKey(), "fakepassword"); props.setProperty(SFSessionProperty.INSECURE_MODE.getPropertyKey(), Boolean.TRUE.toString()); - SnowflakeConnectionV1 con = + try (SnowflakeConnectionV1 con = new SnowflakeConnectionV1( - "jdbc:snowflake://http://fakeaccount.snowflakecomputing.com", props); - assertThat(con.getSfSession().getServiceName(), is(INITIAL_SERVICE_NAME)); + "jdbc:snowflake://http://fakeaccount.snowflakecomputing.com", props)) { + assertThat(con.getSfSession().getServiceName(), is(INITIAL_SERVICE_NAME)); - SnowflakeStatementV1 stmt = (SnowflakeStatementV1) con.createStatement(); - stmt.execute("SELECT 1"); - assertThat( - stmt.getConnection().unwrap(SnowflakeConnectionV1.class).getSfSession().getServiceName(), - is(NEW_SERVICE_NAME)); + try (SnowflakeStatementV1 stmt = (SnowflakeStatementV1) con.createStatement()) { + stmt.execute("SELECT 1"); + assertThat( + stmt.getConnection() + .unwrap(SnowflakeConnectionV1.class) + .getSfSession() + .getServiceName(), + is(NEW_SERVICE_NAME)); + } + } } } } diff --git a/src/test/java/net/snowflake/client/jdbc/SnowflakeChunkDownloaderLatestIT.java b/src/test/java/net/snowflake/client/jdbc/SnowflakeChunkDownloaderLatestIT.java index 76c3b0466..1af7e1534 100644 --- a/src/test/java/net/snowflake/client/jdbc/SnowflakeChunkDownloaderLatestIT.java +++ b/src/test/java/net/snowflake/client/jdbc/SnowflakeChunkDownloaderLatestIT.java @@ -37,19 +37,20 @@ public void testChunkDownloaderRetry() throws SQLException, InterruptedException SnowflakeChunkDownloader snowflakeChunkDownloaderSpy = null; - try (Connection connection = getConnection(properties)) { - Statement statement = connection.createStatement(); + try (Connection connection = getConnection(properties); + Statement statement = connection.createStatement()) { // execute a query that will require chunk downloading - ResultSet resultSet = + try (ResultSet resultSet = statement.executeQuery( - "select seq8(), randstr(1000, random()) from table(generator(rowcount => 10000))"); - List resultSetSerializables = - ((SnowflakeResultSet) resultSet).getResultSetSerializables(100 * 1024 * 1024); - SnowflakeResultSetSerializable resultSetSerializable = resultSetSerializables.get(0); - SnowflakeChunkDownloader downloader = - new SnowflakeChunkDownloader((SnowflakeResultSetSerializableV1) resultSetSerializable); - snowflakeChunkDownloaderSpy = Mockito.spy(downloader); - snowflakeChunkDownloaderSpy.getNextChunkToConsume(); + "select seq8(), randstr(1000, random()) from table(generator(rowcount => 10000))")) { + List resultSetSerializables = + ((SnowflakeResultSet) resultSet).getResultSetSerializables(100 * 1024 * 1024); + SnowflakeResultSetSerializable resultSetSerializable = resultSetSerializables.get(0); + SnowflakeChunkDownloader downloader = + new SnowflakeChunkDownloader((SnowflakeResultSetSerializableV1) resultSetSerializable); + snowflakeChunkDownloaderSpy = Mockito.spy(downloader); + snowflakeChunkDownloaderSpy.getNextChunkToConsume(); + } } catch (SnowflakeSQLException exception) { // verify that request was retried twice before reaching max retries Mockito.verify(snowflakeChunkDownloaderSpy, Mockito.times(2)).getResultStreamProvider(); diff --git a/src/test/java/net/snowflake/client/jdbc/SnowflakeDriverIT.java b/src/test/java/net/snowflake/client/jdbc/SnowflakeDriverIT.java index aa82813f0..953bb6348 100644 --- a/src/test/java/net/snowflake/client/jdbc/SnowflakeDriverIT.java +++ b/src/test/java/net/snowflake/client/jdbc/SnowflakeDriverIT.java @@ -117,26 +117,26 @@ public static void setUp() throws Throwable { @AfterClass public static void tearDown() throws SQLException { try (Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - statement.execute("drop table if exists clustered_jdbc"); - statement.execute("drop table if exists orders_jdbc"); - statement.close(); + try (Statement statement = connection.createStatement()) { + statement.execute("drop table if exists clustered_jdbc"); + statement.execute("drop table if exists orders_jdbc"); + } } } public static Connection getConnection(int injectSocketTimeout) throws SQLException { Connection connection = AbstractDriverIT.getConnection(injectSocketTimeout); - Statement statement = connection.createStatement(); - statement.execute( - "alter session set " - + "TIMEZONE='America/Los_Angeles'," - + "TIMESTAMP_TYPE_MAPPING='TIMESTAMP_LTZ'," - + "TIMESTAMP_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'," - + "TIMESTAMP_TZ_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'," - + "TIMESTAMP_LTZ_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'," - + "TIMESTAMP_NTZ_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'"); - statement.close(); + try (Statement statement = connection.createStatement()) { + statement.execute( + "alter session set " + + "TIMEZONE='America/Los_Angeles'," + + "TIMESTAMP_TYPE_MAPPING='TIMESTAMP_LTZ'," + + "TIMESTAMP_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'," + + "TIMESTAMP_TZ_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'," + + "TIMESTAMP_LTZ_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'," + + "TIMESTAMP_NTZ_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'"); + } return connection; } @@ -149,33 +149,38 @@ public static Connection getConnection() throws SQLException { @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testOauthConnection() throws SQLException { Map params = getConnectionParameters(); - Connection con = getConnection("s3testaccount"); - Statement statement = con.createStatement(); - statement.execute("use role accountadmin"); - statement.execute( - "create or replace security integration jdbc_oauth_integration\n" - + " type=oauth\n" - + " oauth_client=CUSTOM\n" - + " oauth_client_type=CONFIDENTIAL\n" - + " oauth_redirect_uri='https://localhost.com/oauth'\n" - + " oauth_issue_refresh_tokens=true\n" - + " enabled=true oauth_refresh_token_validity=86400;"); - String role = params.get("role"); - ResultSet rs = - statement.executeQuery( - "select system$it('create_oauth_access_token', 'JDBC_OAUTH_INTEGRATION', '" - + role - + "')"); - rs.next(); - String token = rs.getString(1); - con.close(); + String role = null; + String token = null; + + try (Connection con = getConnection("s3testaccount"); + Statement statement = con.createStatement()) { + statement.execute("use role accountadmin"); + statement.execute( + "create or replace security integration jdbc_oauth_integration\n" + + " type=oauth\n" + + " oauth_client=CUSTOM\n" + + " oauth_client_type=CONFIDENTIAL\n" + + " oauth_redirect_uri='https://localhost.com/oauth'\n" + + " oauth_issue_refresh_tokens=true\n" + + " enabled=true oauth_refresh_token_validity=86400;"); + role = params.get("role"); + try (ResultSet rs = + statement.executeQuery( + "select system$it('create_oauth_access_token', 'JDBC_OAUTH_INTEGRATION', '" + + role + + "')")) { + rs.next(); + token = rs.getString(1); + } + } Properties props = new Properties(); props.put("authenticator", ClientAuthnDTO.AuthenticatorType.OAUTH.name()); props.put("token", token); props.put("role", role); - con = getConnection("s3testaccount", props); - con.createStatement().execute("select 1"); - con.close(); + try (Connection con = getConnection("s3testaccount", props); + Statement statement = con.createStatement()) { + statement.execute("select 1"); + } } @Ignore @@ -195,16 +200,10 @@ public void testConnections() throws Throwable { futures.add( executorService.submit( () -> { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - ResultSetMetaData resultSetMetaData; - - try { - connection = getConnection(); - statement = connection.createStatement(); - resultSet = statement.executeQuery("SELECT system$sleep(10) % 1"); - resultSetMetaData = resultSet.getMetaData(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT system$sleep(10) % 1")) { + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); // assert column count assertEquals(1, resultSetMetaData.getColumnCount()); @@ -220,10 +219,6 @@ public void testConnections() throws Throwable { } logger.info("Query " + queryIdx + " passed "); - - statement.close(); - } finally { - closeSQLObjects(resultSet, statement, connection); } return true; })); @@ -239,18 +234,11 @@ public void testConnections() throws Throwable { /** Test show columns */ @Test public void testShowColumns() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - Properties paramProperties = new Properties(); - connection = getConnection(paramProperties); - statement = connection.createStatement(); - resultSet = statement.executeQuery("show columns in clustered_jdbc"); + Properties paramProperties = new Properties(); + try (Connection connection = getConnection(paramProperties); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("show columns in clustered_jdbc")) { assertEquals("number of columns", 2, countRows(resultSet)); - } finally { - closeSQLObjects(resultSet, statement, connection); } } @@ -264,51 +252,40 @@ private int countRows(ResultSet rset) throws Throwable { @Test public void testRowsPerResultset() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - try { - connection = getConnection(); + try (Connection connection = getConnection()) { connection.createStatement().execute("alter session set rows_per_resultset=2048"); - statement = connection.createStatement(); - resultSet = statement.executeQuery("SELECT * FROM orders_jdbc"); - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - int numColumns = resultSetMetaData.getColumnCount(); - assertEquals(9, numColumns); - assertEquals("number of columns", 73, countRows(resultSet)); - statement.close(); - } finally { - closeSQLObjects(resultSet, statement, connection); + try (Statement statement = connection.createStatement()) { + try (ResultSet resultSet = statement.executeQuery("SELECT * FROM orders_jdbc")) { + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + int numColumns = resultSetMetaData.getColumnCount(); + assertEquals(9, numColumns); + assertEquals("number of columns", 73, countRows(resultSet)); + } + } } } @Test public void testDDLs() throws Throwable { - Connection connection = null; - Statement statement = null; - try { - connection = getConnection(); - - statement = connection.createStatement(); - - statement.execute("CREATE OR REPLACE TABLE testDDLs(version number, name string)"); - - } finally { - if (statement != null) { + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + statement.execute("CREATE OR REPLACE TABLE testDDLs(version number, name string)"); + } finally { statement.execute("DROP TABLE testDDLs"); } - closeSQLObjects(statement, connection); } } private long getCurrentTransaction(Connection connection) throws SQLException { try (Statement statement = connection.createStatement()) { statement.execute(getCurrenTransactionStmt); - ResultSet rs = statement.getResultSet(); - if (rs.next()) { - String txnId = rs.getString(1); - return txnId != null ? Long.valueOf(txnId) : 0L; + try (ResultSet rs = statement.getResultSet()) { + if (rs.next()) { + String txnId = rs.getString(1); + return txnId != null ? Long.valueOf(txnId) : 0L; + } } } @@ -318,57 +295,51 @@ private long getCurrentTransaction(Connection connection) throws SQLException { /** Tests autocommit */ @Test public void testAutocommit() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - - // 1. test commit - connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - assertEquals(Connection.TRANSACTION_READ_COMMITTED, connection.getTransactionIsolation()); - connection.setAutoCommit(false); // disable autocommit - assertFalse(connection.getAutoCommit()); - - assertEquals(0, getCurrentTransaction(connection)); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + // 1. test commit + connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + assertEquals(Connection.TRANSACTION_READ_COMMITTED, connection.getTransactionIsolation()); + connection.setAutoCommit(false); // disable autocommit + assertFalse(connection.getAutoCommit()); - // create a table, this should not start a transaction - statement.executeUpdate("CREATE OR REPLACE TABLE AUTOCOMMIT_API_TEST (i int)"); - assertEquals(0, getCurrentTransaction(connection)); + assertEquals(0, getCurrentTransaction(connection)); - // insert into it this should start a transaction. - statement.executeUpdate("INSERT INTO AUTOCOMMIT_API_TEST VALUES (1)"); - assertNotEquals(0, getCurrentTransaction(connection)); + // create a table, this should not start a transaction + statement.executeUpdate("CREATE OR REPLACE TABLE AUTOCOMMIT_API_TEST (i int)"); + assertEquals(0, getCurrentTransaction(connection)); - // commit it using the api - connection.commit(); - assertFalse(connection.getAutoCommit()); - assertEquals(0, getCurrentTransaction(connection)); - resultSet = statement.executeQuery("SELECT COUNT(*) FROM AUTOCOMMIT_API_TEST WHERE i = 1"); - assertTrue(resultSet.next()); - assertEquals(1, resultSet.getInt(1)); - resultSet.close(); - - // 2. test rollback == - // delete from the table, should start a transaction. - statement.executeUpdate("DELETE FROM AUTOCOMMIT_API_TEST"); - assertNotEquals(0, getCurrentTransaction(connection)); - - // roll it back using the api - connection.rollback(); - assertFalse(connection.getAutoCommit()); - assertEquals(0, getCurrentTransaction(connection)); - resultSet = statement.executeQuery("SELECT COUNT(*) FROM AUTOCOMMIT_API_TEST WHERE i = 1"); - assertTrue(resultSet.next()); - assertEquals(1, resultSet.getInt(1)); - } finally { - if (statement != null) { + // insert into it this should start a transaction. + statement.executeUpdate("INSERT INTO AUTOCOMMIT_API_TEST VALUES (1)"); + assertNotEquals(0, getCurrentTransaction(connection)); + + // commit it using the api + connection.commit(); + assertFalse(connection.getAutoCommit()); + assertEquals(0, getCurrentTransaction(connection)); + try (ResultSet resultSet = + statement.executeQuery("SELECT COUNT(*) FROM AUTOCOMMIT_API_TEST WHERE i = 1")) { + assertTrue(resultSet.next()); + assertEquals(1, resultSet.getInt(1)); + } + // 2. test rollback == + // delete from the table, should start a transaction. + statement.executeUpdate("DELETE FROM AUTOCOMMIT_API_TEST"); + assertNotEquals(0, getCurrentTransaction(connection)); + + // roll it back using the api + connection.rollback(); + assertFalse(connection.getAutoCommit()); + assertEquals(0, getCurrentTransaction(connection)); + try (ResultSet resultSet = + statement.executeQuery("SELECT COUNT(*) FROM AUTOCOMMIT_API_TEST WHERE i = 1")) { + assertTrue(resultSet.next()); + assertEquals(1, resultSet.getInt(1)); + } + } finally { statement.execute("DROP TABLE AUTOCOMMIT_API_TEST"); } - closeSQLObjects(resultSet, statement, connection); } } @@ -405,396 +376,367 @@ private void assertConstraintResults( @Test public void testBoolean() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - statement = connection.createStatement(); - statement.execute("alter SESSION set CLIENT_METADATA_REQUEST_USE_CONNECTION_CTX=true"); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + statement.execute("alter SESSION set CLIENT_METADATA_REQUEST_USE_CONNECTION_CTX=true"); - DatabaseMetaData metadata = connection.getMetaData(); + DatabaseMetaData metadata = connection.getMetaData(); - // Create a table with boolean columns - statement.execute("create or replace table testBooleanT1(c1 boolean)"); + // Create a table with boolean columns + statement.execute("create or replace table testBooleanT1(c1 boolean)"); - // Insert values into the table - statement.execute("insert into testBooleanT1 values(true), (false), (null)"); + // Insert values into the table + statement.execute("insert into testBooleanT1 values(true), (false), (null)"); - // Get values from the table - PreparedStatement preparedStatement = - connection.prepareStatement("select c1 from testBooleanT1"); + // Get values from the table + try (PreparedStatement preparedStatement = + connection.prepareStatement("select c1 from testBooleanT1")) { - // I. Test ResultSetMetaData interface - resultSet = preparedStatement.executeQuery(); + // I. Test ResultSetMetaData interface + ResultSet resultSet = preparedStatement.executeQuery(); - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - // Verify the column type is Boolean - assertEquals(Types.BOOLEAN, resultSetMetaData.getColumnType(1)); + // Verify the column type is Boolean + assertEquals(Types.BOOLEAN, resultSetMetaData.getColumnType(1)); - // II. Test DatabaseMetadata interface - ResultSet columnMetaDataResultSet = - metadata.getColumns( - null, // catalog - null, // schema - "TESTBOOLEANT1", // table - null // column - ); + // II. Test DatabaseMetadata interface + ResultSet columnMetaDataResultSet = + metadata.getColumns( + null, // catalog + null, // schema + "TESTBOOLEANT1", // table + null // column + ); - resultSetMetaData = columnMetaDataResultSet.getMetaData(); + resultSetMetaData = columnMetaDataResultSet.getMetaData(); - // assert column count - assertEquals(24, resultSetMetaData.getColumnCount()); + // assert column count + assertEquals(24, resultSetMetaData.getColumnCount()); - assertTrue(columnMetaDataResultSet.next()); - assertEquals(Types.BOOLEAN, columnMetaDataResultSet.getInt(5)); - } finally // cleanup - { - // drop the table - if (statement != null) { + assertTrue(columnMetaDataResultSet.next()); + assertEquals(Types.BOOLEAN, columnMetaDataResultSet.getInt(5)); + } + } finally { statement.execute("drop table testBooleanT1"); } - closeSQLObjects(resultSet, statement, connection); } } @Test public void testConstraints() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - statement.execute("alter SESSION set CLIENT_METADATA_REQUEST_USE_CONNECTION_CTX=true"); - - DatabaseMetaData metadata = connection.getMetaData(); - - // Create primary key tables - statement.execute( - "CREATE OR REPLACE TABLE testConstraintsP1(c1 number unique, c2 " - + "number, constraint cons0 primary key (c1, c2))"); - - statement.execute( - "CREATE OR REPLACE TABLE testConstraintsP2(c1 number " - + "constraint cons1 primary key, c2 number)"); + ResultSet manualResultSet = null; - // Create foreign key tables - statement.execute( - "CREATE OR REPLACE TABLE testConstraintsF1(c1 number, c2 number, " - + "constraint cons3 foreign key (c1, c2) references " - + "testConstraintsP1(c1, c2))"); - - statement.execute( - "CREATE OR REPLACE TABLE testConstraintsF2(c1 number, c2 number, " - + "constraint cons4 foreign key (c1, c2) references " - + "testConstraintsP1(c1, c2), constraint cons5 " - + "foreign key (c2) references testConstraintsP2(c1))"); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + statement.execute("alter SESSION set CLIENT_METADATA_REQUEST_USE_CONNECTION_CTX=true"); - // show primary keys - resultSet = metadata.getPrimaryKeys(null, null, "TESTCONSTRAINTSP1"); + DatabaseMetaData metadata = connection.getMetaData(); - // primary key for testConstraintsP1 should contain two rows - assertConstraintResults(resultSet, 2, 6, "testConstraintsP1", null); + // Create primary key tables + statement.execute( + "CREATE OR REPLACE TABLE testConstraintsP1(c1 number unique, c2 " + + "number, constraint cons0 primary key (c1, c2))"); - resultSet = metadata.getPrimaryKeys(null, null, "TESTCONSTRAINTSP2"); + statement.execute( + "CREATE OR REPLACE TABLE testConstraintsP2(c1 number " + + "constraint cons1 primary key, c2 number)"); - // primary key for testConstraintsP2 contains 1 row - assertConstraintResults(resultSet, 1, 6, "testConstraintsP2", null); - resultSet.close(); - resultSet.next(); + // Create foreign key tables + statement.execute( + "CREATE OR REPLACE TABLE testConstraintsF1(c1 number, c2 number, " + + "constraint cons3 foreign key (c1, c2) references " + + "testConstraintsP1(c1, c2))"); - // Show imported keys - resultSet = metadata.getImportedKeys(null, null, "TESTCONSTRAINTSF1"); + statement.execute( + "CREATE OR REPLACE TABLE testConstraintsF2(c1 number, c2 number, " + + "constraint cons4 foreign key (c1, c2) references " + + "testConstraintsP1(c1, c2), constraint cons5 " + + "foreign key (c2) references testConstraintsP2(c1))"); - assertConstraintResults(resultSet, 2, 14, null, "testConstraintsF1"); + // show primary keys + try (ResultSet resultSet = metadata.getPrimaryKeys(null, null, "TESTCONSTRAINTSP1")) { - resultSet = metadata.getImportedKeys(null, null, "TESTCONSTRAINTSF2"); + // primary key for testConstraintsP1 should contain two rows + assertConstraintResults(resultSet, 2, 6, "testConstraintsP1", null); + } - assertConstraintResults(resultSet, 3, 14, null, "testConstraintsF2"); - resultSet.close(); - resultSet.next(); + ResultSet resultSet1 = metadata.getPrimaryKeys(null, null, "TESTCONSTRAINTSP2"); - // show exported keys - resultSet = metadata.getExportedKeys(null, null, "TESTCONSTRAINTSP1"); + // primary key for testConstraintsP2 contains 1 row + assertConstraintResults(resultSet1, 1, 6, "testConstraintsP2", null); + resultSet1.close(); + resultSet1.next(); - assertConstraintResults(resultSet, 4, 14, "testConstraintsP1", null); + // Show imported keys + try (ResultSet resultSet = metadata.getImportedKeys(null, null, "TESTCONSTRAINTSF1")) { + assertConstraintResults(resultSet, 2, 14, null, "testConstraintsF1"); + } - resultSet = metadata.getExportedKeys(null, null, "TESTCONSTRAINTSP2"); + manualResultSet = metadata.getImportedKeys(null, null, "TESTCONSTRAINTSF2"); - assertConstraintResults(resultSet, 1, 14, "testConstraintsP2", null); - resultSet.close(); - resultSet.next(); + assertConstraintResults(manualResultSet, 3, 14, null, "testConstraintsF2"); + manualResultSet.close(); + manualResultSet.next(); - // show cross references - resultSet = - metadata.getCrossReference( - null, null, "TESTCONSTRAINTSP1", null, null, "TESTCONSTRAINTSF1"); + // show exported keys + try (ResultSet resultSet = metadata.getExportedKeys(null, null, "TESTCONSTRAINTSP1")) { + assertConstraintResults(resultSet, 4, 14, "testConstraintsP1", null); + } - assertConstraintResults(resultSet, 2, 14, "testConstraintsP1", "testConstraintsF1"); + manualResultSet = metadata.getExportedKeys(null, null, "TESTCONSTRAINTSP2"); - resultSet = - metadata.getCrossReference( - null, null, "TESTCONSTRAINTSP2", null, null, "TESTCONSTRAINTSF2"); + assertConstraintResults(manualResultSet, 1, 14, "testConstraintsP2", null); + manualResultSet.close(); + manualResultSet.next(); - assertConstraintResults(resultSet, 1, 14, "testConstraintsP2", "testConstraintsF2"); + // show cross references + try (ResultSet resultSet = + metadata.getCrossReference( + null, null, "TESTCONSTRAINTSP1", null, null, "TESTCONSTRAINTSF1")) { + assertConstraintResults(resultSet, 2, 14, "testConstraintsP1", "testConstraintsF1"); + } - resultSet = - metadata.getCrossReference( - null, null, "TESTCONSTRAINTSP1", null, null, "TESTCONSTRAINTSF2"); + try (ResultSet resultSet = + metadata.getCrossReference( + null, null, "TESTCONSTRAINTSP2", null, null, "TESTCONSTRAINTSF2")) { + assertConstraintResults(resultSet, 1, 14, "testConstraintsP2", "testConstraintsF2"); + } - assertConstraintResults(resultSet, 2, 14, "testConstraintsP1", "testConstraintsF2"); + try (ResultSet resultSet = + metadata.getCrossReference( + null, null, "TESTCONSTRAINTSP1", null, null, "TESTCONSTRAINTSF2")) { + assertConstraintResults(resultSet, 2, 14, "testConstraintsP1", "testConstraintsF2"); + } - resultSet = - metadata.getCrossReference( - null, null, "TESTCONSTRAINTSP2", null, null, "TESTCONSTRAINTSF1"); + manualResultSet = + metadata.getCrossReference( + null, null, "TESTCONSTRAINTSP2", null, null, "TESTCONSTRAINTSF1"); - assertFalse( - "cross reference from testConstraintsP2 to " + "testConstraintsF2 should be empty", - resultSet.next()); - resultSet.close(); - resultSet.next(); - } finally { - if (statement != null) { + assertFalse( + "cross reference from testConstraintsP2 to " + "testConstraintsF2 should be empty", + manualResultSet.next()); + manualResultSet.close(); + manualResultSet.next(); + } finally { statement.execute("DROP TABLE TESTCONSTRAINTSF1"); statement.execute("DROP TABLE TESTCONSTRAINTSF2"); statement.execute("DROP TABLE TESTCONSTRAINTSP1"); statement.execute("DROP TABLE TESTCONSTRAINTSP2"); } - closeSQLObjects(resultSet, statement, connection); } } @Test public void testQueryWithMaxRows() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; final int maxRows = 30; - - try { - connection = getConnection(); - statement = connection.createStatement(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { statement.setMaxRows(maxRows); - resultSet = statement.executeQuery("SELECT * FROM orders_jdbc"); + try (ResultSet resultSet = statement.executeQuery("SELECT * FROM orders_jdbc")) { - // assert column count - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - assertEquals(9, resultSetMetaData.getColumnCount()); - assertEquals(maxRows, countRows(resultSet)); - } finally { - closeSQLObjects(resultSet, statement, connection); + // assert column count + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + assertEquals(9, resultSetMetaData.getColumnCount()); + assertEquals(maxRows, countRows(resultSet)); + } } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testCancelQueryBySystemFunction() throws Throwable { - Statement statement = null; - ResultSet resultSet = null; - - final Connection connection = getConnection(); + try (Connection connection = getConnection()) { - try { // Get the current session identifier - Statement getSessionIdStmt = connection.createStatement(); - getSessionIdStmt.setMaxRows(30); - resultSet = getSessionIdStmt.executeQuery("SELECT current_session()"); - assertTrue(resultSet.next()); - final long sessionId = resultSet.getLong(1); - Timer timer = new Timer(); - timer.schedule( - new TimerTask() { - @Override - public void run() { - try { - PreparedStatement cancelAll; - cancelAll = connection.prepareStatement("call system$cancel_all_queries(?)"); - - // bind integer - cancelAll.setLong(1, sessionId); - cancelAll.executeQuery(); - } catch (SQLException ex) { - logger.log(Level.SEVERE, "Cancel failed with exception {}", ex); - } - } - }, - 5000); - - // execute a query for 120s - statement = connection.createStatement(); - statement.setMaxRows(30); - - resultSet = statement.executeQuery("SELECT count(*) FROM TABLE(generator(timeLimit => 120))"); - - fail("should raise an exception"); - } catch (SQLException ex) { - // assert the sqlstate is what we expect (QUERY CANCELLED) - assertEquals("sqlstate mismatch", SqlState.QUERY_CANCELED, ex.getSQLState()); - } finally { - closeSQLObjects(resultSet, statement, connection); + try (Statement getSessionIdStmt = connection.createStatement()) { + getSessionIdStmt.setMaxRows(30); + try (ResultSet resultSet = getSessionIdStmt.executeQuery("SELECT current_session()")) { + assertTrue(resultSet.next()); + final long sessionId = resultSet.getLong(1); + Timer timer = new Timer(); + timer.schedule( + new TimerTask() { + @Override + public void run() { + try { + PreparedStatement cancelAll; + cancelAll = connection.prepareStatement("call system$cancel_all_queries(?)"); + + // bind integer + cancelAll.setLong(1, sessionId); + cancelAll.executeQuery(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, "Cancel failed with exception {}", ex); + } + } + }, + 5000); + } + // execute a query for 120s + try (Statement statement = connection.createStatement()) { + statement.setMaxRows(30); + ResultSet resultSet = + statement.executeQuery("SELECT count(*) FROM TABLE(generator(timeLimit => 120))"); + } + fail("should raise an exception"); + } catch (SQLException ex) { + // assert the sqlstate is what we expect (QUERY CANCELLED) + assertEquals("sqlstate mismatch", SqlState.QUERY_CANCELED, ex.getSQLState()); + } } } @Test public void testDBMetadata() throws Throwable { - Connection connection = null; - Statement statement = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - statement.execute("alter SESSION set CLIENT_METADATA_REQUEST_USE_CONNECTION_CTX=true"); - + int cnt = 0; + try (Connection connection = getConnection()) { + try (Statement statement = connection.createStatement()) { + statement.execute("alter SESSION set CLIENT_METADATA_REQUEST_USE_CONNECTION_CTX=true"); + } // get database metadata DatabaseMetaData metaData = connection.getMetaData(); // the following will issue - ResultSet databaseSet = metaData.getCatalogs(); - assertTrue("databases shouldn't be empty", databaseSet.next()); - - // "show schemas in [databaseName]" - ResultSet schemaSet = metaData.getSchemas(connection.getCatalog(), connection.getSchema()); - assertTrue("schemas shouldn't be empty", schemaSet.next()); - assertTrue( - "database should be " + connection.getCatalog(), - connection.getCatalog().equalsIgnoreCase(schemaSet.getString(2))); - assertTrue( - "schema should be " + connection.getSchema(), - connection.getSchema().equalsIgnoreCase(schemaSet.getString(1))); - - // snow tables in a schema - ResultSet tableSet = - metaData.getTables( - connection.getCatalog(), connection.getSchema(), ORDERS_JDBC, null); // types - assertTrue( - String.format( - "table %s should exists in db: %s, schema: %s", - ORDERS_JDBC, connection.getCatalog(), connection.getSchema()), - tableSet.next()); - assertTrue( - "database should be " + connection.getCatalog(), - connection.getCatalog().equalsIgnoreCase(schemaSet.getString(2))); - assertTrue( - "schema should be " + connection.getSchema(), - connection.getSchema().equalsIgnoreCase(schemaSet.getString(1))); - assertTrue( - "table should be orders_jdbc", ORDERS_JDBC.equalsIgnoreCase(tableSet.getString(3))); - - ResultSet tableMetaDataResultSet = + try (ResultSet databaseSet = metaData.getCatalogs()) { + assertTrue("databases shouldn't be empty", databaseSet.next()); + + // "show schemas in [databaseName]" + ResultSet schemaSet = metaData.getSchemas(connection.getCatalog(), connection.getSchema()); + assertTrue("schemas shouldn't be empty", schemaSet.next()); + assertTrue( + "database should be " + connection.getCatalog(), + connection.getCatalog().equalsIgnoreCase(schemaSet.getString(2))); + assertTrue( + "schema should be " + connection.getSchema(), + connection.getSchema().equalsIgnoreCase(schemaSet.getString(1))); + // snow tables in a schema + try (ResultSet tableSet = + metaData.getTables( + connection.getCatalog(), connection.getSchema(), ORDERS_JDBC, null)) { // types + assertTrue( + String.format( + "table %s should exists in db: %s, schema: %s", + ORDERS_JDBC, connection.getCatalog(), connection.getSchema()), + tableSet.next()); + assertTrue( + "database should be " + connection.getCatalog(), + connection.getCatalog().equalsIgnoreCase(schemaSet.getString(2))); + assertTrue( + "schema should be " + connection.getSchema(), + connection.getSchema().equalsIgnoreCase(schemaSet.getString(1))); + assertTrue( + "table should be orders_jdbc", ORDERS_JDBC.equalsIgnoreCase(tableSet.getString(3))); + } + } + + try (ResultSet tableMetaDataResultSet = metaData.getTables( null, // catalog null, // schema ORDERS_JDBC, // table - null); // types + null)) { // types - ResultSetMetaData resultSetMetaData = tableMetaDataResultSet.getMetaData(); + ResultSetMetaData resultSetMetaData = tableMetaDataResultSet.getMetaData(); - assertEquals(10, resultSetMetaData.getColumnCount()); + assertEquals(10, resultSetMetaData.getColumnCount()); - // assert we get 1 rows - int cnt = 0; - while (tableMetaDataResultSet.next()) { - assertTrue(ORDERS_JDBC.equalsIgnoreCase(tableMetaDataResultSet.getString(3))); - ++cnt; + // assert we get 1 rows + cnt = 0; + while (tableMetaDataResultSet.next()) { + assertTrue(ORDERS_JDBC.equalsIgnoreCase(tableMetaDataResultSet.getString(3))); + ++cnt; + } + assertEquals("number of tables", 1, cnt); } - assertEquals("number of tables", 1, cnt); - - tableMetaDataResultSet.close(); - // test pattern - tableMetaDataResultSet = + try (ResultSet tableMetaDataResultSet = metaData.getTables( null, // catalog null, // schema "%", // table - null); // types + null)) { // types - resultSetMetaData = tableMetaDataResultSet.getMetaData(); + ResultSetMetaData resultSetMetaData = tableMetaDataResultSet.getMetaData(); - // assert column count - assertEquals(10, resultSetMetaData.getColumnCount()); - - // assert we get orders_jdbc - boolean found = false; - while (tableMetaDataResultSet.next()) { - // assert the table name - if (ORDERS_JDBC.equalsIgnoreCase(tableMetaDataResultSet.getString(3))) { - found = true; - break; + // assert column count + assertEquals(10, resultSetMetaData.getColumnCount()); + + // assert we get orders_jdbc + boolean found = false; + while (tableMetaDataResultSet.next()) { + // assert the table name + if (ORDERS_JDBC.equalsIgnoreCase(tableMetaDataResultSet.getString(3))) { + found = true; + break; + } } + assertTrue("orders_jdbc not found", found); } - assertTrue("orders_jdbc not found", found); - - tableMetaDataResultSet.close(); // get column metadata - ResultSet columnMetaDataResultSet = metaData.getColumns(null, null, ORDERS_JDBC, null); + try (ResultSet columnMetaDataResultSet = metaData.getColumns(null, null, ORDERS_JDBC, null)) { - resultSetMetaData = columnMetaDataResultSet.getMetaData(); + ResultSetMetaData resultSetMetaData = columnMetaDataResultSet.getMetaData(); - // assert column count - assertEquals(24, resultSetMetaData.getColumnCount()); + // assert column count + assertEquals(24, resultSetMetaData.getColumnCount()); - // assert we get 9 rows - cnt = 0; - while (columnMetaDataResultSet.next()) { - // SNOW-16881: assert database name - assertTrue(connection.getCatalog().equalsIgnoreCase(columnMetaDataResultSet.getString(1))); + // assert we get 9 rows + cnt = 0; + while (columnMetaDataResultSet.next()) { + // SNOW-16881: assert database name + assertTrue( + connection.getCatalog().equalsIgnoreCase(columnMetaDataResultSet.getString(1))); - // assert the table name and column name, data type and type name - assertTrue(ORDERS_JDBC.equalsIgnoreCase(columnMetaDataResultSet.getString(3))); + // assert the table name and column name, data type and type name + assertTrue(ORDERS_JDBC.equalsIgnoreCase(columnMetaDataResultSet.getString(3))); - assertTrue(columnMetaDataResultSet.getString(4).startsWith("C")); + assertTrue(columnMetaDataResultSet.getString(4).startsWith("C")); - assertEquals(Types.VARCHAR, columnMetaDataResultSet.getInt(5)); + assertEquals(Types.VARCHAR, columnMetaDataResultSet.getInt(5)); - assertTrue("VARCHAR".equalsIgnoreCase(columnMetaDataResultSet.getString(6))); + assertTrue("VARCHAR".equalsIgnoreCase(columnMetaDataResultSet.getString(6))); - if (cnt == 0) { - // assert comment - assertEquals("JDBC", columnMetaDataResultSet.getString(12)); + if (cnt == 0) { + // assert comment + assertEquals("JDBC", columnMetaDataResultSet.getString(12)); - // assert nullable - assertEquals(DatabaseMetaData.columnNoNulls, columnMetaDataResultSet.getInt(11)); + // assert nullable + assertEquals(DatabaseMetaData.columnNoNulls, columnMetaDataResultSet.getInt(11)); - // assert is_nullable - assertEquals("NO", columnMetaDataResultSet.getString(18)); + // assert is_nullable + assertEquals("NO", columnMetaDataResultSet.getString(18)); + } + ++cnt; } - ++cnt; + assertEquals(9, cnt); } - assertEquals(9, cnt); - - columnMetaDataResultSet.close(); // create a table with mix cases - statement = connection.createStatement(); - statement.execute("create or replace table \"testDBMetadata\" (a timestamp_ltz)"); - columnMetaDataResultSet = metaData.getColumns(null, null, "testDBMetadata", null); + try (Statement statement = connection.createStatement()) { + statement.execute("create or replace table \"testDBMetadata\" (a timestamp_ltz)"); + try (ResultSet columnMetaDataResultSet = + metaData.getColumns(null, null, "testDBMetadata", null)) { - // assert we get 1 row - cnt = 0; - while (columnMetaDataResultSet.next()) { - // assert the table name and column name, data type and type name - assertTrue("testDBMetadata".equalsIgnoreCase(columnMetaDataResultSet.getString(3))); + // assert we get 1 row + cnt = 0; + while (columnMetaDataResultSet.next()) { + // assert the table name and column name, data type and type name + assertTrue("testDBMetadata".equalsIgnoreCase(columnMetaDataResultSet.getString(3))); - assertEquals(Types.TIMESTAMP, columnMetaDataResultSet.getInt(5)); + assertEquals(Types.TIMESTAMP, columnMetaDataResultSet.getInt(5)); - assertTrue(columnMetaDataResultSet.getString(4).equalsIgnoreCase("a")); - cnt++; - } - assertEquals(1, cnt); - } finally { - if (statement != null) { - statement.execute("DROP TABLE IF EXISTS \"testDBMetadata\""); + assertTrue(columnMetaDataResultSet.getString(4).equalsIgnoreCase("a")); + cnt++; + } + assertEquals(1, cnt); + } } - closeSQLObjects(statement, connection); + connection.createStatement().execute("DROP TABLE IF EXISTS \"testDBMetadata\""); } } @@ -804,57 +746,53 @@ public void testPutWithWildcardGCP() throws Throwable { Properties _connectionProperties = new Properties(); _connectionProperties.put("inject_wait_in_put", 5); _connectionProperties.put("ssl", "off"); - Connection connection = - getConnection( - DONT_INJECT_SOCKET_TIMEOUT, _connectionProperties, false, false, "gcpaccount"); - Statement statement = connection.createStatement(); - - String sourceFilePath = getFullPathFileInResource(TEST_DATA_FILE); - // replace file name with wildcard character - sourceFilePath = sourceFilePath.replace("orders_100.csv", "orders_10*.csv"); - - File destFolder = tmpFolder.newFolder(); - String destFolderCanonicalPath = destFolder.getCanonicalPath(); - String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; + try (Connection connection = + getConnection( + DONT_INJECT_SOCKET_TIMEOUT, _connectionProperties, false, false, "gcpaccount"); + Statement statement = connection.createStatement()) { + try { + String sourceFilePath = getFullPathFileInResource(TEST_DATA_FILE); + // replace file name with wildcard character + sourceFilePath = sourceFilePath.replace("orders_100.csv", "orders_10*.csv"); - try { - statement.execute("alter session set ENABLE_GCP_PUT_EXCEPTION_FOR_OLD_DRIVERS=false"); - statement.execute("CREATE OR REPLACE STAGE wildcard_stage"); - assertTrue( - "Failed to put a file", - statement.execute("PUT file://" + sourceFilePath + " @wildcard_stage")); + File destFolder = tmpFolder.newFolder(); + String destFolderCanonicalPath = destFolder.getCanonicalPath(); + String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; + statement.execute("alter session set ENABLE_GCP_PUT_EXCEPTION_FOR_OLD_DRIVERS=false"); + statement.execute("CREATE OR REPLACE STAGE wildcard_stage"); + assertTrue( + "Failed to put a file", + statement.execute("PUT file://" + sourceFilePath + " @wildcard_stage")); - findFile(statement, "ls @wildcard_stage/"); + findFile(statement, "ls @wildcard_stage/"); - assertTrue( - "Failed to get files", - statement.execute( - "GET @wildcard_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); + assertTrue( + "Failed to get files", + statement.execute( + "GET @wildcard_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); - File downloaded; - // download the files we just uploaded to stage - for (int i = 0; i < fileNames.length; i++) { - // Make sure that the downloaded file exists, it should be gzip compressed - downloaded = new File(destFolderCanonicalPathWithSeparator + fileNames[i] + ".gz"); - assert (downloaded.exists()); + File downloaded; + // download the files we just uploaded to stage + for (int i = 0; i < fileNames.length; i++) { + // Make sure that the downloaded file exists, it should be gzip compressed + downloaded = new File(destFolderCanonicalPathWithSeparator + fileNames[i] + ".gz"); + assert (downloaded.exists()); - Process p = - Runtime.getRuntime() - .exec("gzip -d " + destFolderCanonicalPathWithSeparator + fileNames[i] + ".gz"); - p.waitFor(); + Process p = + Runtime.getRuntime() + .exec("gzip -d " + destFolderCanonicalPathWithSeparator + fileNames[i] + ".gz"); + p.waitFor(); - String individualFilePath = sourceFilePath.replace("orders_10*.csv", fileNames[i]); + String individualFilePath = sourceFilePath.replace("orders_10*.csv", fileNames[i]); - File original = new File(individualFilePath); - File unzipped = new File(destFolderCanonicalPathWithSeparator + fileNames[i]); - assert (original.length() == unzipped.length()); - assert (FileUtils.contentEquals(original, unzipped)); + File original = new File(individualFilePath); + File unzipped = new File(destFolderCanonicalPathWithSeparator + fileNames[i]); + assert (original.length() == unzipped.length()); + assert (FileUtils.contentEquals(original, unzipped)); + } + } finally { + statement.execute("DROP STAGE IF EXISTS wildcard_stage"); } - - } finally { - statement.execute("DROP STAGE IF EXISTS wildcard_stage"); - statement.close(); - connection.close(); } } @@ -868,110 +806,104 @@ public void testPutWithWildcardGCP() throws Throwable { private void copyContentFrom(File file1, File file2) throws Exception { FileInputStream inputStream = new FileInputStream(file1); FileOutputStream outputStream = new FileOutputStream(file2); - FileChannel fIn = inputStream.getChannel(); - FileChannel fOut = outputStream.getChannel(); - fOut.transferFrom(fIn, 0, fIn.size()); - fIn.position(0); - fOut.transferFrom(fIn, fIn.size(), fIn.size()); - fOut.close(); - fIn.close(); + try (FileChannel fIn = inputStream.getChannel(); + FileChannel fOut = outputStream.getChannel()) { + fOut.transferFrom(fIn, 0, fIn.size()); + fIn.position(0); + fOut.transferFrom(fIn, fIn.size(), fIn.size()); + } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPutGetLargeFileGCP() throws Throwable { - Connection connection = getConnection("gcpaccount"); - Statement statement = connection.createStatement(); + try (Connection connection = getConnection("gcpaccount"); + Statement statement = connection.createStatement()) { + try { + File destFolder = tmpFolder.newFolder(); + String destFolderCanonicalPath = destFolder.getCanonicalPath(); + String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; - File destFolder = tmpFolder.newFolder(); - String destFolderCanonicalPath = destFolder.getCanonicalPath(); - String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; + File largeTempFile = tmpFolder.newFile("largeFile.csv"); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(largeTempFile))) { + bw.write("Creating large test file for GCP PUT/GET test"); + bw.write(System.lineSeparator()); + bw.write("Creating large test file for GCP PUT/GET test"); + bw.write(System.lineSeparator()); + } + File largeTempFile2 = tmpFolder.newFile("largeFile2.csv"); - File largeTempFile = tmpFolder.newFile("largeFile.csv"); - BufferedWriter bw = new BufferedWriter(new FileWriter(largeTempFile)); - bw.write("Creating large test file for GCP PUT/GET test"); - bw.write(System.lineSeparator()); - bw.write("Creating large test file for GCP PUT/GET test"); - bw.write(System.lineSeparator()); - bw.close(); - File largeTempFile2 = tmpFolder.newFile("largeFile2.csv"); - - String sourceFilePath = largeTempFile.getCanonicalPath(); - - try { - // copy info from 1 file to another and continue doubling file size until we reach ~1.5GB, - // which is a large file - for (int i = 0; i < 12; i++) { - copyContentFrom(largeTempFile, largeTempFile2); - copyContentFrom(largeTempFile2, largeTempFile); - } + String sourceFilePath = largeTempFile.getCanonicalPath(); - statement.execute("alter session set ENABLE_GCP_PUT_EXCEPTION_FOR_OLD_DRIVERS=false"); + // copy info from 1 file to another and continue doubling file size until we reach ~1.5GB, + // which is a large file + for (int i = 0; i < 12; i++) { + copyContentFrom(largeTempFile, largeTempFile2); + copyContentFrom(largeTempFile2, largeTempFile); + } - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE largefile_stage"); - assertTrue( - "Failed to put a file", - statement.execute("PUT file://" + sourceFilePath + " @largefile_stage")); + statement.execute("alter session set ENABLE_GCP_PUT_EXCEPTION_FOR_OLD_DRIVERS=false"); - // check that file exists in stage after PUT - findFile(statement, "ls @largefile_stage/"); + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE largefile_stage"); + assertTrue( + "Failed to put a file", + statement.execute("PUT file://" + sourceFilePath + " @largefile_stage")); - // create a new table with columns matching CSV file - statement.execute("create or replace table large_table (colA string)"); - // copy rows from file into table - statement.execute("copy into large_table from @largefile_stage/largeFile.csv.gz"); - // copy back from table into different stage - statement.execute("create or replace stage extra_stage"); - statement.execute("copy into @extra_stage/bigFile.csv.gz from large_table single=true"); + // check that file exists in stage after PUT + findFile(statement, "ls @largefile_stage/"); - // get file from new stage - assertTrue( - "Failed to get files", - statement.execute( - "GET @extra_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); - - // Make sure that the downloaded file exists; it should be gzip compressed - File downloaded = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); - assert (downloaded.exists()); - - // unzip the file - Process p = - Runtime.getRuntime() - .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); - p.waitFor(); - - // compare the original file with the file that's been uploaded, copied into a table, copied - // back into a stage, - // downloaded, and unzipped - File unzipped = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv"); - assert (largeTempFile.length() == unzipped.length()); - assert (FileUtils.contentEquals(largeTempFile, unzipped)); - } finally { - statement.execute("DROP STAGE IF EXISTS largefile_stage"); - statement.execute("DROP STAGE IF EXISTS extra_stage"); - statement.execute("DROP TABLE IF EXISTS large_table"); - statement.close(); - connection.close(); + // create a new table with columns matching CSV file + statement.execute("create or replace table large_table (colA string)"); + // copy rows from file into table + statement.execute("copy into large_table from @largefile_stage/largeFile.csv.gz"); + // copy back from table into different stage + statement.execute("create or replace stage extra_stage"); + statement.execute("copy into @extra_stage/bigFile.csv.gz from large_table single=true"); + + // get file from new stage + assertTrue( + "Failed to get files", + statement.execute( + "GET @extra_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); + + // Make sure that the downloaded file exists; it should be gzip compressed + File downloaded = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); + assert (downloaded.exists()); + + // unzip the file + Process p = + Runtime.getRuntime() + .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); + p.waitFor(); + + // compare the original file with the file that's been uploaded, copied into a table, copied + // back into a stage, + // downloaded, and unzipped + File unzipped = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv"); + assert (largeTempFile.length() == unzipped.length()); + assert (FileUtils.contentEquals(largeTempFile, unzipped)); + } finally { + statement.execute("DROP STAGE IF EXISTS largefile_stage"); + statement.execute("DROP STAGE IF EXISTS extra_stage"); + statement.execute("DROP TABLE IF EXISTS large_table"); + } } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPutOverwrite() throws Throwable { - Connection connection = null; - Statement statement = null; - // create 2 files: an original, and one that will overwrite the original File file1 = tmpFolder.newFile("testfile.csv"); - BufferedWriter bw = new BufferedWriter(new FileWriter(file1)); - bw.write("Writing original file content. This should get overwritten."); - bw.close(); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(file1))) { + bw.write("Writing original file content. This should get overwritten."); + } File file2 = tmpFolder2.newFile("testfile.csv"); - bw = new BufferedWriter(new FileWriter(file2)); - bw.write("This is all new! This should be the result of the overwriting."); - bw.close(); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(file2))) { + bw.write("This is all new! This should be the result of the overwriting."); + } String sourceFilePathOriginal = file1.getCanonicalPath(); String sourceFilePathOverwrite = file2.getCanonicalPath(); @@ -982,51 +914,49 @@ public void testPutOverwrite() throws Throwable { List accounts = Arrays.asList(null, "s3testaccount", "azureaccount", "gcpaccount"); for (int i = 0; i < accounts.size(); i++) { - try { - connection = getConnection(accounts.get(i)); - - statement = connection.createStatement(); - - statement.execute("alter session set ENABLE_GCP_PUT_EXCEPTION_FOR_OLD_DRIVERS=false"); + try (Connection connection = getConnection(accounts.get(i)); + Statement statement = connection.createStatement()) { + try { + statement.execute("alter session set ENABLE_GCP_PUT_EXCEPTION_FOR_OLD_DRIVERS=false"); - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE testing_stage"); - assertTrue( - "Failed to put a file", - statement.execute("PUT file://" + sourceFilePathOriginal + " @testing_stage")); - // check that file exists in stage after PUT - findFile(statement, "ls @testing_stage/"); + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE testing_stage"); + assertTrue( + "Failed to put a file", + statement.execute("PUT file://" + sourceFilePathOriginal + " @testing_stage")); + // check that file exists in stage after PUT + findFile(statement, "ls @testing_stage/"); - // put another file in same stage with same filename with overwrite = true - assertTrue( - "Failed to put a file", - statement.execute( - "PUT file://" + sourceFilePathOverwrite + " @testing_stage overwrite=true")); + // put another file in same stage with same filename with overwrite = true + assertTrue( + "Failed to put a file", + statement.execute( + "PUT file://" + sourceFilePathOverwrite + " @testing_stage overwrite=true")); - // check that file exists in stage after PUT - findFile(statement, "ls @testing_stage/"); + // check that file exists in stage after PUT + findFile(statement, "ls @testing_stage/"); - // get file from new stage - assertTrue( - "Failed to get files", - statement.execute( - "GET @testing_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); + // get file from new stage + assertTrue( + "Failed to get files", + statement.execute( + "GET @testing_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); - // Make sure that the downloaded file exists; it should be gzip compressed - File downloaded = new File(destFolderCanonicalPathWithSeparator + "testfile.csv.gz"); - assert (downloaded.exists()); + // Make sure that the downloaded file exists; it should be gzip compressed + File downloaded = new File(destFolderCanonicalPathWithSeparator + "testfile.csv.gz"); + assert (downloaded.exists()); - // unzip the file - Process p = - Runtime.getRuntime() - .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "testfile.csv.gz"); - p.waitFor(); + // unzip the file + Process p = + Runtime.getRuntime() + .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "testfile.csv.gz"); + p.waitFor(); - File unzipped = new File(destFolderCanonicalPathWithSeparator + "testfile.csv"); - assert (FileUtils.contentEqualsIgnoreEOL(file2, unzipped, null)); - } finally { - statement.execute("DROP TABLE IF EXISTS testLoadToLocalFS"); - statement.close(); + File unzipped = new File(destFolderCanonicalPathWithSeparator + "testfile.csv"); + assert (FileUtils.contentEqualsIgnoreEOL(file2, unzipped, null)); + } finally { + statement.execute("DROP TABLE IF EXISTS testLoadToLocalFS"); + } } } } @@ -1034,20 +964,14 @@ public void testPutOverwrite() throws Throwable { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPut() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; List accounts = Arrays.asList(null, "s3testaccount", "azureaccount", "gcpaccount"); for (int i = 0; i < accounts.size(); i++) { - try { - connection = getConnection(accounts.get(i)); - - statement = connection.createStatement(); - - // load file test - // create a unique data file name by using current timestamp in millis + try (Connection connection = getConnection(accounts.get(i)); + Statement statement = connection.createStatement()) { try { + // load file test + // create a unique data file name by using current timestamp in millis statement.execute("alter session set ENABLE_GCP_PUT_EXCEPTION_FOR_OLD_DRIVERS=false"); // test external table load statement.execute("CREATE OR REPLACE TABLE testLoadToLocalFS(a number)"); @@ -1060,361 +984,293 @@ public void testPut() throws Throwable { + getFullPathFileInResource(TEST_DATA_FILE) + " @%testLoadToLocalFS/orders parallel=10")); - resultSet = statement.getResultSet(); + try (ResultSet resultSet = statement.getResultSet()) { - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - - // assert column count - assertTrue(resultSetMetaData.getColumnCount() > 0); + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - assertTrue(resultSet.next()); // one row - assertFalse(resultSet.next()); + // assert column count + assertTrue(resultSetMetaData.getColumnCount() > 0); + assertTrue(resultSet.next()); // one row + assertFalse(resultSet.next()); + } findFile( statement, "ls @%testLoadToLocalFS/ pattern='.*orders/" + TEST_DATA_FILE + ".g.*'"); // remove files - resultSet = + try (ResultSet resultSet = statement.executeQuery( - "rm @%testLoadToLocalFS/ pattern='.*orders/" + TEST_DATA_FILE + ".g.*'"); - - resultSetMetaData = resultSet.getMetaData(); - - // assert column count - assertTrue(resultSetMetaData.getColumnCount() >= 1); + "rm @%testLoadToLocalFS/ pattern='.*orders/" + TEST_DATA_FILE + ".g.*'")) { + + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + + // assert column count + assertTrue(resultSetMetaData.getColumnCount() >= 1); + + // assert we get 1 row for the file we copied + assertTrue(resultSet.next()); + assertNotNull(resultSet.getString(1)); + assertFalse(resultSet.next()); + try { + resultSet.getString(1); // no more row + fail("must fail"); + } catch (SQLException ex) { + assertEquals( + (int) ErrorCode.COLUMN_DOES_NOT_EXIST.getMessageCode(), ex.getErrorCode()); + } - // assert we get 1 row for the file we copied - assertTrue(resultSet.next()); - assertNotNull(resultSet.getString(1)); - assertFalse(resultSet.next()); - try { - resultSet.getString(1); // no more row - fail("must fail"); - } catch (SQLException ex) { - assertEquals((int) ErrorCode.COLUMN_DOES_NOT_EXIST.getMessageCode(), ex.getErrorCode()); + Thread.sleep(100); } - - Thread.sleep(100); - // show files again - resultSet = statement.executeQuery("ls @%testLoadToLocalFS/ pattern='.*orders/orders.*'"); - - // assert we get 0 row - assertFalse(resultSet.next()); + try (ResultSet resultSet = + statement.executeQuery("ls @%testLoadToLocalFS/ pattern='.*orders/orders.*'")) { + // assert we get 0 row + assertFalse(resultSet.next()); + } } finally { statement.execute("DROP TABLE IF EXISTS testLoadToLocalFS"); - statement.close(); } - - } finally { - closeSQLObjects(resultSet, statement, connection); } } } static void findFile(Statement statement, String checkSQL) throws Throwable { boolean fileFound = false; - ResultSet resultSet = null; // tolerate at most 60 tries for the following loop for (int numSecs = 0; numSecs <= 60; numSecs++) { // show files - resultSet = statement.executeQuery(checkSQL); + try (ResultSet resultSet = statement.executeQuery(checkSQL)) { + + if (resultSet.next()) { + fileFound = true; + break; + } + // give enough time for s3 eventual consistency for US region + Thread.sleep(1000); + assertTrue("Could not find a file", fileFound); - if (resultSet.next()) { - fileFound = true; - break; + // assert the first column not null + assertNotNull("Null result", resultSet.getString(1)); } - // give enough time for s3 eventual consistency for US region - Thread.sleep(1000); } - assertTrue("Could not find a file", fileFound); - - // assert the first column not null - assertNotNull("Null result", resultSet.getString(1)); } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testSQLError42S02() throws SQLException { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { // execute a bad query - try { - resultSet = statement.executeQuery("SELECT * FROM nonexistence"); - + try (ResultSet resultSet = statement.executeQuery("SELECT * FROM nonexistence")) { fail("SQL exception not raised"); } catch (SQLException ex1) { // assert the sqlstate "42S02" which means BASE_TABLE_OR_VIEW_NOT_FOUND assertEquals("sqlstate mismatch", "42S02", ex1.getSQLState()); } - } finally { - closeSQLObjects(resultSet, statement, connection); } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testExplainPlan() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - statement = connection.createStatement(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement(); - // test explain plan: sorry not available for general but debugging purpose only - resultSet = statement.executeQuery("EXPLAIN PLAN FOR SELECT c1 FROM orders_jdbc"); + // test explain plan: sorry not available for general but debugging purpose only + ResultSet resultSet = + statement.executeQuery("EXPLAIN PLAN FOR SELECT c1 FROM orders_jdbc")) { ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); assertTrue("must return more than 4 columns", resultSetMetaData.getColumnCount() >= 4); assertTrue("must return more than 3 rows", countRows(resultSet) > 3); - - statement.close(); - - } finally { - closeSQLObjects(resultSet, statement, connection); } } @Test public void testTimestampParsing() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - resultSet = - statement.executeQuery( - "select to_timestamp('2013-05-08T15:39:20.123-07:00') from orders_jdbc"); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement(); + ResultSet resultSet = + statement.executeQuery( + "select to_timestamp('2013-05-08T15:39:20.123-07:00') from orders_jdbc")) { assertTrue(resultSet.next()); assertEquals("Wed, 08 May 2013 15:39:20 -0700", resultSet.getString(1)); - } finally { - closeSQLObjects(resultSet, statement, connection); } } @Test public void testDateParsing() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - statement = connection.createStatement(); - resultSet = statement.executeQuery("select to_date('0001-01-01')"); - + try (Connection connection = getConnection(); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("select to_date('0001-01-01')")) { assertTrue(resultSet.next()); assertEquals("0001-01-01", resultSet.getString(1)); - } finally { - closeSQLObjects(resultSet, statement, connection); } } @Test public void testTimeParsing() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - statement = connection.createStatement(); - resultSet = statement.executeQuery("select to_time('15:39:20.123') from orders_jdbc"); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement(); + ResultSet resultSet = + statement.executeQuery("select to_time('15:39:20.123') from orders_jdbc")) { assertTrue(resultSet.next()); assertEquals("15:39:20", resultSet.getString(1)); - } finally { - closeSQLObjects(resultSet, statement, connection); } } @Test public void testClientSideSorting() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; + ResultSetMetaData resultSetMetaData = null; - try { - connection = getConnection(); - - statement = connection.createStatement(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { // turn on sorting mode statement.execute("set-sf-property sort on"); - resultSet = statement.executeQuery("SELECT c3 FROM orders_jdbc"); + try (ResultSet resultSet = statement.executeQuery("SELECT c3 FROM orders_jdbc")) { + resultSetMetaData = resultSet.getMetaData(); - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - - // assert column count - assertEquals(1, resultSetMetaData.getColumnCount()); + // assert column count + assertEquals(1, resultSetMetaData.getColumnCount()); - // assert the values for the first 5 rows - for (int i = 0; i < 5; i++) { - assertTrue(resultSet.next()); + // assert the values for the first 5 rows + for (int i = 0; i < 5; i++) { + assertTrue(resultSet.next()); - // assert each column is 'F' - assertEquals("F", resultSet.getString(1)); + // assert each column is 'F' + assertEquals("F", resultSet.getString(1)); + } } - // turn off sorting mode statement.execute("set-sf-property sort off"); - resultSet = statement.executeQuery("SELECT c3 FROM orders_jdbc order by c3 desc"); + try (ResultSet resultSet = + statement.executeQuery("SELECT c3 FROM orders_jdbc order by c3 desc")) { - resultSetMetaData = resultSet.getMetaData(); + resultSetMetaData = resultSet.getMetaData(); - // assert column count - assertEquals(1, resultSetMetaData.getColumnCount()); + // assert column count + assertEquals(1, resultSetMetaData.getColumnCount()); - // assert the values for the first 4 rows - for (int i = 0; i < 4; i++) { - assertTrue(resultSet.next()); + // assert the values for the first 4 rows + for (int i = 0; i < 4; i++) { + assertTrue(resultSet.next()); - // assert each column is 'P' - assertEquals("P", resultSet.getString(1)); + // assert each column is 'P' + assertEquals("P", resultSet.getString(1)); + } } - } finally { - closeSQLObjects(resultSet, statement, connection); } } @Test public void testUpdateCount() throws Throwable { - Connection connection = null; - Statement statement = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - - // create test table - statement.execute("CREATE OR REPLACE TABLE testUpdateCount(version number, name string)"); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + // create test table + statement.execute("CREATE OR REPLACE TABLE testUpdateCount(version number, name string)"); - // insert two rows - int numRows = - statement.executeUpdate("INSERT INTO testUpdateCount values (1, 'a'), (2, 'b')"); + // insert two rows + int numRows = + statement.executeUpdate("INSERT INTO testUpdateCount values (1, 'a'), (2, 'b')"); - assertEquals("Unexpected number of rows inserted: " + numRows, 2, numRows); - } finally { - if (statement != null) { + assertEquals("Unexpected number of rows inserted: " + numRows, 2, numRows); + } finally { statement.execute("DROP TABLE if exists testUpdateCount"); } - closeSQLObjects(null, statement, connection); } } @Test public void testSnow4245() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - // set timestamp format - statement.execute("alter session set timestamp_input_format = 'YYYY-MM-DD HH24:MI:SS';"); - - // create test table with different time zone flavors - String createSQL = - "create or replace table testSnow4245(t timestamp with local time " - + "zone,ntz timestamp without time zone,tz timestamp with time zone)"; - statement.execute(createSQL); - - // populate - int numRows = - statement.executeUpdate( - "insert into testSnow4245 values(NULL,NULL,NULL)," - + "('2013-06-04 01:00:04','2013-06-04 01:00:04','2013-06-04 01:00:04')," - + "('2013-06-05 23:00:05','2013-06-05 23:00:05','2013-06-05 23:00:05')"); - assertEquals("Unexpected number of rows inserted: " + numRows, 3, numRows); - - // query the data - resultSet = - statement.executeQuery( - "SELECT * FROM testSnow4245 order by 1 " - + "nulls first, 2 nulls first, 3 nulls first"); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + // set timestamp format + statement.execute("alter session set timestamp_input_format = 'YYYY-MM-DD HH24:MI:SS';"); + + // create test table with different time zone flavors + String createSQL = + "create or replace table testSnow4245(t timestamp with local time " + + "zone,ntz timestamp without time zone,tz timestamp with time zone)"; + statement.execute(createSQL); + + // populate + int numRows = + statement.executeUpdate( + "insert into testSnow4245 values(NULL,NULL,NULL)," + + "('2013-06-04 01:00:04','2013-06-04 01:00:04','2013-06-04 01:00:04')," + + "('2013-06-05 23:00:05','2013-06-05 23:00:05','2013-06-05 23:00:05')"); + assertEquals("Unexpected number of rows inserted: " + numRows, 3, numRows); + + // query the data + try (ResultSet resultSet = + statement.executeQuery( + "SELECT * FROM testSnow4245 order by 1 " + + "nulls first, 2 nulls first, 3 nulls first")) { - int i = 0; - // assert we get 3 rows + int i = 0; + // assert we get 3 rows - while (resultSet.next()) { - // assert each column is not null except the first row + while (resultSet.next()) { + // assert each column is not null except the first row - if (i == 0) { - for (int j = 1; j < 4; j++) { - assertNull(resultSet.getString(j), resultSet.getString(j)); - } - } else { - for (int j = 1; j < 4; j++) { - assertNotNull(resultSet.getString(j), resultSet.getString(j)); + if (i == 0) { + for (int j = 1; j < 4; j++) { + assertNull(resultSet.getString(j), resultSet.getString(j)); + } + } else { + for (int j = 1; j < 4; j++) { + assertNotNull(resultSet.getString(j), resultSet.getString(j)); + } + } + i = i + 1; } } - i = i + 1; - } - } finally { - if (statement != null) { + } finally { statement.execute("drop table testSnow4245"); } - closeSQLObjects(resultSet, statement, connection); } } /** SNOW-4394 - Four bytes UTF-8 characters are not returned correctly. */ @Test public void testSnow4394() throws Throwable { - Connection connection = null; - Statement statement = null; - String tableName = String.format("snow4394_%s", UUID.randomUUID().toString()).replaceAll("-", "_"); - try { - connection = getConnection(); - - statement = connection.createStatement(); - + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { // create test table - statement.execute(String.format("CREATE OR REPLACE TABLE %s(str string)", tableName)); - - String data = "What is \ud83d\ude12?"; - // insert two rows - int numRows = - statement.executeUpdate( - String.format("INSERT INTO %s(str) values('%s')", tableName, data)); - assertEquals("Unexpected number of rows inserted: " + numRows, 1, numRows); - - ResultSet rset = statement.executeQuery(String.format("SELECT str FROM %s", tableName)); - String ret = null; - while (rset.next()) { - ret = rset.getString(1); - } - rset.close(); - assertEquals("Unexpected string value: " + ret, data, ret); - } finally { - if (statement != null) { + try { + statement.execute(String.format("CREATE OR REPLACE TABLE %s(str string)", tableName)); + + String data = "What is \ud83d\ude12?"; + // insert two rows + int numRows = + statement.executeUpdate( + String.format("INSERT INTO %s(str) values('%s')", tableName, data)); + assertEquals("Unexpected number of rows inserted: " + numRows, 1, numRows); + + try (ResultSet rset = + statement.executeQuery(String.format("SELECT str FROM %s", tableName))) { + String ret = null; + while (rset.next()) { + ret = rset.getString(1); + } + assertEquals("Unexpected string value: " + ret, data, ret); + } + } finally { statement.execute(String.format("DROP TABLE if exists %s", tableName)); - statement.close(); } - closeSQLObjects(null, statement, connection); } } @@ -1447,1116 +1303,1017 @@ private void addBindBatch(PreparedStatement preparedStatement, java.sql.Date sql @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void test31448() throws Throwable { - Connection connection = getConnection(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + + statement.execute( + "alter session set enable_fix_31448_2=2, " + "error_on_generic_pruner=true;"); - Statement statement = connection.createStatement(); - - statement.execute("alter session set enable_fix_31448_2=2, " + "error_on_generic_pruner=true;"); - - statement.execute("alter session set timestamp_type_mapping=timestamp_ntz"); - - statement.execute("create or replace table " + "bug56658(iv number, tsv timestamp_ntz)"); - statement.execute( - "insert into bug56658 select seq8(), " - + "timestampadd(day, seq8(), '1970-01-13 00:00:00'::timestamp_ntz)\n" - + "from table(generator(rowcount=>20))"); - - connection - .unwrap(SnowflakeConnectionV1.class) - .getSfSession() - .setTimestampMappedType(SnowflakeType.TIMESTAMP_NTZ); - Timestamp ts = buildTimestamp(1970, 0, 15, 10, 14, 30, 0); - PreparedStatement preparedStatement = - connection.prepareStatement( - "select iv, tsv from bug56658 where tsv" + " >= ? and tsv <= ? order by iv;"); - statement.execute("alter session set timestamp_type_mapping=timestamp_ntz"); - Timestamp ts2 = buildTimestamp(1970, 0, 18, 10, 14, 30, 0); - preparedStatement.setTimestamp(1, ts); - preparedStatement.setTimestamp(2, ts2); - preparedStatement.executeQuery(); + statement.execute("alter session set timestamp_type_mapping=timestamp_ntz"); + + statement.execute("create or replace table " + "bug56658(iv number, tsv timestamp_ntz)"); + statement.execute( + "insert into bug56658 select seq8(), " + + "timestampadd(day, seq8(), '1970-01-13 00:00:00'::timestamp_ntz)\n" + + "from table(generator(rowcount=>20))"); + + connection + .unwrap(SnowflakeConnectionV1.class) + .getSfSession() + .setTimestampMappedType(SnowflakeType.TIMESTAMP_NTZ); + Timestamp ts = buildTimestamp(1970, 0, 15, 10, 14, 30, 0); + try (PreparedStatement preparedStatement = + connection.prepareStatement( + "select iv, tsv from bug56658 where tsv" + " >= ? and tsv <= ? order by iv;")) { + statement.execute("alter session set timestamp_type_mapping=timestamp_ntz"); + Timestamp ts2 = buildTimestamp(1970, 0, 18, 10, 14, 30, 0); + preparedStatement.setTimestamp(1, ts); + preparedStatement.setTimestamp(2, ts2); + preparedStatement.executeQuery(); + } + } } @Test public void testBind() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - preparedStatement = connection.prepareStatement("SELECT ?, ?"); - - // bind integer - preparedStatement.setInt(1, 1); - preparedStatement.setString(2, "hello"); - resultSet = preparedStatement.executeQuery(); - - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - - // assert column count - assertEquals(2, resultSetMetaData.getColumnCount()); - assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); - - // assert we get 1 rows - assertTrue(resultSet.next()); - - assertEquals("integer", 1, resultSet.getInt(1)); - assertEquals("string", "hello", resultSet.getString(2)); - - // bind float - preparedStatement.setDouble(1, 1.2); - resultSet = preparedStatement.executeQuery(); - - resultSetMetaData = resultSet.getMetaData(); - - // assert column count - assertEquals(2, resultSetMetaData.getColumnCount()); - assertEquals(Types.DOUBLE, resultSetMetaData.getColumnType(1)); - - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("double", 1.2, resultSet.getDouble(1), 0); - assertEquals("string", "hello", resultSet.getString(2)); - - // bind string - preparedStatement.setString(1, "hello"); - resultSet = preparedStatement.executeQuery(); - - resultSetMetaData = resultSet.getMetaData(); + ResultSetMetaData resultSetMetaData = null; + Timestamp ts = null; + Time tm = null; + java.sql.Date sqlDate = null; + int[] updateCounts; + try (Connection connection = getConnection()) { + try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT ?, ?")) { - // assert column count - assertEquals(2, resultSetMetaData.getColumnCount()); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(1)); + // bind integer + preparedStatement.setInt(1, 1); + preparedStatement.setString(2, "hello"); + try (ResultSet resultSet = preparedStatement.executeQuery()) { - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("string1", "hello", resultSet.getString(1)); - assertEquals("string2", "hello", resultSet.getString(2)); + resultSetMetaData = resultSet.getMetaData(); - // bind date - java.sql.Date sqlDate = java.sql.Date.valueOf("2014-08-26"); - preparedStatement.setDate(1, sqlDate); - resultSet = preparedStatement.executeQuery(); + // assert column count + assertEquals(2, resultSetMetaData.getColumnCount()); + assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); - resultSetMetaData = resultSet.getMetaData(); + // assert we get 1 rows + assertTrue(resultSet.next()); - // assert column count - assertEquals(2, resultSetMetaData.getColumnCount()); - assertEquals(Types.DATE, resultSetMetaData.getColumnType(1)); + assertEquals("integer", 1, resultSet.getInt(1)); + assertEquals("string", "hello", resultSet.getString(2)); + } + // bind float + preparedStatement.setDouble(1, 1.2); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("string", "2014-08-26", resultSet.getString(1)); - assertEquals("string", "hello", resultSet.getString(2)); + // assert column count + assertEquals(2, resultSetMetaData.getColumnCount()); + assertEquals(Types.DOUBLE, resultSetMetaData.getColumnType(1)); - // bind timestamp - Timestamp ts = buildTimestamp(2014, 7, 26, 3, 52, 0, 0); - preparedStatement.setTimestamp(1, ts); - resultSet = preparedStatement.executeQuery(); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("double", 1.2, resultSet.getDouble(1), 0); + assertEquals("string", "hello", resultSet.getString(2)); + } + // bind string + preparedStatement.setString(1, "hello"); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - resultSetMetaData = resultSet.getMetaData(); + // assert column count + assertEquals(2, resultSetMetaData.getColumnCount()); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(1)); - // assert column count - assertEquals(2, resultSetMetaData.getColumnCount()); - assertEquals(Types.TIMESTAMP, resultSetMetaData.getColumnType(1)); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("string1", "hello", resultSet.getString(1)); + assertEquals("string2", "hello", resultSet.getString(2)); + } + // bind date + sqlDate = java.sql.Date.valueOf("2014-08-26"); + preparedStatement.setDate(1, sqlDate); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals( - "Incorrect timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(1)); - assertEquals("string", "hello", resultSet.getString(2)); + // assert column count + assertEquals(2, resultSetMetaData.getColumnCount()); + assertEquals(Types.DATE, resultSetMetaData.getColumnType(1)); - // bind time - Time tm = new Time(12345678); // 03:25:45.678 - preparedStatement.setTime(1, tm); - resultSet = preparedStatement.executeQuery(); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("string", "2014-08-26", resultSet.getString(1)); + assertEquals("string", "hello", resultSet.getString(2)); + } + // bind timestamp + ts = buildTimestamp(2014, 7, 26, 3, 52, 0, 0); + preparedStatement.setTimestamp(1, ts); + try (ResultSet resultSet = preparedStatement.executeQuery()) { - resultSetMetaData = resultSet.getMetaData(); + resultSetMetaData = resultSet.getMetaData(); - // assert column count - assertEquals(2, resultSetMetaData.getColumnCount()); - assertEquals(Types.TIME, resultSetMetaData.getColumnType(1)); + // assert column count + assertEquals(2, resultSetMetaData.getColumnCount()); + assertEquals(Types.TIMESTAMP, resultSetMetaData.getColumnType(1)); - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("Incorrect time", "03:25:45", resultSet.getString(1)); - assertEquals("string", "hello", resultSet.getString(2)); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals( + "Incorrect timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(1)); + assertEquals("string", "hello", resultSet.getString(2)); + } + // bind time + tm = new Time(12345678); // 03:25:45.678 + preparedStatement.setTime(1, tm); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - preparedStatement.close(); + // assert column count + assertEquals(2, resultSetMetaData.getColumnCount()); + assertEquals(Types.TIME, resultSetMetaData.getColumnType(1)); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("Incorrect time", "03:25:45", resultSet.getString(1)); + assertEquals("string", "hello", resultSet.getString(2)); + } + } // bind in where clause - preparedStatement = - connection.prepareStatement("SELECT * FROM orders_jdbc WHERE to_number(c1) = ?"); + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT * FROM orders_jdbc WHERE to_number(c1) = ?")) { - preparedStatement.setInt(1, 100); - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); - - // assert column count - assertEquals(9, resultSetMetaData.getColumnCount()); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(1)); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); + preparedStatement.setInt(1, 100); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("c1", "100", resultSet.getString(1)); - assertEquals("c2", "147004", resultSet.getString(2)); + // assert column count + assertEquals(9, resultSetMetaData.getColumnCount()); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(1)); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); - preparedStatement.close(); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("c1", "100", resultSet.getString(1)); + assertEquals("c2", "147004", resultSet.getString(2)); + } + } // bind in insert statement // create a test table - regularStatement = connection.createStatement(); - regularStatement.executeUpdate( - "create or replace table testBind(a int, b string, c double, d date, " - + "e timestamp, f time, g date)"); + try (Statement regularStatement = connection.createStatement()) { + regularStatement.executeUpdate( + "create or replace table testBind(a int, b string, c double, d date, " + + "e timestamp, f time, g date)"); - preparedStatement = - connection.prepareStatement( - "insert into testBind(a, b, c, d, e, f) values(?, ?, ?, ?, ?, ?)"); + try (PreparedStatement preparedStatement = + connection.prepareStatement( + "insert into testBind(a, b, c, d, e, f) values(?, ?, ?, ?, ?, ?)")) { + + preparedStatement.setInt(1, 1); + preparedStatement.setString(2, "hello"); + preparedStatement.setDouble(3, 1.2); + preparedStatement.setDate(4, sqlDate); + preparedStatement.setTimestamp(5, ts); + preparedStatement.setTime(6, tm); + int rowCount = preparedStatement.executeUpdate(); + + // update count should be 1 + assertEquals("update count", 1, rowCount); + + // test the inserted rows + try (ResultSet resultSet = regularStatement.executeQuery("select * from testBind")) { + + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("int", 1, resultSet.getInt(1)); + assertEquals("string", "hello", resultSet.getString(2)); + assertEquals("double", 1.2, resultSet.getDouble(3), 0); + assertEquals("date", "2014-08-26", resultSet.getString(4)); + assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(5)); + assertEquals("time", "03:25:45", resultSet.getString(6)); + assertNull("date", resultSet.getString(7)); + } + } + // bind in update statement + try (PreparedStatement preparedStatement = + connection.prepareStatement("update testBind set b=? where a=?")) { + preparedStatement.setString(1, "world"); + preparedStatement.setInt(2, 1); + preparedStatement.execute(); + } - preparedStatement.setInt(1, 1); - preparedStatement.setString(2, "hello"); - preparedStatement.setDouble(3, 1.2); - preparedStatement.setDate(4, sqlDate); - preparedStatement.setTimestamp(5, ts); - preparedStatement.setTime(6, tm); - int rowCount = preparedStatement.executeUpdate(); + // test the updated rows + try (ResultSet resultSet = regularStatement.executeQuery("select * from testBind")) { + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("int", 1, resultSet.getInt(1)); + assertEquals("string", "world", resultSet.getString(2)); + assertEquals("double", 1.2, resultSet.getDouble(3), 0); + assertEquals("date", "2014-08-26", resultSet.getString(4)); + assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(5)); + assertEquals("time", "03:25:45", resultSet.getString(6)); + assertNull("date", resultSet.getString(7)); + } + // array bind for insert + try (PreparedStatement preparedStatement = + connection.prepareStatement( + "insert into testBind (a, b, c, d, e, f, g) " + + "values(?, ?, ?, ?, ?, ?, current_date())")) { + + preparedStatement.setInt(1, 2); + preparedStatement.setString(2, "hello"); + preparedStatement.setDouble(3, 1.2); + preparedStatement.setDate(4, sqlDate); + preparedStatement.setTimestamp(5, ts); + preparedStatement.setTime(6, tm); + preparedStatement.addBatch(); + + preparedStatement.setInt(1, 3); + preparedStatement.setString(2, "hello"); + preparedStatement.setDouble(3, 1.2); + preparedStatement.setDate(4, sqlDate); + preparedStatement.setTimestamp(5, ts); + preparedStatement.setTime(6, tm); + preparedStatement.addBatch(); + + updateCounts = preparedStatement.executeBatch(); + + // GS optimizes this into one insert execution, but we expand the + // return count into an array + assertEquals("Number of update counts", 2, updateCounts.length); + + // update count should be 1 for each + assertEquals("update count", 1, updateCounts[0]); + assertEquals("update count", 1, updateCounts[1]); + } + // test the inserted rows + try (ResultSet resultSet = + regularStatement.executeQuery("select * from testBind where a = 2")) { - // update count should be 1 - assertEquals("update count", 1, rowCount); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("int", 2, resultSet.getInt(1)); + assertEquals("string", "hello", resultSet.getString(2)); + assertEquals("double", 1.2, resultSet.getDouble(3), 0); + assertEquals("date", "2014-08-26", resultSet.getString(4)); + assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(5)); + assertEquals("time", "03:25:45", resultSet.getString(6)); + } - // test the inserted rows - resultSet = regularStatement.executeQuery("select * from testBind"); + try (ResultSet resultSet = + regularStatement.executeQuery("select * from testBind where a = 3")) { - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("int", 1, resultSet.getInt(1)); - assertEquals("string", "hello", resultSet.getString(2)); - assertEquals("double", 1.2, resultSet.getDouble(3), 0); - assertEquals("date", "2014-08-26", resultSet.getString(4)); - assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(5)); - assertEquals("time", "03:25:45", resultSet.getString(6)); - assertNull("date", resultSet.getString(7)); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("int", 3, resultSet.getInt(1)); + assertEquals("string", "hello", resultSet.getString(2)); + assertEquals("double", 1.2, resultSet.getDouble(3), 0); + assertEquals("date", "2014-08-26", resultSet.getString(4)); + assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(5)); + assertEquals("time", "03:25:45", resultSet.getString(6)); + } - // bind in update statement - preparedStatement = connection.prepareStatement("update testBind set b=? where a=?"); + // describe mode + try (PreparedStatement preparedStatement = + connection.prepareStatement("select * from testBind WHERE to_number(a) = ?")) { + + resultSetMetaData = preparedStatement.getMetaData(); + assertEquals(7, resultSetMetaData.getColumnCount()); + assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); + assertEquals(Types.DOUBLE, resultSetMetaData.getColumnType(3)); + assertEquals(Types.DATE, resultSetMetaData.getColumnType(4)); + assertEquals(Types.TIMESTAMP, resultSetMetaData.getColumnType(5)); + assertEquals(Types.TIME, resultSetMetaData.getColumnType(6)); + assertEquals(Types.DATE, resultSetMetaData.getColumnType(7)); + } - preparedStatement.setString(1, "world"); - preparedStatement.setInt(2, 1); - preparedStatement.execute(); + try (PreparedStatement preparedStatement = connection.prepareStatement("select ?, ?")) { + resultSetMetaData = preparedStatement.getMetaData(); + assertEquals(2, resultSetMetaData.getColumnCount()); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(1)); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); + } - preparedStatement.close(); + try (PreparedStatement preparedStatement = connection.prepareStatement("select ?, ?")) { - // test the updated rows - resultSet = regularStatement.executeQuery("select * from testBind"); + preparedStatement.setInt(1, 1); + preparedStatement.setString(2, "hello"); + ResultSet result = preparedStatement.executeQuery(); - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("int", 1, resultSet.getInt(1)); - assertEquals("string", "world", resultSet.getString(2)); - assertEquals("double", 1.2, resultSet.getDouble(3), 0); - assertEquals("date", "2014-08-26", resultSet.getString(4)); - assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(5)); - assertEquals("time", "03:25:45", resultSet.getString(6)); - assertNull("date", resultSet.getString(7)); - - // array bind for insert - preparedStatement = - connection.prepareStatement( - "insert into testBind (a, b, c, d, e, f, g) " - + "values(?, ?, ?, ?, ?, ?, current_date())"); - - preparedStatement.setInt(1, 2); - preparedStatement.setString(2, "hello"); - preparedStatement.setDouble(3, 1.2); - preparedStatement.setDate(4, sqlDate); - preparedStatement.setTimestamp(5, ts); - preparedStatement.setTime(6, tm); - preparedStatement.addBatch(); - - preparedStatement.setInt(1, 3); - preparedStatement.setString(2, "hello"); - preparedStatement.setDouble(3, 1.2); - preparedStatement.setDate(4, sqlDate); - preparedStatement.setTimestamp(5, ts); - preparedStatement.setTime(6, tm); - preparedStatement.addBatch(); - - int[] updateCounts = preparedStatement.executeBatch(); - - // GS optimizes this into one insert execution, but we expand the - // return count into an array - assertEquals("Number of update counts", 2, updateCounts.length); - - // update count should be 1 for each - assertEquals("update count", 1, updateCounts[0]); - assertEquals("update count", 1, updateCounts[1]); - - // test the inserted rows - resultSet = regularStatement.executeQuery("select * from testBind where a = 2"); - - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("int", 2, resultSet.getInt(1)); - assertEquals("string", "hello", resultSet.getString(2)); - assertEquals("double", 1.2, resultSet.getDouble(3), 0); - assertEquals("date", "2014-08-26", resultSet.getString(4)); - assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(5)); - assertEquals("time", "03:25:45", resultSet.getString(6)); + resultSetMetaData = result.getMetaData(); + assertEquals(2, resultSetMetaData.getColumnCount()); + assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); + } - resultSet = regularStatement.executeQuery("select * from testBind where a = 3"); + // test null binding + try (PreparedStatement preparedStatement = connection.prepareStatement("select ?")) { - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("int", 3, resultSet.getInt(1)); - assertEquals("string", "hello", resultSet.getString(2)); - assertEquals("double", 1.2, resultSet.getDouble(3), 0); - assertEquals("date", "2014-08-26", resultSet.getString(4)); - assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(5)); - assertEquals("time", "03:25:45", resultSet.getString(6)); - - // describe mode - preparedStatement = - connection.prepareStatement("select * from testBind WHERE to_number(a) = ?"); - - resultSetMetaData = preparedStatement.getMetaData(); - assertEquals(7, resultSetMetaData.getColumnCount()); - assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); - assertEquals(Types.DOUBLE, resultSetMetaData.getColumnType(3)); - assertEquals(Types.DATE, resultSetMetaData.getColumnType(4)); - assertEquals(Types.TIMESTAMP, resultSetMetaData.getColumnType(5)); - assertEquals(Types.TIME, resultSetMetaData.getColumnType(6)); - assertEquals(Types.DATE, resultSetMetaData.getColumnType(7)); - - preparedStatement.close(); - preparedStatement = connection.prepareStatement("select ?, ?"); - - resultSetMetaData = preparedStatement.getMetaData(); - assertEquals(2, resultSetMetaData.getColumnCount()); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(1)); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); - - preparedStatement.close(); - preparedStatement = connection.prepareStatement("select ?, ?"); - - preparedStatement.setInt(1, 1); - preparedStatement.setString(2, "hello"); - ResultSet result = preparedStatement.executeQuery(); - - resultSetMetaData = result.getMetaData(); - assertEquals(2, resultSetMetaData.getColumnCount()); - assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); - - preparedStatement.close(); - - // test null binding - preparedStatement = connection.prepareStatement("select ?"); - - preparedStatement.setNull(1, Types.VARCHAR); - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); - - // assert column count - assertEquals(1, resultSetMetaData.getColumnCount()); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(1)); - - // assert we get 1 rows - assertTrue(resultSet.next()); - assertNull(resultSet.getObject(1)); + preparedStatement.setNull(1, Types.VARCHAR); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - preparedStatement.setNull(1, Types.INTEGER); - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); + // assert column count + assertEquals(1, resultSetMetaData.getColumnCount()); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(1)); - // assert column count - assertEquals(1, resultSetMetaData.getColumnCount()); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertNull(resultSet.getObject(1)); + } + preparedStatement.setNull(1, Types.INTEGER); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - // assert we get 1 rows - assertTrue(resultSet.next()); - assertNull(resultSet.getObject(1)); + // assert column count + assertEquals(1, resultSetMetaData.getColumnCount()); - preparedStatement.close(); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertNull(resultSet.getObject(1)); + } + } + } // bind in insert statement // create a test table - regularStatement = connection.createStatement(); - regularStatement.executeUpdate( - "create or replace table testBind1(c1 double, c2 string, c3 date, " - + "c4 date, c5 string, c6 date, c7 string, c8 string, " - + "c9 string, c10 string, c11 string, c12 date, c13 string, " - + "c14 float, c15 string, c16 string, c17 string, c18 string," - + "c19 string, c20 date, c21 string)"); - - // array bind for insert - preparedStatement = - connection.prepareStatement( - "insert into testBind1 (c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, " - + "c12, c13, c14, c15, c16, c17, c18, c19, c20, c21) values " - + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?," - + " ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + try (Statement regularStatement = connection.createStatement()) { + regularStatement.executeUpdate( + "create or replace table testBind1(c1 double, c2 string, c3 date, " + + "c4 date, c5 string, c6 date, c7 string, c8 string, " + + "c9 string, c10 string, c11 string, c12 date, c13 string, " + + "c14 float, c15 string, c16 string, c17 string, c18 string," + + "c19 string, c20 date, c21 string)"); + + // array bind for insert + try (PreparedStatement preparedStatement = + connection.prepareStatement( + "insert into testBind1 (c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, " + + "c12, c13, c14, c15, c16, c17, c18, c19, c20, c21) values " + + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { - for (int idx = 0; idx < 16; idx++) { - addBindBatch(preparedStatement, sqlDate); - } + for (int idx = 0; idx < 16; idx++) { + addBindBatch(preparedStatement, sqlDate); + } - updateCounts = preparedStatement.executeBatch(); + updateCounts = preparedStatement.executeBatch(); - // GS optimizes this into one insert execution - assertEquals("Number of update counts", 16, updateCounts.length); + // GS optimizes this into one insert execution + assertEquals("Number of update counts", 16, updateCounts.length); - for (int idx = 0; idx < 16; idx++) { - assertEquals("update count", 1, updateCounts[idx]); - } - } finally { - if (regularStatement != null) { - regularStatement.execute("DROP TABLE testBind"); - regularStatement.close(); + for (int idx = 0; idx < 16; idx++) { + assertEquals("update count", 1, updateCounts[idx]); + } + } } - - closeSQLObjects(resultSet, preparedStatement, connection); + connection.createStatement().execute("DROP TABLE testBind"); } } @Test public void testTableBind() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - // select * from table(?) - preparedStatement = connection.prepareStatement("SELECT * from table(?)"); - ResultSetMetaData resultSetMetaData = preparedStatement.getMetaData(); - // we do not have any metadata, without a specified table - assertEquals(0, resultSetMetaData.getColumnCount()); - - preparedStatement.setString(1, ORDERS_JDBC); - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); - assertEquals(9, resultSetMetaData.getColumnCount()); - // assert we have 73 rows - for (int i = 0; i < 73; i++) { - assertTrue(resultSet.next()); - } - assertFalse(resultSet.next()); - - preparedStatement.close(); - - // select * from table(?) where c1 = 1 - preparedStatement = connection.prepareStatement("SELECT * from table(?) where c1 = 1"); - preparedStatement.setString(1, ORDERS_JDBC); - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); - - assertEquals(9, resultSetMetaData.getColumnCount()); - assertTrue(resultSet.next()); - assertFalse(resultSet.next()); - - preparedStatement.close(); - - // select * from table(?) where c1 = 2 order by c3 - preparedStatement = connection.prepareStatement("SELECT * from table(?) order by c3"); - preparedStatement.setString(1, ORDERS_JDBC); - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); - - assertEquals(9, resultSetMetaData.getColumnCount()); - // assert we have 73 rows - for (int i = 0; i < 73; i++) { - assertTrue(resultSet.next()); - } - assertFalse(resultSet.next()); - - preparedStatement.close(); - - regularStatement = connection.createStatement(); - regularStatement.execute("create or replace table testTableBind(c integer, d string)"); + ResultSetMetaData resultSetMetaData = null; - // insert into table - regularStatement = connection.createStatement(); - regularStatement.executeUpdate("insert into testTableBind (c, d) values (1, 'one')"); - - // select c1, c from table(?), testTableBind - preparedStatement = connection.prepareStatement("SELECT * from table(?), testTableBind"); - preparedStatement.setString(1, ORDERS_JDBC); - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); - - assertEquals(11, resultSetMetaData.getColumnCount()); - // assert we have 73 rows - for (int i = 0; i < 73; i++) { - assertTrue(resultSet.next()); - } - assertFalse(resultSet.next()); - - preparedStatement.close(); - - // select * from table(?), table(?) - preparedStatement = connection.prepareStatement("SELECT * from table(?), table(?)"); - preparedStatement.setString(1, ORDERS_JDBC); - preparedStatement.setString(2, "testTableBind"); - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); + try (Connection connection = getConnection(); + Statement regularStatement = connection.createStatement()) { + try { + // select * from table(?) + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT * from table(?)")) { + resultSetMetaData = preparedStatement.getMetaData(); + // we do not have any metadata, without a specified table + assertEquals(0, resultSetMetaData.getColumnCount()); + + preparedStatement.setString(1, ORDERS_JDBC); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); + assertEquals(9, resultSetMetaData.getColumnCount()); + // assert we have 73 rows + for (int i = 0; i < 73; i++) { + assertTrue(resultSet.next()); + } + assertFalse(resultSet.next()); + } + } - assertEquals(11, resultSetMetaData.getColumnCount()); - // assert we have 73 rows - for (int i = 0; i < 73; i++) { - assertTrue(resultSet.next()); - } - assertFalse(resultSet.next()); + // select * from table(?) where c1 = 1 + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT * from table(?) where c1 = 1")) { + preparedStatement.setString(1, ORDERS_JDBC); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - preparedStatement.close(); + assertEquals(9, resultSetMetaData.getColumnCount()); + assertTrue(resultSet.next()); + assertFalse(resultSet.next()); + } + } - // select tab1.c1, tab2.c from table(?) as a, table(?) as b - preparedStatement = - connection.prepareStatement("SELECT a.c1, b.c from table(?) as a, table(?) as b"); - preparedStatement.setString(1, ORDERS_JDBC); - preparedStatement.setString(2, "testTableBind"); - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); + // select * from table(?) where c1 = 2 order by c3 + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT * from table(?) order by c3")) { + preparedStatement.setString(1, ORDERS_JDBC); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); + + assertEquals(9, resultSetMetaData.getColumnCount()); + // assert we have 73 rows + for (int i = 0; i < 73; i++) { + assertTrue(resultSet.next()); + } + assertFalse(resultSet.next()); + } + } - assertEquals(2, resultSetMetaData.getColumnCount()); - // assert we have 73 rows - for (int i = 0; i < 73; i++) { - assertTrue(resultSet.next()); - } - assertFalse(resultSet.next()); + regularStatement.execute("create or replace table testTableBind(c integer, d string)"); + // insert into table + regularStatement.executeUpdate("insert into testTableBind (c, d) values (1, 'one')"); + // select c1, c from table(?), testTableBind + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT * from table(?), testTableBind")) { + preparedStatement.setString(1, ORDERS_JDBC); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); + + assertEquals(11, resultSetMetaData.getColumnCount()); + // assert we have 73 rows + for (int i = 0; i < 73; i++) { + assertTrue(resultSet.next()); + } + assertFalse(resultSet.next()); + } + } - preparedStatement.close(); + // select * from table(?), table(?) + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT * from table(?), table(?)")) { + preparedStatement.setString(1, ORDERS_JDBC); + preparedStatement.setString(2, "testTableBind"); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); + + assertEquals(11, resultSetMetaData.getColumnCount()); + // assert we have 73 rows + for (int i = 0; i < 73; i++) { + assertTrue(resultSet.next()); + } + assertFalse(resultSet.next()); + } + } - } finally { - if (regularStatement != null) { + // select tab1.c1, tab2.c from table(?) as a, table(?) as b + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT a.c1, b.c from table(?) as a, table(?) as b")) { + preparedStatement.setString(1, ORDERS_JDBC); + preparedStatement.setString(2, "testTableBind"); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); + + assertEquals(2, resultSetMetaData.getColumnCount()); + // assert we have 73 rows + for (int i = 0; i < 73; i++) { + assertTrue(resultSet.next()); + } + assertFalse(resultSet.next()); + } + } + } finally { regularStatement.execute("DROP TABLE testTableBind"); } - closeSQLObjects(resultSet, preparedStatement, connection); } } @Test public void testBindInWithClause() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - // create a test table - regularStatement = connection.createStatement(); - regularStatement.execute( - "create or replace table testBind2(a int, b string, c double, " - + "d date, e timestamp, f time, g date)"); + try (Connection connection = getConnection(); + Statement regularStatement = connection.createStatement()) { + try { + // create a test table + regularStatement.execute( + "create or replace table testBind2(a int, b string, c double, " + + "d date, e timestamp, f time, g date)"); - // bind in where clause - preparedStatement = - connection.prepareStatement( - "WITH V AS (SELECT * FROM testBind2 WHERE a = ?) " + "SELECT count(*) FROM V"); + // bind in where clause + try (PreparedStatement preparedStatement = + connection.prepareStatement( + "WITH V AS (SELECT * FROM testBind2 WHERE a = ?) " + "SELECT count(*) FROM V")) { - preparedStatement.setInt(1, 100); - resultSet = preparedStatement.executeQuery(); - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + preparedStatement.setInt(1, 100); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - // assert column count - assertEquals(1, resultSetMetaData.getColumnCount()); + // assert column count + assertEquals(1, resultSetMetaData.getColumnCount()); - // assert we get 1 rows - assertTrue(resultSet.next()); - preparedStatement.close(); - } finally { - if (regularStatement != null) { + // assert we get 1 rows + assertTrue(resultSet.next()); + } + } + } finally { regularStatement.execute("DROP TABLE testBind2"); - regularStatement.close(); } - - closeSQLObjects(resultSet, preparedStatement, connection); } } @Test public void testBindTimestampNTZ() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - // create a test table - regularStatement = connection.createStatement(); - regularStatement.executeUpdate( - "create or replace table testBindTimestampNTZ(a timestamp_ntz)"); - - regularStatement.execute("alter session set client_timestamp_type_mapping='timestamp_ntz'"); - // bind in where clause - preparedStatement = connection.prepareStatement("insert into testBindTimestampNTZ values(?)"); + try (Connection connection = getConnection(); + Statement regularStatement = connection.createStatement()) { + try { + // create a test table + regularStatement.executeUpdate( + "create or replace table testBindTimestampNTZ(a timestamp_ntz)"); - Timestamp ts = buildTimestamp(2014, 7, 26, 3, 52, 0, 0); - preparedStatement.setTimestamp(1, ts); + regularStatement.execute("alter session set client_timestamp_type_mapping='timestamp_ntz'"); - int updateCount = preparedStatement.executeUpdate(); + // bind in where clause + try (PreparedStatement preparedStatement = + connection.prepareStatement("insert into testBindTimestampNTZ values(?)")) { - // update count should be 1 - assertEquals("update count", 1, updateCount); + Timestamp ts = buildTimestamp(2014, 7, 26, 3, 52, 0, 0); + preparedStatement.setTimestamp(1, ts); - // test the inserted rows - resultSet = regularStatement.executeQuery("select * from testBindTimestampNTZ"); + int updateCount = preparedStatement.executeUpdate(); - // assert we get 1 rows - assertTrue(resultSet.next()); - assertEquals("timestamp", "Tue, 26 Aug 2014 03:52:00 Z", resultSet.getString(1)); + // update count should be 1 + assertEquals("update count", 1, updateCount); - regularStatement.executeUpdate("truncate table testBindTimestampNTZ"); + // test the inserted rows + try (ResultSet resultSet = + regularStatement.executeQuery("select * from testBindTimestampNTZ")) { - preparedStatement.setTimestamp( - 1, ts, Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"))); + // assert we get 1 rows + assertTrue(resultSet.next()); + assertEquals("timestamp", "Tue, 26 Aug 2014 03:52:00 Z", resultSet.getString(1)); - updateCount = preparedStatement.executeUpdate(); + regularStatement.executeUpdate("truncate table testBindTimestampNTZ"); - // update count should be 1 - assertEquals("update count", 1, updateCount); + preparedStatement.setTimestamp( + 1, ts, Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"))); - // test the inserted rows - resultSet = regularStatement.executeQuery("select * from testBindTimestampNTZ"); + updateCount = preparedStatement.executeUpdate(); - // assert we get 1 rows - assertTrue(resultSet.next()); + // update count should be 1 + assertEquals("update count", 1, updateCount); + } + // test the inserted rows + try (ResultSet resultSet = + regularStatement.executeQuery("select * from testBindTimestampNTZ")) { - preparedStatement.close(); - } finally { - if (regularStatement != null) { + // assert we get 1 rows + assertTrue(resultSet.next()); + } + } + } finally { regularStatement.execute("DROP TABLE testBindTimestampNTZ"); - regularStatement.close(); } - - closeSQLObjects(resultSet, preparedStatement, connection); } } @Test public void testNullBind() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - - try { - connection = getConnection(); - regularStatement = connection.createStatement(); - regularStatement.execute("create or replace table testNullBind(a double)"); - - // array bind with nulls - preparedStatement = connection.prepareStatement("insert into testNullBind (a) values(?)"); + try (Connection connection = getConnection(); + Statement regularStatement = connection.createStatement()) { + try { + regularStatement.execute("create or replace table testNullBind(a double)"); - preparedStatement.setDouble(1, 1.2); - preparedStatement.addBatch(); + // array bind with nulls + try (PreparedStatement preparedStatement = + connection.prepareStatement("insert into testNullBind (a) values(?)")) { + preparedStatement.setDouble(1, 1.2); + preparedStatement.addBatch(); - preparedStatement.setObject(1, null); - preparedStatement.addBatch(); + preparedStatement.setObject(1, null); + preparedStatement.addBatch(); - int[] updateCounts = preparedStatement.executeBatch(); + int[] updateCounts = preparedStatement.executeBatch(); - // GS optimizes this into one insert execution - assertEquals("Number of update counts", 2, updateCounts.length); + // GS optimizes this into one insert execution + assertEquals("Number of update counts", 2, updateCounts.length); - // update count should be 1 - assertEquals("update count", 1, updateCounts[0]); - assertEquals("update count", 1, updateCounts[1]); + // update count should be 1 + assertEquals("update count", 1, updateCounts[0]); + assertEquals("update count", 1, updateCounts[1]); - preparedStatement.clearBatch(); + preparedStatement.clearBatch(); - preparedStatement.setObject(1, null); - preparedStatement.addBatch(); + preparedStatement.setObject(1, null); + preparedStatement.addBatch(); - preparedStatement.setDouble(1, 1.2); - preparedStatement.addBatch(); + preparedStatement.setDouble(1, 1.2); + preparedStatement.addBatch(); - updateCounts = preparedStatement.executeBatch(); + updateCounts = preparedStatement.executeBatch(); - // GS optimizes this into one insert execution - assertEquals("Number of update counts", 2, updateCounts.length); + // GS optimizes this into one insert execution + assertEquals("Number of update counts", 2, updateCounts.length); - // update count should be 1 - assertEquals("update count", 1, updateCounts[0]); - assertEquals("update count", 1, updateCounts[1]); + // update count should be 1 + assertEquals("update count", 1, updateCounts[0]); + assertEquals("update count", 1, updateCounts[1]); - preparedStatement.clearBatch(); + preparedStatement.clearBatch(); - preparedStatement.setObject(1, null); - preparedStatement.addBatch(); + preparedStatement.setObject(1, null); + preparedStatement.addBatch(); - updateCounts = preparedStatement.executeBatch(); + updateCounts = preparedStatement.executeBatch(); - // GS optimizes this into one insert execution - assertEquals("Number of update counts", 1, updateCounts.length); + // GS optimizes this into one insert execution + assertEquals("Number of update counts", 1, updateCounts.length); - // update count should be 1 - assertEquals("update count", 1, updateCounts[0]); + // update count should be 1 + assertEquals("update count", 1, updateCounts[0]); - preparedStatement.clearBatch(); + preparedStatement.clearBatch(); - // this test causes query count in GS not to be decremented because - // the exception is thrown before registerQC. Discuss with Johnston - // to resolve the issue before enabling the test. - try { - preparedStatement.setObject(1, "Null", Types.DOUBLE); - preparedStatement.addBatch(); - preparedStatement.executeBatch(); - fail("must fail in executeBatch()"); - } catch (SnowflakeSQLException ex) { - assertEquals(2086, ex.getErrorCode()); - } + // this test causes query count in GS not to be decremented because + // the exception is thrown before registerQC. Discuss with Johnston + // to resolve the issue before enabling the test. + try { + preparedStatement.setObject(1, "Null", Types.DOUBLE); + preparedStatement.addBatch(); + preparedStatement.executeBatch(); + fail("must fail in executeBatch()"); + } catch (SnowflakeSQLException ex) { + assertEquals(2086, ex.getErrorCode()); + } - preparedStatement.clearBatch(); + preparedStatement.clearBatch(); - try { - preparedStatement.setString(1, "hello"); - preparedStatement.addBatch(); + try { + preparedStatement.setString(1, "hello"); + preparedStatement.addBatch(); - preparedStatement.setDouble(1, 1.2); - preparedStatement.addBatch(); - fail("must fail"); - } catch (SnowflakeSQLException ex) { - assertEquals( - (int) ErrorCode.ARRAY_BIND_MIXED_TYPES_NOT_SUPPORTED.getMessageCode(), - ex.getErrorCode()); - } - } finally { - if (regularStatement != null) { + preparedStatement.setDouble(1, 1.2); + preparedStatement.addBatch(); + fail("must fail"); + } catch (SnowflakeSQLException ex) { + assertEquals( + (int) ErrorCode.ARRAY_BIND_MIXED_TYPES_NOT_SUPPORTED.getMessageCode(), + ex.getErrorCode()); + } + } + } finally { regularStatement.execute("DROP TABLE testNullBind"); - regularStatement.close(); } - - closeSQLObjects(preparedStatement, connection); } } @Test public void testSnow12603() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); + ResultSetMetaData resultSetMetaData = null; + try (Connection connection = getConnection()) { + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT ?, ?, ?, ?, ?, ?")) { - preparedStatement = connection.prepareStatement("SELECT ?, ?, ?, ?, ?, ?"); + java.sql.Date sqlDate = java.sql.Date.valueOf("2014-08-26"); - java.sql.Date sqlDate = java.sql.Date.valueOf("2014-08-26"); + Timestamp ts = buildTimestamp(2014, 7, 26, 3, 52, 0, 0); - Timestamp ts = buildTimestamp(2014, 7, 26, 3, 52, 0, 0); + preparedStatement.setObject(1, 1); + preparedStatement.setObject(2, "hello"); + preparedStatement.setObject(3, new BigDecimal("1.3")); + preparedStatement.setObject(4, Float.valueOf("1.3")); + preparedStatement.setObject(5, sqlDate); + preparedStatement.setObject(6, ts); + try (ResultSet resultSet = preparedStatement.executeQuery()) { - preparedStatement.setObject(1, 1); - preparedStatement.setObject(2, "hello"); - preparedStatement.setObject(3, new BigDecimal("1.3")); - preparedStatement.setObject(4, Float.valueOf("1.3")); - preparedStatement.setObject(5, sqlDate); - preparedStatement.setObject(6, ts); - resultSet = preparedStatement.executeQuery(); + resultSetMetaData = resultSet.getMetaData(); - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + // assert column count + assertEquals(6, resultSetMetaData.getColumnCount()); + assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); + assertEquals(Types.DECIMAL, resultSetMetaData.getColumnType(3)); + assertEquals(Types.DOUBLE, resultSetMetaData.getColumnType(4)); + assertEquals(Types.DATE, resultSetMetaData.getColumnType(5)); + assertEquals(Types.TIMESTAMP, resultSetMetaData.getColumnType(6)); + + // assert we get 1 rows + assertTrue(resultSet.next()); - // assert column count - assertEquals(6, resultSetMetaData.getColumnCount()); - assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); - assertEquals(Types.DECIMAL, resultSetMetaData.getColumnType(3)); - assertEquals(Types.DOUBLE, resultSetMetaData.getColumnType(4)); - assertEquals(Types.DATE, resultSetMetaData.getColumnType(5)); - assertEquals(Types.TIMESTAMP, resultSetMetaData.getColumnType(6)); + assertEquals("integer", 1, resultSet.getInt(1)); + assertEquals("string", "hello", resultSet.getString(2)); + assertEquals("decimal", new BigDecimal("1.3"), resultSet.getBigDecimal(3)); + assertEquals("double", 1.3, resultSet.getDouble(4), 0); + assertEquals("date", "2014-08-26", resultSet.getString(5)); + assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(6)); + + preparedStatement.setObject(1, 1, Types.INTEGER); + preparedStatement.setObject(2, "hello", Types.VARCHAR); + preparedStatement.setObject(3, new BigDecimal("1.3"), Types.DECIMAL); + preparedStatement.setObject(4, Float.valueOf("1.3"), Types.DOUBLE); + preparedStatement.setObject(5, sqlDate, Types.DATE); + preparedStatement.setObject(6, ts, Types.TIMESTAMP); + } + try (ResultSet resultSet = preparedStatement.executeQuery()) { - // assert we get 1 rows - assertTrue(resultSet.next()); + resultSetMetaData = resultSet.getMetaData(); - assertEquals("integer", 1, resultSet.getInt(1)); - assertEquals("string", "hello", resultSet.getString(2)); - assertEquals("decimal", new BigDecimal("1.3"), resultSet.getBigDecimal(3)); - assertEquals("double", 1.3, resultSet.getDouble(4), 0); - assertEquals("date", "2014-08-26", resultSet.getString(5)); - assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(6)); - - preparedStatement.setObject(1, 1, Types.INTEGER); - preparedStatement.setObject(2, "hello", Types.VARCHAR); - preparedStatement.setObject(3, new BigDecimal("1.3"), Types.DECIMAL); - preparedStatement.setObject(4, Float.valueOf("1.3"), Types.DOUBLE); - preparedStatement.setObject(5, sqlDate, Types.DATE); - preparedStatement.setObject(6, ts, Types.TIMESTAMP); - - resultSet = preparedStatement.executeQuery(); - - resultSetMetaData = resultSet.getMetaData(); - - // assert column count - assertEquals(6, resultSetMetaData.getColumnCount()); - assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); - assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); - assertEquals(Types.DECIMAL, resultSetMetaData.getColumnType(3)); - assertEquals(Types.DOUBLE, resultSetMetaData.getColumnType(4)); - assertEquals(Types.DATE, resultSetMetaData.getColumnType(5)); - assertEquals(Types.TIMESTAMP, resultSetMetaData.getColumnType(6)); - - // assert we get 1 rows - assertTrue(resultSet.next()); + // assert column count + assertEquals(6, resultSetMetaData.getColumnCount()); + assertEquals(Types.BIGINT, resultSetMetaData.getColumnType(1)); + assertEquals(Types.VARCHAR, resultSetMetaData.getColumnType(2)); + assertEquals(Types.DECIMAL, resultSetMetaData.getColumnType(3)); + assertEquals(Types.DOUBLE, resultSetMetaData.getColumnType(4)); + assertEquals(Types.DATE, resultSetMetaData.getColumnType(5)); + assertEquals(Types.TIMESTAMP, resultSetMetaData.getColumnType(6)); + + // assert we get 1 rows + assertTrue(resultSet.next()); - assertEquals("integer", 1, resultSet.getInt(1)); - assertEquals("string", "hello", resultSet.getString(2)); - assertEquals("decimal", new BigDecimal("1.3"), resultSet.getBigDecimal(3)); - assertEquals("double", 1.3, resultSet.getDouble(4), 0); - assertEquals("date", "2014-08-26", resultSet.getString(5)); - assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(6)); - } finally { - closeSQLObjects(resultSet, preparedStatement, connection); + assertEquals("integer", 1, resultSet.getInt(1)); + assertEquals("string", "hello", resultSet.getString(2)); + assertEquals("decimal", new BigDecimal("1.3"), resultSet.getBigDecimal(3)); + assertEquals("double", 1.3, resultSet.getDouble(4), 0); + assertEquals("date", "2014-08-26", resultSet.getString(5)); + assertEquals("timestamp", "Mon, 25 Aug 2014 20:52:00 -0700", resultSet.getString(6)); + } + } } } /** SNOW-6290: timestamp value is shifted by local timezone */ @Test public void testSnow6290() throws Throwable { - Connection connection = null; - Statement statement = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - - // create test table - statement.execute("CREATE OR REPLACE TABLE testSnow6290(ts timestamp)"); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + // create test table + statement.execute("CREATE OR REPLACE TABLE testSnow6290(ts timestamp)"); - PreparedStatement preparedStatement = - connection.prepareStatement("INSERT INTO testSnow6290(ts) values(?)"); + PreparedStatement preparedStatement = + connection.prepareStatement("INSERT INTO testSnow6290(ts) values(?)"); - Timestamp ts = new Timestamp(System.currentTimeMillis()); + Timestamp ts = new Timestamp(System.currentTimeMillis()); - preparedStatement.setTimestamp(1, ts); - preparedStatement.executeUpdate(); + preparedStatement.setTimestamp(1, ts); + preparedStatement.executeUpdate(); - ResultSet res = statement.executeQuery("select ts from testSnow6290"); + ResultSet res = statement.executeQuery("select ts from testSnow6290"); - assertTrue("expect a row", res.next()); + assertTrue("expect a row", res.next()); - Timestamp tsFromDB = res.getTimestamp(1); + Timestamp tsFromDB = res.getTimestamp(1); - assertEquals("timestamp mismatch", ts.getTime(), tsFromDB.getTime()); - } finally { - if (statement != null) { + assertEquals("timestamp mismatch", ts.getTime(), tsFromDB.getTime()); + } finally { statement.execute("DROP TABLE if exists testSnow6290"); - statement.close(); } - closeSQLObjects(statement, connection); } } /** SNOW-6986: null sql shouldn't be allowed */ @Test public void testInvalidSQL() throws Throwable { - Connection connection = null; - Statement statement = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { // execute DDLs statement.executeQuery(null); - statement.close(); fail("expected exception, but no exception"); } catch (SnowflakeSQLException ex) { assertEquals((int) ErrorCode.INVALID_SQL.getMessageCode(), ex.getErrorCode()); - } finally { - closeSQLObjects(statement, connection); } } @Test public void testGetObject() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; ResultSetMetaData resultSetMetaData; - try { - connection = getConnection(); - - preparedStatement = connection.prepareStatement("SELECT ?"); - - // bind integer - preparedStatement.setInt(1, 1); - resultSet = preparedStatement.executeQuery(); - - resultSetMetaData = resultSet.getMetaData(); - - assertEquals( - "column class name=BigDecimal", - Long.class.getName(), - resultSetMetaData.getColumnClassName(1)); - - // assert we get 1 rows - assertTrue(resultSet.next()); - - assertTrue("integer", resultSet.getObject(1) instanceof Long); - - preparedStatement.setString(1, "hello"); - resultSet = preparedStatement.executeQuery(); + try (Connection connection = getConnection()) { + try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT ?")) { + // bind integer + preparedStatement.setInt(1, 1); + try (ResultSet resultSet = preparedStatement.executeQuery()) { - resultSetMetaData = resultSet.getMetaData(); + resultSetMetaData = resultSet.getMetaData(); - assertEquals( - "column class name=String", - String.class.getName(), - resultSetMetaData.getColumnClassName(1)); + assertEquals( + "column class name=BigDecimal", + Long.class.getName(), + resultSetMetaData.getColumnClassName(1)); - // assert we get 1 rows - assertTrue(resultSet.next()); + // assert we get 1 rows + assertTrue(resultSet.next()); - assertTrue("string", resultSet.getObject(1) instanceof String); + assertTrue("integer", resultSet.getObject(1) instanceof Long); + } + preparedStatement.setString(1, "hello"); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - preparedStatement.setDouble(1, 1.2); - resultSet = preparedStatement.executeQuery(); + assertEquals( + "column class name=String", + String.class.getName(), + resultSetMetaData.getColumnClassName(1)); - resultSetMetaData = resultSet.getMetaData(); + // assert we get 1 rows + assertTrue(resultSet.next()); - assertEquals( - "column class name=Double", - Double.class.getName(), - resultSetMetaData.getColumnClassName(1)); + assertTrue("string", resultSet.getObject(1) instanceof String); + } - // assert we get 1 rows - assertTrue(resultSet.next()); + preparedStatement.setDouble(1, 1.2); + try (ResultSet resultSet = preparedStatement.executeQuery()) { - assertTrue("double", resultSet.getObject(1) instanceof Double); + resultSetMetaData = resultSet.getMetaData(); - preparedStatement.setTimestamp(1, new Timestamp(0)); - resultSet = preparedStatement.executeQuery(); + assertEquals( + "column class name=Double", + Double.class.getName(), + resultSetMetaData.getColumnClassName(1)); - resultSetMetaData = resultSet.getMetaData(); + // assert we get 1 rows + assertTrue(resultSet.next()); - assertEquals( - "column class name=Timestamp", - Timestamp.class.getName(), - resultSetMetaData.getColumnClassName(1)); + assertTrue("double", resultSet.getObject(1) instanceof Double); + } - // assert we get 1 rows - assertTrue(resultSet.next()); + preparedStatement.setTimestamp(1, new Timestamp(0)); + try (ResultSet resultSet = preparedStatement.executeQuery()) { - assertTrue("timestamp", resultSet.getObject(1) instanceof Timestamp); + resultSetMetaData = resultSet.getMetaData(); - preparedStatement.setDate(1, new java.sql.Date(0)); - resultSet = preparedStatement.executeQuery(); + assertEquals( + "column class name=Timestamp", + Timestamp.class.getName(), + resultSetMetaData.getColumnClassName(1)); - resultSetMetaData = resultSet.getMetaData(); + // assert we get 1 rows + assertTrue(resultSet.next()); - assertEquals( - "column class name=Date", - java.sql.Date.class.getName(), - resultSetMetaData.getColumnClassName(1)); + assertTrue("timestamp", resultSet.getObject(1) instanceof Timestamp); + } - // assert we get 1 rows - assertTrue(resultSet.next()); + preparedStatement.setDate(1, new java.sql.Date(0)); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); - assertTrue("date", resultSet.getObject(1) instanceof java.sql.Date); + assertEquals( + "column class name=Date", + java.sql.Date.class.getName(), + resultSetMetaData.getColumnClassName(1)); - preparedStatement.close(); + // assert we get 1 rows + assertTrue(resultSet.next()); - } finally { - closeSQLObjects(resultSet, preparedStatement, connection); + assertTrue("date", resultSet.getObject(1) instanceof java.sql.Date); + } + } } } @Test public void testGetDoubleForNull() throws Throwable { - Connection connection = null; - Statement stmt = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - stmt = connection.createStatement(); - resultSet = stmt.executeQuery("select cast(null as int) as null_int"); + try (Connection connection = getConnection(); + Statement stmt = connection.createStatement(); + ResultSet resultSet = stmt.executeQuery("select cast(null as int) as null_int")) { assertTrue(resultSet.next()); assertEquals("0 for null", 0, resultSet.getDouble(1), 0.0001); - } finally { - closeSQLObjects(resultSet, stmt, connection); } } // SNOW-27438 @Test public void testGetDoubleForNaN() throws Throwable { - Connection connection = null; - Statement stmt = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - stmt = connection.createStatement(); - resultSet = stmt.executeQuery("select 'nan'::float"); + try (Connection connection = getConnection(); + Statement stmt = connection.createStatement(); + ResultSet resultSet = stmt.executeQuery("select 'nan'::float")) { assertTrue(resultSet.next()); assertThat("NaN for NaN", resultSet.getDouble(1), equalTo(Double.NaN)); - } finally { - closeSQLObjects(resultSet, stmt, connection); } } @Test public void testPutViaExecuteQuery() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - - // load file test - // create a unique data file name by using current timestamp in millis + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { try { + // load file test + // create a unique data file name by using current timestamp in millis // test external table load statement.execute("CREATE OR REPLACE TABLE testPutViaExecuteQuery(a number)"); // put files - resultSet = + try (ResultSet resultSet = statement.executeQuery( "PUT file://" + getFullPathFileInResource(TEST_DATA_FILE) - + " @%testPutViaExecuteQuery/orders parallel=10"); - - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + + " @%testPutViaExecuteQuery/orders parallel=10")) { - // assert column count - assertTrue(resultSetMetaData.getColumnCount() > 0); + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - // assert we get 1 rows - for (int i = 0; i < 1; i++) { - assertTrue(resultSet.next()); + // assert column count + assertTrue(resultSetMetaData.getColumnCount() > 0); + // assert we get 1 rows + for (int i = 0; i < 1; i++) { + assertTrue(resultSet.next()); + } } } finally { - statement.execute("DROP TABLE IF EXISTS testPutViaExecuteQuery"); - statement.close(); + connection.createStatement().execute("DROP TABLE IF EXISTS testPutViaExecuteQuery"); } - } finally { - closeSQLObjects(resultSet, statement, connection); } } @Ignore("takes 7 min. enable this for long running tests") @Test public void testSnow16332() throws Throwable { - Connection conn = null; - Connection connWithNwError = null; - Statement stmt = null; - Statement stmtWithNwError = null; - - try { - // use v1 query request API and inject 200ms socket timeout for first - // http request to simulate network failure - conn = getConnection(); - stmt = conn.createStatement(); - - // create a table - stmt.execute("CREATE OR REPLACE TABLE SNOW16332 (i int)"); - - // make sure QC is JIT optimized. Change the GS JVM args to include - // -Xcomp or -XX:CompileThreshold = < a number smaller than the - // stmtCounter - - int stmtCounter = 2000; - while (stmtCounter > 0) { - // insert into it this should start a transaction. - stmt.executeUpdate("INSERT INTO SNOW16332 VALUES (" + stmtCounter + ")"); - --stmtCounter; - } + // use v1 query request API and inject 200ms socket timeout for first + // http request to simulate network failure + try (Connection conn = getConnection(); + Statement stmt = conn.createStatement()) { + try { + // create a table + stmt.execute("CREATE OR REPLACE TABLE SNOW16332 (i int)"); + + // make sure QC is JIT optimized. Change the GS JVM args to include + // -Xcomp or -XX:CompileThreshold = < a number smaller than the + // stmtCounter + + int stmtCounter = 2000; + while (stmtCounter > 0) { + // insert into it this should start a transaction. + stmt.executeUpdate("INSERT INTO SNOW16332 VALUES (" + stmtCounter + ")"); + --stmtCounter; + } - connWithNwError = getConnection(500); // inject socket timeout in ms - stmtWithNwError = connWithNwError.createStatement(); + try (Connection connWithNwError = getConnection(500)) { // inject socket timeout in ms + try (Statement stmtWithNwError = connWithNwError.createStatement()) { - // execute dml - stmtWithNwError.executeUpdate( - "INSERT INTO SNOW16332 " + "SELECT seq8() " + "FROM table(generator(timeLimit => 1))"); + // execute dml + stmtWithNwError.executeUpdate( + "INSERT INTO SNOW16332 " + + "SELECT seq8() " + + "FROM table(generator(timeLimit => 1))"); - // and execute another dml - stmtWithNwError.executeUpdate( - "INSERT INTO SNOW16332 " + "SELECT seq8() " + "FROM table(generator(timeLimit => 1))"); - } finally { - if (stmt != null) { + // and execute another dml + stmtWithNwError.executeUpdate( + "INSERT INTO SNOW16332 " + + "SELECT seq8() " + + "FROM table(generator(timeLimit => 1))"); + } + } + } finally { stmt.executeQuery("DROP TABLE SNOW16332"); } - closeSQLObjects(stmt, conn); - closeSQLObjects(stmtWithNwError, connWithNwError); } } @Test public void testV1Query() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - // use v1 query request API and inject 200ms socket timeout for first - // http request to simulate network failure - connection = getConnection(200); // inject socket timeout = 200ms - - statement = connection.createStatement(); + ResultSetMetaData resultSetMetaData = null; + // use v1 query request API and inject 200ms socket timeout for first + // http request to simulate network failure + try (Connection connection = getConnection(200); // inject socket timeout = 200m + Statement statement = connection.createStatement()) { // execute query - resultSet = - statement.executeQuery("SELECT count(*) FROM table(generator(rowCount => 100000000))"); - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + try (ResultSet resultSet = + statement.executeQuery("SELECT count(*) FROM table(generator(rowCount => 100000000))")) { + resultSetMetaData = resultSet.getMetaData(); - // assert column count - assertEquals(1, resultSetMetaData.getColumnCount()); + // assert column count + assertEquals(1, resultSetMetaData.getColumnCount()); - // assert we get 1 row - for (int i = 0; i < 1; i++) { - assertTrue(resultSet.next()); - assertTrue(resultSet.getInt(1) > 0); + // assert we get 1 row + for (int i = 0; i < 1; i++) { + assertTrue(resultSet.next()); + assertTrue(resultSet.getInt(1) > 0); + } } // Test parsing for timestamp with timezone value that has new encoding // where timezone index follows timestamp value - resultSet = statement.executeQuery("SELECT 'Fri, 23 Oct 2015 12:35:38 -0700'::timestamp_tz"); - resultSetMetaData = resultSet.getMetaData(); + try (ResultSet resultSet = + statement.executeQuery("SELECT 'Fri, 23 Oct 2015 12:35:38 -0700'::timestamp_tz")) { + resultSetMetaData = resultSet.getMetaData(); - // assert column count - assertEquals(1, resultSetMetaData.getColumnCount()); + // assert column count + assertEquals(1, resultSetMetaData.getColumnCount()); - // assert we get 1 row - for (int i = 0; i < 1; i++) { - assertTrue(resultSet.next()); - assertEquals("Fri, 23 Oct 2015 12:35:38 -0700", resultSet.getString(1)); + // assert we get 1 row + for (int i = 0; i < 1; i++) { + assertTrue(resultSet.next()); + assertEquals("Fri, 23 Oct 2015 12:35:38 -0700", resultSet.getString(1)); + } } - } finally { - closeSQLObjects(resultSet, statement, connection); } } @Test public void testCancelQuery() throws Throwable { - ResultSet resultSet = null; - - final Connection connection = getConnection(); - - final Statement statement = connection.createStatement(); - - // schedule a cancel in 5 seconds - try { + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + // schedule a cancel in 5 seconds Timer timer = new Timer(); timer.schedule( new TimerTask() { @@ -2572,162 +2329,143 @@ public void run() { 5000); // now run a query for 120 seconds - resultSet = statement.executeQuery("SELECT count(*) FROM TABLE(generator(timeLimit => 120))"); - fail("should be canceled"); - } catch (SQLException ex) { - // assert the sqlstate is what we expect (QUERY CANCELLED) - assertEquals("sqlstate mismatch", SqlState.QUERY_CANCELED, ex.getSQLState()); - } finally { - closeSQLObjects(resultSet, statement, connection); + try (ResultSet resultSet = + statement.executeQuery("SELECT count(*) FROM TABLE(generator(timeLimit => 120))")) { + fail("should be canceled"); + } catch (SQLException ex) { + // assert the sqlstate is what we expect (QUERY CANCELLED) + assertEquals("sqlstate mismatch", SqlState.QUERY_CANCELED, ex.getSQLState()); + } } } /** SNOW-14774: timestamp_ntz value should use client time zone to adjust the epoch time. */ @Test public void testSnow14774() throws Throwable { - Connection connection = null; - Statement statement = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - + Calendar calendar = null; + Timestamp tsInUTC = null; + Timestamp tsInLA = null; + SimpleDateFormat sdf = null; + String tsStrInLA = null; + String tsStrInUTC = null; + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { // 30 minutes past daylight saving change (from 2am to 3am) - ResultSet res = statement.executeQuery("select '2015-03-08 03:30:00'::timestamp_ntz"); - - res.next(); + try (ResultSet res = statement.executeQuery("select '2015-03-08 03:30:00'::timestamp_ntz")) { - // get timestamp in UTC - Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - Timestamp tsInUTC = res.getTimestamp(1, calendar); + res.next(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String tsStrInUTC = sdf.format(tsInUTC); + // get timestamp in UTC + calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + tsInUTC = res.getTimestamp(1, calendar); - // get timestamp in LA timezone - calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); - Timestamp tsInLA = res.getTimestamp(1, calendar); + sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + tsStrInUTC = sdf.format(tsInUTC); - sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); - String tsStrInLA = sdf.format(tsInLA); + // get timestamp in LA timezone + calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); + tsInLA = res.getTimestamp(1, calendar); - // the timestamp in LA and in UTC should be the same - assertEquals("timestamp values not equal", tsStrInUTC, tsStrInLA); + sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); + tsStrInLA = sdf.format(tsInLA); + // the timestamp in LA and in UTC should be the same + assertEquals("timestamp values not equal", tsStrInUTC, tsStrInLA); + } // 30 minutes before daylight saving change - res = statement.executeQuery("select '2015-03-08 01:30:00'::timestamp_ntz"); + try (ResultSet res = statement.executeQuery("select '2015-03-08 01:30:00'::timestamp_ntz")) { - res.next(); + res.next(); - // get timestamp in UTC - calendar.setTimeZone(TimeZone.getTimeZone("UTC")); - tsInUTC = res.getTimestamp(1, calendar); + // get timestamp in UTC + calendar.setTimeZone(TimeZone.getTimeZone("UTC")); + tsInUTC = res.getTimestamp(1, calendar); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - tsStrInUTC = sdf.format(tsInUTC); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + tsStrInUTC = sdf.format(tsInUTC); - // get timestamp in LA timezone - calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); - tsInLA = res.getTimestamp(1, calendar); + // get timestamp in LA timezone + calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); + tsInLA = res.getTimestamp(1, calendar); - sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); - tsStrInLA = sdf.format(tsInLA); + sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); + tsStrInLA = sdf.format(tsInLA); - // the timestamp in LA and in UTC should be the same - assertEquals("timestamp values not equal", tsStrInUTC, tsStrInLA); - } finally { - closeSQLObjects(null, statement, connection); + // the timestamp in LA and in UTC should be the same + assertEquals("timestamp values not equal", tsStrInUTC, tsStrInLA); + } } } /** SNOW-19172: getMoreResults should return false after executeQuery */ @Test public void testSnow19172() throws SQLException { - Connection connection = null; - Statement statement = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { statement.executeQuery("select 1"); assertTrue(!statement.getMoreResults()); - - } finally { - closeSQLObjects(statement, connection); } } @Test public void testSnow19819() throws Throwable { - Connection connection; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - ResultSet resultSet = null; - connection = getConnection(); - try { - regularStatement = connection.createStatement(); - regularStatement.execute( - "create or replace table testSnow19819(\n" - + "s string,\n" - + "v variant,\n" - + "t timestamp_ltz)\n"); - - preparedStatement = - connection.prepareStatement( - "insert into testSnow19819 (s, v, t)\n" + "select ?, parse_json(?), to_timestamp(?)"); - - preparedStatement.setString(1, "foo"); - preparedStatement.setString(2, "{ }"); - preparedStatement.setString(3, "2016-05-12 12:15:00"); - preparedStatement.addBatch(); - - preparedStatement.setString(1, "foo2"); - preparedStatement.setString(2, "{ \"a\": 1 }"); - preparedStatement.setString(3, "2016-05-12 12:16:00"); - preparedStatement.addBatch(); - - preparedStatement.executeBatch(); - - resultSet = - connection.createStatement().executeQuery("SELECT s, v, t FROM testSnow19819 ORDER BY 1"); - assertThat("next result", resultSet.next()); - assertThat("String", resultSet.getString(1), equalTo("foo")); - assertThat("Variant", resultSet.getString(2), equalTo("{}")); - assertThat("next result", resultSet.next()); - assertThat("String", resultSet.getString(1), equalTo("foo2")); - assertThat("Variant", resultSet.getString(2), equalTo("{\n \"a\": 1\n}")); - assertThat("no more result", !resultSet.next()); - } finally { - if (regularStatement != null) { - regularStatement.execute("DROP TABLE testSnow19819"); + try (Connection connection = getConnection()) { + try (Statement regularStatement = connection.createStatement()) { + try { + regularStatement.execute( + "create or replace table testSnow19819(\n" + + "s string,\n" + + "v variant,\n" + + "t timestamp_ltz)\n"); + + try (PreparedStatement preparedStatement = + connection.prepareStatement( + "insert into testSnow19819 (s, v, t)\n" + + "select ?, parse_json(?), to_timestamp(?)")) { + + preparedStatement.setString(1, "foo"); + preparedStatement.setString(2, "{ }"); + preparedStatement.setString(3, "2016-05-12 12:15:00"); + preparedStatement.addBatch(); + + preparedStatement.setString(1, "foo2"); + preparedStatement.setString(2, "{ \"a\": 1 }"); + preparedStatement.setString(3, "2016-05-12 12:16:00"); + preparedStatement.addBatch(); + + preparedStatement.executeBatch(); + + try (ResultSet resultSet = + connection + .createStatement() + .executeQuery("SELECT s, v, t FROM testSnow19819 ORDER BY 1")) { + assertThat("next result", resultSet.next()); + assertThat("String", resultSet.getString(1), equalTo("foo")); + assertThat("Variant", resultSet.getString(2), equalTo("{}")); + assertThat("next result", resultSet.next()); + assertThat("String", resultSet.getString(1), equalTo("foo2")); + assertThat("Variant", resultSet.getString(2), equalTo("{\n \"a\": 1\n}")); + assertThat("no more result", !resultSet.next()); + } + } + } finally { + regularStatement.execute("DROP TABLE testSnow19819"); + } } - - closeSQLObjects(resultSet, preparedStatement, connection); } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnTestaccount.class) public void testClientInfo() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet res = null; - - try { - System.setProperty( - "snowflake.client.info", - "{\"spark.version\":\"3.0.0\", \"spark.snowflakedb.version\":\"2.8.5\", \"spark.app.name\":\"SnowflakeSourceSuite\", \"scala.version\":\"2.12.11\", \"java.version\":\"1.8.0_221\", \"snowflakedb.jdbc.version\":\"3.13.2\"}"); - - connection = getConnection(); - - statement = connection.createStatement(); - - res = statement.executeQuery("select current_session_client_info()"); + System.setProperty( + "snowflake.client.info", + "{\"spark.version\":\"3.0.0\", \"spark.snowflakedb.version\":\"2.8.5\", \"spark.app.name\":\"SnowflakeSourceSuite\", \"scala.version\":\"2.12.11\", \"java.version\":\"1.8.0_221\", \"snowflakedb.jdbc.version\":\"3.13.2\"}"); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement(); + ResultSet res = statement.executeQuery("select current_session_client_info()")) { assertTrue("result expected", res.next()); @@ -2746,115 +2484,87 @@ public void testClientInfo() throws Throwable { "SnowflakeSourceSuite", clientInfoJSON.get("spark.app.name").asText()); - } finally { - System.clearProperty("snowflake.client.info"); closeSQLObjects(res, statement, connection); } + System.clearProperty("snowflake.client.info"); } @Test public void testLargeResultSet() throws Throwable { - Connection connection = null; - Statement statement = null; - try { - connection = getConnection(); - - // create statement - statement = connection.createStatement(); - + try (Connection connection = getConnection(); + // create statement + Statement statement = connection.createStatement()) { String sql = "SELECT random()||random(), randstr(1000, random()) FROM table(generator(rowcount =>" + " 10000))"; - ResultSet result = statement.executeQuery(sql); - - int cnt = 0; - while (result.next()) { - ++cnt; + try (ResultSet result = statement.executeQuery(sql)) { + int cnt = 0; + while (result.next()) { + ++cnt; + } + assertEquals(10000, cnt); } - assertEquals(10000, cnt); - } finally { - closeSQLObjects(null, statement, connection); } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testSnow26503() throws Throwable { - Connection connection = null; - Connection snowflakeConnection = null; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - Statement regularStatementSF = null; - ResultSet resultSet = null; ResultSetMetaData resultSetMetaData; + String queryId = null; + try (Connection connection = getConnection(); + // create a test table + Statement regularStatement = connection.createStatement()) { + try { + regularStatement.execute( + "create or replace table testBind2(a int) as select * from values(1),(2),(8),(10)"); + + // test binds in BETWEEN predicate + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT * FROM testBind2 WHERE a between ? and ?")) { + preparedStatement.setInt(1, 3); + preparedStatement.setInt(2, 9); + // test that the query succeeds; used to fail with incident + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSetMetaData = resultSet.getMetaData(); + + // assert column count + assertEquals(1, resultSetMetaData.getColumnCount()); + + // assert we get 1 row + assertTrue(resultSet.next()); + } + } + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT last_query_id()"); + ResultSet resultSet = preparedStatement.executeQuery()) { + resultSet.next(); + queryId = resultSet.getString(1); + } - try { - connection = getConnection(); - - // create a test table - regularStatement = connection.createStatement(); - regularStatement.execute( - "create or replace table testBind2(a int) as select * from values(1),(2),(8),(10)"); - - // test binds in BETWEEN predicate - preparedStatement = - connection.prepareStatement("SELECT * FROM testBind2 WHERE a between ? and ?"); - - preparedStatement.setInt(1, 3); - preparedStatement.setInt(2, 9); - // test that the query succeeds; used to fail with incident - resultSet = preparedStatement.executeQuery(); - resultSetMetaData = resultSet.getMetaData(); - - // assert column count - assertEquals(1, resultSetMetaData.getColumnCount()); - - // assert we get 1 row - assertTrue(resultSet.next()); - - resultSet.close(); - preparedStatement.close(); - preparedStatement = connection.prepareStatement("SELECT last_query_id()"); - resultSet = preparedStatement.executeQuery(); - resultSet.next(); - String queryId = resultSet.getString(1); - - resultSet.close(); - preparedStatement.close(); - - // check that the bind values can be retrieved using system$get_bind_values - snowflakeConnection = getSnowflakeAdminConnection(); - - regularStatementSF = snowflakeConnection.createStatement(); - regularStatementSF.execute("create or replace warehouse wh26503 warehouse_size=xsmall"); - - preparedStatement = - snowflakeConnection.prepareStatement( - "select bv:\"1\":\"value\"::string, bv:\"2\":\"value\"::string from (select" - + " parse_json(system$get_bind_values(?)) bv)"); - preparedStatement.setString(1, queryId); - resultSet = preparedStatement.executeQuery(); - resultSet.next(); - - // check that the bind values are correct - assertEquals(3, resultSet.getInt(1)); - assertEquals(9, resultSet.getInt(2)); - - } finally { - if (regularStatement != null) { + // check that the bind values can be retrieved using system$get_bind_values + try (Connection snowflakeConnection = getSnowflakeAdminConnection()) { + try (Statement regularStatementSF = snowflakeConnection.createStatement()) { + regularStatementSF.execute("create or replace warehouse wh26503 warehouse_size=xsmall"); + + try (PreparedStatement preparedStatement = + snowflakeConnection.prepareStatement( + "select bv:\"1\":\"value\"::string, bv:\"2\":\"value\"::string from (select" + + " parse_json(system$get_bind_values(?)) bv)")) { + preparedStatement.setString(1, queryId); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSet.next(); + + // check that the bind values are correct + assertEquals(3, resultSet.getInt(1)); + assertEquals(9, resultSet.getInt(2)); + } + } + } + snowflakeConnection.createStatement().execute("DROP warehouse wh26503"); + } + } finally { regularStatement.execute("DROP TABLE testBind2"); - regularStatement.close(); - } - - if (regularStatementSF != null) { - regularStatementSF.execute("DROP warehouse wh26503"); - regularStatementSF.close(); - } - - closeSQLObjects(resultSet, preparedStatement, connection); - - if (snowflakeConnection != null) { - snowflakeConnection.close(); } } } @@ -2865,60 +2575,49 @@ public void testSnow26503() throws Throwable { */ @Test public void testSnow28530() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - - try { - connection = getConnection(); - regularStatement = connection.createStatement(); - regularStatement.execute("create or replace table t(a number, b number)"); - - ///////////////////////////////////////// - // bind variables in a view definition + try (Connection connection = getConnection(); + Statement regularStatement = connection.createStatement()) { try { - preparedStatement = - connection.prepareStatement("create or replace view v as select * from t where a=?"); - preparedStatement.setInt(1, 1); - preparedStatement.execute(); - - // we shouldn't reach here - fail("Bind variable in view definition did not cause a user error"); - } catch (SnowflakeSQLException e) { - assertEquals(ERROR_CODE_BIND_VARIABLE_NOT_ALLOWED_IN_VIEW_OR_UDF_DEF, e.getErrorCode()); - } + regularStatement.execute("create or replace table t(a number, b number)"); + + ///////////////////////////////////////// + // bind variables in a view definition + try (PreparedStatement preparedStatement = + connection.prepareStatement("create or replace view v as select * from t where a=?")) { + preparedStatement.setInt(1, 1); + preparedStatement.execute(); + + // we shouldn't reach here + fail("Bind variable in view definition did not cause a user error"); + } catch (SnowflakeSQLException e) { + assertEquals(ERROR_CODE_BIND_VARIABLE_NOT_ALLOWED_IN_VIEW_OR_UDF_DEF, e.getErrorCode()); + } - ///////////////////////////////////////////// - // bind variables in a scalar UDF definition - try { - preparedStatement = + ///////////////////////////////////////////// + // bind variables in a scalar UDF definition + try (PreparedStatement preparedStatement = connection.prepareStatement( - "create or replace function f(n number) returns number as " + "'n + ?'"); - preparedStatement.execute(); - fail("Bind variable in scalar UDF definition did not cause a user " + "error"); - } catch (SnowflakeSQLException e) { - assertEquals(ERROR_CODE_BIND_VARIABLE_NOT_ALLOWED_IN_VIEW_OR_UDF_DEF, e.getErrorCode()); - } + "create or replace function f(n number) returns number as " + "'n + ?'")) { + preparedStatement.execute(); + fail("Bind variable in scalar UDF definition did not cause a user " + "error"); + } catch (SnowflakeSQLException e) { + assertEquals(ERROR_CODE_BIND_VARIABLE_NOT_ALLOWED_IN_VIEW_OR_UDF_DEF, e.getErrorCode()); + } - /////////////////////////////////////////// - // bind variables in a table UDF definition - try { - preparedStatement = + /////////////////////////////////////////// + // bind variables in a table UDF definition + try (PreparedStatement preparedStatement = connection.prepareStatement( "create or replace function tf(n number) returns table(b number) as" - + " 'select b from t where a=?'"); - preparedStatement.execute(); - fail("Bind variable in table UDF definition did not cause a user " + "error"); - } catch (SnowflakeSQLException e) { - assertEquals(ERROR_CODE_BIND_VARIABLE_NOT_ALLOWED_IN_VIEW_OR_UDF_DEF, e.getErrorCode()); - } - } finally { - if (regularStatement != null) { + + " 'select b from t where a=?'")) { + preparedStatement.execute(); + fail("Bind variable in table UDF definition did not cause a user " + "error"); + } catch (SnowflakeSQLException e) { + assertEquals(ERROR_CODE_BIND_VARIABLE_NOT_ALLOWED_IN_VIEW_OR_UDF_DEF, e.getErrorCode()); + } + } finally { regularStatement.execute("drop table t"); - regularStatement.close(); } - - closeSQLObjects(null, preparedStatement, connection); } } @@ -2928,54 +2627,47 @@ public void testSnow28530() throws Throwable { */ @Test public void testSnow31104() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - ResultSet resultSet = null; - - try { - Properties paramProperties = new Properties(); - paramProperties.put("TYPESYSTEM_WIDEN_CONSTANTS_EXACTLY", Boolean.TRUE.toString()); - connection = getConnection(paramProperties); - - regularStatement = connection.createStatement(); + Properties paramProperties = new Properties(); + paramProperties.put("TYPESYSTEM_WIDEN_CONSTANTS_EXACTLY", Boolean.TRUE.toString()); + try (Connection connection = getConnection(paramProperties); + Statement regularStatement = connection.createStatement()) { // Repeat a couple of test cases from snow-31104.sql // We don't need to repeat all of them; we just need to verify // that string bind refs and null bind refs are treated the same as // string and null constants. + try { + regularStatement.execute("create or replace table t(n number)"); - regularStatement.execute("create or replace table t(n number)"); - - regularStatement.executeUpdate( - "insert into t values (1), (90000000000000000000000000000000000000)"); - - preparedStatement = connection.prepareStatement("select n, n > ? from t order by 1"); - preparedStatement.setString(1, "1"); - - // this should not produce a user error - resultSet = preparedStatement.executeQuery(); - resultSet.next(); - assertFalse(resultSet.getBoolean(2)); - resultSet.next(); - assertTrue(resultSet.getBoolean(2)); + regularStatement.executeUpdate( + "insert into t values (1), (90000000000000000000000000000000000000)"); - preparedStatement = - connection.prepareStatement("select n, '1' in (?, '256', n, 10) from t order by 1"); - preparedStatement.setString(1, null); + try (PreparedStatement preparedStatement = + connection.prepareStatement("select n, n > ? from t order by 1")) { + preparedStatement.setString(1, "1"); - resultSet = preparedStatement.executeQuery(); - resultSet.next(); - assertTrue(resultSet.getBoolean(2)); - resultSet.next(); - assertNull(resultSet.getObject(2)); - } finally { - if (regularStatement != null) { + // this should not produce a user error + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSet.next(); + assertFalse(resultSet.getBoolean(2)); + resultSet.next(); + assertTrue(resultSet.getBoolean(2)); + } + } + try (PreparedStatement preparedStatement = + connection.prepareStatement("select n, '1' in (?, '256', n, 10) from t order by 1")) { + preparedStatement.setString(1, null); + + try (ResultSet resultSet = preparedStatement.executeQuery()) { + resultSet.next(); + assertTrue(resultSet.getBoolean(2)); + resultSet.next(); + assertNull(resultSet.getObject(2)); + } + } + } finally { regularStatement.execute("drop table t"); - regularStatement.close(); } - - closeSQLObjects(resultSet, preparedStatement, connection); } } @@ -2983,22 +2675,17 @@ public void testSnow31104() throws Throwable { @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPutGet() throws Throwable { - Connection connection = null; - Statement statement = null; List accounts = Arrays.asList(null, "s3testaccount", "azureaccount", "gcpaccount"); for (int i = 0; i < accounts.size(); i++) { - try { - connection = getConnection(accounts.get(i)); - - statement = connection.createStatement(); - - String sourceFilePath = getFullPathFileInResource(TEST_DATA_FILE); + try (Connection connection = getConnection(accounts.get(i)); + Statement statement = connection.createStatement()) { + try { + String sourceFilePath = getFullPathFileInResource(TEST_DATA_FILE); - File destFolder = tmpFolder.newFolder(); - String destFolderCanonicalPath = destFolder.getCanonicalPath(); - String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; + File destFolder = tmpFolder.newFolder(); + String destFolderCanonicalPath = destFolder.getCanonicalPath(); + String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; - try { statement.execute("alter session set ENABLE_GCP_PUT_EXCEPTION_FOR_OLD_DRIVERS=false"); statement.execute("CREATE OR REPLACE STAGE testPutGet_stage"); @@ -3028,10 +2715,7 @@ public void testPutGet() throws Throwable { assert (original.length() == unzipped.length()); } finally { statement.execute("DROP STAGE IF EXISTS testGetPut_stage"); - statement.close(); } - } finally { - closeSQLObjects(null, statement, connection); } } } @@ -3046,22 +2730,17 @@ public void testPutGet() throws Throwable { @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPutGetToUnencryptedStage() throws Throwable { - Connection connection = null; - Statement statement = null; List accounts = Arrays.asList(null, "s3testaccount", "azureaccount", "gcpaccount"); for (int i = 0; i < accounts.size(); i++) { - try { - connection = getConnection(accounts.get(i)); - - statement = connection.createStatement(); - - String sourceFilePath = getFullPathFileInResource(TEST_DATA_FILE); + try (Connection connection = getConnection(accounts.get(i)); + Statement statement = connection.createStatement()) { + try { + String sourceFilePath = getFullPathFileInResource(TEST_DATA_FILE); - File destFolder = tmpFolder.newFolder(); - String destFolderCanonicalPath = destFolder.getCanonicalPath(); - String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; + File destFolder = tmpFolder.newFolder(); + String destFolderCanonicalPath = destFolder.getCanonicalPath(); + String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; - try { statement.execute("alter session set ENABLE_UNENCRYPTED_INTERNAL_STAGES=true"); statement.execute("alter session set ENABLE_GCP_PUT_EXCEPTION_FOR_OLD_DRIVERS=false"); statement.execute( @@ -3095,10 +2774,7 @@ public void testPutGetToUnencryptedStage() throws Throwable { assert (original.length() == unzipped.length()); } finally { statement.execute("DROP STAGE IF EXISTS testPutGet_unencstage"); - statement.close(); } - } finally { - closeSQLObjects(null, statement, connection); } } } @@ -3114,39 +2790,33 @@ public void testNotClosedSession() throws Throwable { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testToTimestampNullBind() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - - try { - connection = getConnection(); - - preparedStatement = - connection.prepareStatement( - "select 3 where to_timestamp_ltz(?, 3) = '1970-01-01 00:00:12.345" - + " +000'::timestamp_ltz"); - + try (Connection connection = getConnection(); + PreparedStatement preparedStatement = + connection.prepareStatement( + "select 3 where to_timestamp_ltz(?, 3) = '1970-01-01 00:00:12.345" + + " +000'::timestamp_ltz")) { // First test, normal usage. preparedStatement.setInt(1, 12345); - ResultSet resultSet = preparedStatement.executeQuery(); - ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); - // Assert column count. - assertEquals(1, resultSetMetaData.getColumnCount()); - // Assert this returned a 3. - assertTrue(resultSet.next()); - assertEquals(3, resultSet.getInt(1)); - assertFalse(resultSet.next()); - - // Second test, input is null. - preparedStatement.setNull(1, Types.INTEGER); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + // Assert column count. + assertEquals(1, resultSetMetaData.getColumnCount()); + // Assert this returned a 3. + assertTrue(resultSet.next()); + assertEquals(3, resultSet.getInt(1)); + assertFalse(resultSet.next()); - resultSet = preparedStatement.executeQuery(); - // Assert no rows returned. - assertFalse(resultSet.next()); - } finally { - closeSQLObjects(preparedStatement, connection); + // Second test, input is null. + preparedStatement.setNull(1, Types.INTEGER); + } + try (ResultSet resultSet = preparedStatement.executeQuery()) { + // Assert no rows returned. + assertFalse(resultSet.next()); + } } + // NOTE: Don't add new tests here. Instead, add it to other appropriate test class or create a + // new + // one. This class is too large to have more tests. } - // NOTE: Don't add new tests here. Instead, add it to other appropriate test class or create a new - // one. This class is too large to have more tests. } diff --git a/src/test/java/net/snowflake/client/jdbc/SnowflakeDriverLatestIT.java b/src/test/java/net/snowflake/client/jdbc/SnowflakeDriverLatestIT.java index e76e5c60e..a6a9ea193 100644 --- a/src/test/java/net/snowflake/client/jdbc/SnowflakeDriverLatestIT.java +++ b/src/test/java/net/snowflake/client/jdbc/SnowflakeDriverLatestIT.java @@ -106,40 +106,37 @@ public void testStaticVersionMatchesManifest() { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnTestaccount.class) public void testClientInfoConnectionProperty() throws Throwable { - Connection connection = null; - Statement statement = null; - ResultSet res = null; - - try { - Properties props = new Properties(); - props.put( - "snowflakeClientInfo", - "{\"spark.version\":\"3.0.0\", \"spark.snowflakedb.version\":\"2.8.5\"," - + " \"spark.app.name\":\"SnowflakeSourceSuite\", \"scala.version\":\"2.12.11\"," - + " \"java.version\":\"1.8.0_221\", \"snowflakedb.jdbc.version\":\"3.13.2\"}"); - connection = getConnection(DONT_INJECT_SOCKET_TIMEOUT, props, false, false); - statement = connection.createStatement(); - res = statement.executeQuery("select current_session_client_info()"); + String clientInfoJSONStr = null; + JsonNode clientInfoJSON = null; + Properties props = new Properties(); + props.put( + "snowflakeClientInfo", + "{\"spark.version\":\"3.0.0\", \"spark.snowflakedb.version\":\"2.8.5\"," + + " \"spark.app.name\":\"SnowflakeSourceSuite\", \"scala.version\":\"2.12.11\"," + + " \"java.version\":\"1.8.0_221\", \"snowflakedb.jdbc.version\":\"3.13.2\"}"); + try (Connection connection = getConnection(DONT_INJECT_SOCKET_TIMEOUT, props, false, false); + Statement statement = connection.createStatement(); + ResultSet res = statement.executeQuery("select current_session_client_info()")) { assertTrue(res.next()); - String clientInfoJSONStr = res.getString(1); - JsonNode clientInfoJSON = mapper.readTree(clientInfoJSONStr); + clientInfoJSONStr = res.getString(1); + clientInfoJSON = mapper.readTree(clientInfoJSONStr); // assert that spart version and spark app are found assertEquals("spark version mismatch", "3.0.0", clientInfoJSON.get("spark.version").asText()); assertEquals( "spark app mismatch", "SnowflakeSourceSuite", clientInfoJSON.get("spark.app.name").asText()); - connection.close(); - - // Test that when session property is set, connection parameter overrides it - System.setProperty( - "snowflake.client.info", - "{\"spark.version\":\"fake\", \"spark.snowflakedb.version\":\"fake\"," - + " \"spark.app.name\":\"fake\", \"scala.version\":\"fake\"," - + " \"java.version\":\"fake\", \"snowflakedb.jdbc.version\":\"fake\"}"); - connection = getConnection(DONT_INJECT_SOCKET_TIMEOUT, props, false, false); - statement = connection.createStatement(); - res = statement.executeQuery("select current_session_client_info()"); + } + + // Test that when session property is set, connection parameter overrides it + System.setProperty( + "snowflake.client.info", + "{\"spark.version\":\"fake\", \"spark.snowflakedb.version\":\"fake\"," + + " \"spark.app.name\":\"fake\", \"scala.version\":\"fake\"," + + " \"java.version\":\"fake\", \"snowflakedb.jdbc.version\":\"fake\"}"); + try (Connection connection = getConnection(DONT_INJECT_SOCKET_TIMEOUT, props, false, false); + Statement statement = connection.createStatement(); + ResultSet res = statement.executeQuery("select current_session_client_info()")) { assertTrue(res.next()); clientInfoJSONStr = res.getString(1); clientInfoJSON = mapper.readTree(clientInfoJSONStr); @@ -149,21 +146,20 @@ public void testClientInfoConnectionProperty() throws Throwable { "spark app mismatch", "SnowflakeSourceSuite", clientInfoJSON.get("spark.app.name").asText()); - - } finally { - System.clearProperty("snowflake.client.info"); - closeSQLObjects(res, statement, connection); } + System.clearProperty("snowflake.client.info"); } @Test public void testGetSessionID() throws Throwable { - Connection con = getConnection(); - String sessionID = con.unwrap(SnowflakeConnection.class).getSessionID(); - Statement statement = con.createStatement(); - ResultSet rset = statement.executeQuery("select current_session()"); - rset.next(); - assertEquals(sessionID, rset.getString(1)); + try (Connection con = getConnection()) { + String sessionID = con.unwrap(SnowflakeConnection.class).getSessionID(); + try (Statement statement = con.createStatement(); + ResultSet rset = statement.executeQuery("select current_session()")) { + rset.next(); + assertEquals(sessionID, rset.getString(1)); + } + } } @Test @@ -172,32 +168,33 @@ public void testPutThreshold() throws SQLException { try (Connection connection = getConnection()) { // assert that threshold equals default 200 from server side SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); - Statement statement = connection.createStatement(); - SFStatement sfStatement = statement.unwrap(SnowflakeStatementV1.class).getSfStatement(); - statement.execute("CREATE OR REPLACE STAGE PUTTHRESHOLDSTAGE"); - String command = - "PUT file://" + getFullPathFileInResource(TEST_DATA_FILE) + " @PUTTHRESHOLDSTAGE"; - SnowflakeFileTransferAgent agent = - new SnowflakeFileTransferAgent(command, sfSession, sfStatement); - assertEquals(200 * 1024 * 1024, agent.getBigFileThreshold()); - // assert that setting threshold via put statement directly sets the big file threshold - // appropriately - String commandWithPut = command + " threshold=314572800"; - agent = new SnowflakeFileTransferAgent(commandWithPut, sfSession, sfStatement); - assertEquals(314572800, agent.getBigFileThreshold()); - // assert that after put statement, threshold goes back to previous session threshold - agent = new SnowflakeFileTransferAgent(command, sfSession, sfStatement); - assertEquals(200 * 1024 * 1024, agent.getBigFileThreshold()); - // Attempt to set threshold to an invalid value such as a negative number - String commandWithInvalidThreshold = command + " threshold=-1"; - try { - agent = new SnowflakeFileTransferAgent(commandWithInvalidThreshold, sfSession, sfStatement); - } - // assert invalid value causes exception to be thrown of type INVALID_PARAMETER_VALUE - catch (SQLException e) { - assertEquals(SqlState.INVALID_PARAMETER_VALUE, e.getSQLState()); + try (Statement statement = connection.createStatement()) { + SFStatement sfStatement = statement.unwrap(SnowflakeStatementV1.class).getSfStatement(); + statement.execute("CREATE OR REPLACE STAGE PUTTHRESHOLDSTAGE"); + String command = + "PUT file://" + getFullPathFileInResource(TEST_DATA_FILE) + " @PUTTHRESHOLDSTAGE"; + SnowflakeFileTransferAgent agent = + new SnowflakeFileTransferAgent(command, sfSession, sfStatement); + assertEquals(200 * 1024 * 1024, agent.getBigFileThreshold()); + // assert that setting threshold via put statement directly sets the big file threshold + // appropriately + String commandWithPut = command + " threshold=314572800"; + agent = new SnowflakeFileTransferAgent(commandWithPut, sfSession, sfStatement); + assertEquals(314572800, agent.getBigFileThreshold()); + // assert that after put statement, threshold goes back to previous session threshold + agent = new SnowflakeFileTransferAgent(command, sfSession, sfStatement); + assertEquals(200 * 1024 * 1024, agent.getBigFileThreshold()); + // Attempt to set threshold to an invalid value such as a negative number + String commandWithInvalidThreshold = command + " threshold=-1"; + try { + agent = + new SnowflakeFileTransferAgent(commandWithInvalidThreshold, sfSession, sfStatement); + } + // assert invalid value causes exception to be thrown of type INVALID_PARAMETER_VALUE + catch (SQLException e) { + assertEquals(SqlState.INVALID_PARAMETER_VALUE, e.getSQLState()); + } } - statement.close(); } catch (SQLException ex) { throw ex; } @@ -207,99 +204,12 @@ public void testPutThreshold() throws SQLException { @Test @Ignore public void testGCPFileTransferMetadataWithOneFile() throws Throwable { - Connection connection = null; File destFolder = tmpFolder.newFolder(); String destFolderCanonicalPath = destFolder.getCanonicalPath(); - try { - connection = getConnection("gcpaccount"); - Statement statement = connection.createStatement(); - - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE " + testStageName); - - SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); - - // Test put file with internal compression - String putCommand1 = "put file:///dummy/path/file1.gz @" + testStageName; - SnowflakeFileTransferAgent sfAgent1 = - new SnowflakeFileTransferAgent(putCommand1, sfSession, new SFStatement(sfSession)); - List metadatas1 = sfAgent1.getFileTransferMetadatas(); - - String srcPath1 = getFullPathFileInResource(TEST_DATA_FILE); - for (SnowflakeFileTransferMetadata oneMetadata : metadatas1) { - InputStream inputStream = new FileInputStream(srcPath1); - - assert (oneMetadata.isForOneFile()); - SnowflakeFileTransferAgent.uploadWithoutConnection( - SnowflakeFileTransferConfig.Builder.newInstance() - .setSnowflakeFileTransferMetadata(oneMetadata) - .setUploadStream(inputStream) - .setRequireCompress(true) - .setNetworkTimeoutInMilli(0) - .setOcspMode(OCSPMode.FAIL_OPEN) - .build()); - } - - // Test Put file with external compression - String putCommand2 = "put file:///dummy/path/file2.gz @" + testStageName; - SnowflakeFileTransferAgent sfAgent2 = - new SnowflakeFileTransferAgent(putCommand2, sfSession, new SFStatement(sfSession)); - List metadatas2 = sfAgent2.getFileTransferMetadatas(); - - String srcPath2 = getFullPathFileInResource(TEST_DATA_FILE_2); - for (SnowflakeFileTransferMetadata oneMetadata : metadatas2) { - String gzfilePath = destFolderCanonicalPath + "/tmp_compress.gz"; - Process p = - Runtime.getRuntime() - .exec("cp -fr " + srcPath2 + " " + destFolderCanonicalPath + "/tmp_compress"); - p.waitFor(); - p = Runtime.getRuntime().exec("gzip " + destFolderCanonicalPath + "/tmp_compress"); - p.waitFor(); - InputStream gzInputStream = new FileInputStream(gzfilePath); - assert (oneMetadata.isForOneFile()); - SnowflakeFileTransferAgent.uploadWithoutConnection( - SnowflakeFileTransferConfig.Builder.newInstance() - .setSnowflakeFileTransferMetadata(oneMetadata) - .setUploadStream(gzInputStream) - .setRequireCompress(false) - .setNetworkTimeoutInMilli(0) - .setOcspMode(OCSPMode.FAIL_OPEN) - .build()); - } - - // Download two files and verify their content. - assertTrue( - "Failed to get files", - statement.execute( - "GET @" + testStageName + " 'file://" + destFolderCanonicalPath + "/' parallel=8")); - - // Make sure that the downloaded files are EQUAL, - // they should be gzip compressed - assert (isFileContentEqual(srcPath1, false, destFolderCanonicalPath + "/file1.gz", true)); - assert (isFileContentEqual(srcPath2, false, destFolderCanonicalPath + "/file2.gz", true)); - } finally { - if (connection != null) { - connection.createStatement().execute("DROP STAGE if exists " + testStageName); - connection.close(); - } - } - } - - /** Test API for Kafka connector for FileTransferMetadata */ - @Test - @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) - public void testAzureS3FileTransferMetadataWithOneFile() throws Throwable { - Connection connection = null; - File destFolder = tmpFolder.newFolder(); - String destFolderCanonicalPath = destFolder.getCanonicalPath(); - - List supportedAccounts = Arrays.asList("s3testaccount", "azureaccount"); - for (String accountName : supportedAccounts) { + try (Connection connection = getConnection("gcpaccount"); + Statement statement = connection.createStatement()) { try { - connection = getConnection(accountName); - Statement statement = connection.createStatement(); - // create a stage to put the file in statement.execute("CREATE OR REPLACE STAGE " + testStageName); @@ -315,6 +225,7 @@ public void testAzureS3FileTransferMetadataWithOneFile() throws Throwable { for (SnowflakeFileTransferMetadata oneMetadata : metadatas1) { InputStream inputStream = new FileInputStream(srcPath1); + assert (oneMetadata.isForOneFile()); SnowflakeFileTransferAgent.uploadWithoutConnection( SnowflakeFileTransferConfig.Builder.newInstance() .setSnowflakeFileTransferMetadata(oneMetadata) @@ -322,8 +233,6 @@ public void testAzureS3FileTransferMetadataWithOneFile() throws Throwable { .setRequireCompress(true) .setNetworkTimeoutInMilli(0) .setOcspMode(OCSPMode.FAIL_OPEN) - .setSFSession(sfSession) - .setCommand(putCommand1) .build()); } @@ -344,7 +253,7 @@ public void testAzureS3FileTransferMetadataWithOneFile() throws Throwable { p.waitFor(); InputStream gzInputStream = new FileInputStream(gzfilePath); - + assert (oneMetadata.isForOneFile()); SnowflakeFileTransferAgent.uploadWithoutConnection( SnowflakeFileTransferConfig.Builder.newInstance() .setSnowflakeFileTransferMetadata(oneMetadata) @@ -352,8 +261,6 @@ public void testAzureS3FileTransferMetadataWithOneFile() throws Throwable { .setRequireCompress(false) .setNetworkTimeoutInMilli(0) .setOcspMode(OCSPMode.FAIL_OPEN) - .setSFSession(sfSession) - .setCommand(putCommand2) .build()); } @@ -368,9 +275,96 @@ public void testAzureS3FileTransferMetadataWithOneFile() throws Throwable { assert (isFileContentEqual(srcPath1, false, destFolderCanonicalPath + "/file1.gz", true)); assert (isFileContentEqual(srcPath2, false, destFolderCanonicalPath + "/file2.gz", true)); } finally { - if (connection != null) { - connection.createStatement().execute("DROP STAGE if exists " + testStageName); - connection.close(); + statement.execute("DROP STAGE if exists " + testStageName); + } + } + } + + /** Test API for Kafka connector for FileTransferMetadata */ + @Test + @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) + public void testAzureS3FileTransferMetadataWithOneFile() throws Throwable { + File destFolder = tmpFolder.newFolder(); + String destFolderCanonicalPath = destFolder.getCanonicalPath(); + + List supportedAccounts = Arrays.asList("s3testaccount", "azureaccount"); + for (String accountName : supportedAccounts) { + try (Connection connection = getConnection(accountName); + Statement statement = connection.createStatement()) { + try { + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE " + testStageName); + + SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); + + // Test put file with internal compression + String putCommand1 = "put file:///dummy/path/file1.gz @" + testStageName; + SnowflakeFileTransferAgent sfAgent1 = + new SnowflakeFileTransferAgent(putCommand1, sfSession, new SFStatement(sfSession)); + List metadatas1 = sfAgent1.getFileTransferMetadatas(); + + String srcPath1 = getFullPathFileInResource(TEST_DATA_FILE); + for (SnowflakeFileTransferMetadata oneMetadata : metadatas1) { + InputStream inputStream = new FileInputStream(srcPath1); + + SnowflakeFileTransferAgent.uploadWithoutConnection( + SnowflakeFileTransferConfig.Builder.newInstance() + .setSnowflakeFileTransferMetadata(oneMetadata) + .setUploadStream(inputStream) + .setRequireCompress(true) + .setNetworkTimeoutInMilli(0) + .setOcspMode(OCSPMode.FAIL_OPEN) + .setSFSession(sfSession) + .setCommand(putCommand1) + .build()); + } + + // Test Put file with external compression + String putCommand2 = "put file:///dummy/path/file2.gz @" + testStageName; + SnowflakeFileTransferAgent sfAgent2 = + new SnowflakeFileTransferAgent(putCommand2, sfSession, new SFStatement(sfSession)); + List metadatas2 = sfAgent2.getFileTransferMetadatas(); + + String srcPath2 = getFullPathFileInResource(TEST_DATA_FILE_2); + for (SnowflakeFileTransferMetadata oneMetadata : metadatas2) { + String gzfilePath = destFolderCanonicalPath + "/tmp_compress.gz"; + Process p = + Runtime.getRuntime() + .exec("cp -fr " + srcPath2 + " " + destFolderCanonicalPath + "/tmp_compress"); + p.waitFor(); + p = Runtime.getRuntime().exec("gzip " + destFolderCanonicalPath + "/tmp_compress"); + p.waitFor(); + + InputStream gzInputStream = new FileInputStream(gzfilePath); + + SnowflakeFileTransferAgent.uploadWithoutConnection( + SnowflakeFileTransferConfig.Builder.newInstance() + .setSnowflakeFileTransferMetadata(oneMetadata) + .setUploadStream(gzInputStream) + .setRequireCompress(false) + .setNetworkTimeoutInMilli(0) + .setOcspMode(OCSPMode.FAIL_OPEN) + .setSFSession(sfSession) + .setCommand(putCommand2) + .build()); + } + + // Download two files and verify their content. + assertTrue( + "Failed to get files", + statement.execute( + "GET @" + + testStageName + + " 'file://" + + destFolderCanonicalPath + + "/' parallel=8")); + + // Make sure that the downloaded files are EQUAL, + // they should be gzip compressed + assert (isFileContentEqual(srcPath1, false, destFolderCanonicalPath + "/file1.gz", true)); + assert (isFileContentEqual(srcPath2, false, destFolderCanonicalPath + "/file2.gz", true)); + } finally { + statement.execute("DROP STAGE if exists " + testStageName); } } } @@ -380,45 +374,42 @@ public void testAzureS3FileTransferMetadataWithOneFile() throws Throwable { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testGCPFileTransferMetadataNegativeOnlySupportPut() throws Throwable { - Connection connection = null; int expectExceptionCount = 1; int actualExceptionCount = -1; - try { - connection = getConnection("gcpaccount"); - Statement statement = connection.createStatement(); + try (Connection connection = getConnection("gcpaccount"); + Statement statement = connection.createStatement()) { + try { + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE " + testStageName); - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE " + testStageName); + // Put one file to the stage + String srcPath = getFullPathFileInResource(TEST_DATA_FILE); + statement.execute("put file://" + srcPath + " @" + testStageName); - // Put one file to the stage - String srcPath = getFullPathFileInResource(TEST_DATA_FILE); - statement.execute("put file://" + srcPath + " @" + testStageName); + SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); - SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); + File destFolder = tmpFolder.newFolder(); + String destFolderCanonicalPath = destFolder.getCanonicalPath(); - File destFolder = tmpFolder.newFolder(); - String destFolderCanonicalPath = destFolder.getCanonicalPath(); + String getCommand = "get @" + testStageName + " file://" + destFolderCanonicalPath; - String getCommand = "get @" + testStageName + " file://" + destFolderCanonicalPath; + // The GET can be executed in normal way. + statement.execute(getCommand); - // The GET can be executed in normal way. - statement.execute(getCommand); + // Start negative test for GET. + SnowflakeFileTransferAgent sfAgent = + new SnowflakeFileTransferAgent(getCommand, sfSession, new SFStatement(sfSession)); - // Start negative test for GET. - SnowflakeFileTransferAgent sfAgent = - new SnowflakeFileTransferAgent(getCommand, sfSession, new SFStatement(sfSession)); + // Below function call should fail. + actualExceptionCount = 0; + sfAgent.getFileTransferMetadatas(); + fail("Above function should raise exception for GET"); - // Below function call should fail. - actualExceptionCount = 0; - sfAgent.getFileTransferMetadatas(); - fail("Above function should raise exception for GET"); - } catch (Exception ex) { - System.out.println("Negative test to hit expected exception: " + ex.getMessage()); - actualExceptionCount++; - } finally { - if (connection != null) { - connection.createStatement().execute("DROP STAGE if exists " + testStageName); - connection.close(); + } catch (Exception ex) { + System.out.println("Negative test to hit expected exception: " + ex.getMessage()); + actualExceptionCount++; + } finally { + statement.execute("DROP STAGE if exists " + testStageName); } } assertEquals(expectExceptionCount, actualExceptionCount); @@ -494,20 +485,17 @@ public void testGetPropertyInfo() throws SQLException { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPutOverwriteFalseNoDigest() throws Throwable { - Connection connection = null; - Statement statement = null; // create 2 files: an original, and one that will overwrite the original File file1 = tmpFolder.newFile("testfile.csv"); - BufferedWriter bw = new BufferedWriter(new FileWriter(file1)); - bw.write("Writing original file content. This should get overwritten."); - bw.close(); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(file1))) { + bw.write("Writing original file content. This should get overwritten."); + } File file2 = tmpFolder2.newFile("testfile.csv"); - bw = new BufferedWriter(new FileWriter(file2)); - bw.write("This is all new! This should be the result of the overwriting."); - bw.close(); - + try (BufferedWriter bw = new BufferedWriter(new FileWriter(file2))) { + bw.write("This is all new! This should be the result of the overwriting."); + } String sourceFilePathOriginal = file1.getCanonicalPath(); String sourceFilePathOverwrite = file2.getCanonicalPath(); @@ -520,50 +508,48 @@ public void testPutOverwriteFalseNoDigest() throws Throwable { List accounts = Arrays.asList(null, "s3testaccount", "azureaccount", "gcpaccount"); for (int i = 0; i < accounts.size(); i++) { - try { - connection = getConnection(accounts.get(i), paramProperties); - - statement = connection.createStatement(); - - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE testing_stage"); - assertTrue( - "Failed to put a file", - statement.execute("PUT file://" + sourceFilePathOriginal + " @testing_stage")); - // check that file exists in stage after PUT - findFile(statement, "ls @testing_stage/"); - - // put another file in same stage with same filename with overwrite = true - assertTrue( - "Failed to put a file", - statement.execute( - "PUT file://" + sourceFilePathOverwrite + " @testing_stage overwrite=false")); - - // check that file exists in stage after PUT - findFile(statement, "ls @testing_stage/"); - - // get file from new stage - assertTrue( - "Failed to get files", - statement.execute( - "GET @testing_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); - - // Make sure that the downloaded file exists; it should be gzip compressed - File downloaded = new File(destFolderCanonicalPathWithSeparator + "testfile.csv.gz"); - assertTrue(downloaded.exists()); - - // unzip the file - Process p = - Runtime.getRuntime() - .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "testfile.csv.gz"); - p.waitFor(); + try (Connection connection = getConnection(accounts.get(i), paramProperties); + Statement statement = connection.createStatement()) { + try { + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE testing_stage"); + assertTrue( + "Failed to put a file", + statement.execute("PUT file://" + sourceFilePathOriginal + " @testing_stage")); + // check that file exists in stage after PUT + findFile(statement, "ls @testing_stage/"); + + // put another file in same stage with same filename with overwrite = true + assertTrue( + "Failed to put a file", + statement.execute( + "PUT file://" + sourceFilePathOverwrite + " @testing_stage overwrite=false")); + + // check that file exists in stage after PUT + findFile(statement, "ls @testing_stage/"); + + // get file from new stage + assertTrue( + "Failed to get files", + statement.execute( + "GET @testing_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); + + // Make sure that the downloaded file exists; it should be gzip compressed + File downloaded = new File(destFolderCanonicalPathWithSeparator + "testfile.csv.gz"); + assertTrue(downloaded.exists()); + + // unzip the file + Process p = + Runtime.getRuntime() + .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "testfile.csv.gz"); + p.waitFor(); - // 2nd file should never be uploaded - File unzipped = new File(destFolderCanonicalPathWithSeparator + "testfile.csv"); - assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, unzipped, null)); - } finally { - statement.execute("DROP TABLE IF EXISTS testLoadToLocalFS"); - statement.close(); + // 2nd file should never be uploaded + File unzipped = new File(destFolderCanonicalPathWithSeparator + "testfile.csv"); + assertTrue(FileUtils.contentEqualsIgnoreEOL(file1, unzipped, null)); + } finally { + statement.execute("DROP TABLE IF EXISTS testLoadToLocalFS"); + } } } } @@ -576,14 +562,12 @@ public void testPutOverwriteFalseNoDigest() throws Throwable { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPutDisable() throws Throwable { - Connection connection = null; - Statement statement = null; // create a file File file = tmpFolder.newFile("testfile99.csv"); - BufferedWriter bw = new BufferedWriter(new FileWriter(file)); - bw.write("This content won't be uploaded as PUT is disabled."); - bw.close(); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { + bw.write("This content won't be uploaded as PUT is disabled."); + } String sourceFilePathOriginal = file.getCanonicalPath(); @@ -592,19 +576,14 @@ public void testPutDisable() throws Throwable { List accounts = Arrays.asList(null, "s3testaccount", "azureaccount", "gcpaccount"); for (int i = 0; i < accounts.size(); i++) { - try { - connection = getConnection(accounts.get(i), paramProperties); - - statement = connection.createStatement(); - + try (Connection connection = getConnection(accounts.get(i), paramProperties); + Statement statement = connection.createStatement()) { statement.execute("PUT file://" + sourceFilePathOriginal + " @testPutGet_disable_stage"); assertTrue("Shouldn't come here", false); } catch (Exception ex) { // Expected assertTrue(ex.getMessage().equalsIgnoreCase("File transfers have been disabled.")); - } finally { - statement.close(); } } } @@ -617,8 +596,6 @@ public void testPutDisable() throws Throwable { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testGetDisable() throws Throwable { - Connection connection = null; - Statement statement = null; // create a folder File destFolder = tmpFolder.newFolder(); @@ -629,10 +606,8 @@ public void testGetDisable() throws Throwable { List accounts = Arrays.asList(null, "s3testaccount", "azureaccount", "gcpaccount"); for (int i = 0; i < accounts.size(); i++) { - try { - connection = getConnection(accounts.get(i), paramProperties); - - statement = connection.createStatement(); + try (Connection connection = getConnection(accounts.get(i), paramProperties); + Statement statement = connection.createStatement()) { statement.execute( "GET @testPutGet_disable_stage 'file://" + destFolderCanonicalPath + "' parallel=8"); @@ -641,8 +616,6 @@ public void testGetDisable() throws Throwable { } catch (Exception ex) { // Expected assertTrue(ex.getMessage().equalsIgnoreCase("File transfers have been disabled.")); - } finally { - statement.close(); } } } @@ -653,161 +626,164 @@ public void testGetDisable() throws Throwable { */ @Test public void testSnow76376() throws Throwable { - Connection connection = null; - PreparedStatement preparedStatement = null; - Statement regularStatement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - regularStatement = connection.createStatement(); - regularStatement.execute( - "create or replace table t(a int) as select * from values" + "(1),(2),(8),(10)"); - - preparedStatement = - connection.prepareStatement("SELECT * FROM t " + "ORDER BY a LIMIT " + "? OFFSET ?"); - - //////////////////////////// - // both NULL - preparedStatement.setNull(1, 4); // int - preparedStatement.setNull(2, 4); // int - - if (preparedStatement.execute()) { - resultSet = preparedStatement.getResultSet(); - resultSet.next(); - assertEquals(1, resultSet.getInt(1)); - resultSet.next(); - assertEquals(2, resultSet.getInt(1)); - resultSet.next(); - assertEquals(8, resultSet.getInt(1)); - resultSet.next(); - assertEquals(10, resultSet.getInt(1)); - } else { - fail("Could not execute preparedStatement with OFFSET and LIMIT set " + "to NULL"); - } - - //////////////////////////// - // both empty string - preparedStatement.setString(1, ""); - preparedStatement.setString(2, ""); - - if (preparedStatement.execute()) { - resultSet = preparedStatement.getResultSet(); - resultSet.next(); - assertEquals(1, resultSet.getInt(1)); - resultSet.next(); - assertEquals(2, resultSet.getInt(1)); - resultSet.next(); - assertEquals(8, resultSet.getInt(1)); - resultSet.next(); - assertEquals(10, resultSet.getInt(1)); - } else { - fail("Could not execute preparedStatement with OFFSET and LIMIT set " + "to empty string"); - } + try (Connection connection = getConnection(); + Statement regularStatement = connection.createStatement()) { + try { + regularStatement.execute( + "create or replace table t(a int) as select * from values" + "(1),(2),(8),(10)"); + + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT * FROM t " + "ORDER BY a LIMIT " + "? OFFSET ?")) { + + //////////////////////////// + // both NULL + preparedStatement.setNull(1, 4); // int + preparedStatement.setNull(2, 4); // int + + if (preparedStatement.execute()) { + try (ResultSet resultSet = preparedStatement.getResultSet()) { + resultSet.next(); + assertEquals(1, resultSet.getInt(1)); + resultSet.next(); + assertEquals(2, resultSet.getInt(1)); + resultSet.next(); + assertEquals(8, resultSet.getInt(1)); + resultSet.next(); + assertEquals(10, resultSet.getInt(1)); + } + } else { + fail("Could not execute preparedStatement with OFFSET and LIMIT set " + "to NULL"); + } - //////////////////////////// - // only LIMIT NULL - preparedStatement.setNull(1, 4); // int - preparedStatement.setInt(2, 2); - - if (preparedStatement.execute()) { - resultSet = preparedStatement.getResultSet(); - resultSet.next(); - assertEquals(8, resultSet.getInt(1)); - resultSet.next(); - assertEquals(10, resultSet.getInt(1)); - } else { - fail("Could not execute preparedStatement with LIMIT set to NULL"); - } + //////////////////////////// + // both empty string + preparedStatement.setString(1, ""); + preparedStatement.setString(2, ""); + + if (preparedStatement.execute()) { + try (ResultSet resultSet = preparedStatement.getResultSet()) { + resultSet.next(); + assertEquals(1, resultSet.getInt(1)); + resultSet.next(); + assertEquals(2, resultSet.getInt(1)); + resultSet.next(); + assertEquals(8, resultSet.getInt(1)); + resultSet.next(); + assertEquals(10, resultSet.getInt(1)); + } + } else { + fail( + "Could not execute preparedStatement with OFFSET and LIMIT set " + + "to empty string"); + } - //////////////////////////// - // only LIMIT empty string - preparedStatement.setString(1, ""); - preparedStatement.setInt(2, 2); - - if (preparedStatement.execute()) { - resultSet = preparedStatement.getResultSet(); - resultSet.next(); - assertEquals(8, resultSet.getInt(1)); - resultSet.next(); - assertEquals(10, resultSet.getInt(1)); - } else { - fail("Could not execute preparedStatement with LIMIT set to empty " + "string"); - } + //////////////////////////// + // only LIMIT NULL + preparedStatement.setNull(1, 4); // int + preparedStatement.setInt(2, 2); + + if (preparedStatement.execute()) { + try (ResultSet resultSet = preparedStatement.getResultSet()) { + resultSet.next(); + assertEquals(8, resultSet.getInt(1)); + resultSet.next(); + assertEquals(10, resultSet.getInt(1)); + } + } else { + fail("Could not execute preparedStatement with LIMIT set to NULL"); + } - //////////////////////////// - // only OFFSET NULL - preparedStatement.setInt(1, 3); // int - preparedStatement.setNull(2, 4); - - if (preparedStatement.execute()) { - resultSet = preparedStatement.getResultSet(); - resultSet.next(); - assertEquals(1, resultSet.getInt(1)); - resultSet.next(); - assertEquals(2, resultSet.getInt(1)); - resultSet.next(); - assertEquals(8, resultSet.getInt(1)); - } else { - fail("Could not execute preparedStatement with OFFSET set to NULL"); - } + //////////////////////////// + // only LIMIT empty string + preparedStatement.setString(1, ""); + preparedStatement.setInt(2, 2); + + if (preparedStatement.execute()) { + try (ResultSet resultSet = preparedStatement.getResultSet()) { + resultSet.next(); + assertEquals(8, resultSet.getInt(1)); + resultSet.next(); + assertEquals(10, resultSet.getInt(1)); + } + } else { + fail("Could not execute preparedStatement with LIMIT set to empty " + "string"); + } - //////////////////////////// - // only OFFSET empty string - preparedStatement.setInt(1, 3); // int - preparedStatement.setNull(2, 4); - - if (preparedStatement.execute()) { - resultSet = preparedStatement.getResultSet(); - resultSet.next(); - assertEquals(1, resultSet.getInt(1)); - resultSet.next(); - assertEquals(2, resultSet.getInt(1)); - resultSet.next(); - assertEquals(8, resultSet.getInt(1)); - } else { - fail("Could not execute preparedStatement with OFFSET set to empty " + "string"); - } + //////////////////////////// + // only OFFSET NULL + preparedStatement.setInt(1, 3); // int + preparedStatement.setNull(2, 4); + + if (preparedStatement.execute()) { + try (ResultSet resultSet = preparedStatement.getResultSet()) { + resultSet.next(); + assertEquals(1, resultSet.getInt(1)); + resultSet.next(); + assertEquals(2, resultSet.getInt(1)); + resultSet.next(); + assertEquals(8, resultSet.getInt(1)); + } + } else { + fail("Could not execute preparedStatement with OFFSET set to NULL"); + } - //////////////////////////// - // OFFSET and LIMIT NULL for constant select query - preparedStatement = - connection.prepareStatement("SELECT 1 FROM t " + "ORDER BY a LIMIT " + "? OFFSET ?"); - preparedStatement.setNull(1, 4); // int - preparedStatement.setNull(2, 4); // int - if (preparedStatement.execute()) { - resultSet = preparedStatement.getResultSet(); - for (int i = 0; i < 4; i++) { - resultSet.next(); - assertEquals(1, resultSet.getInt(1)); + //////////////////////////// + // only OFFSET empty string + preparedStatement.setInt(1, 3); // int + preparedStatement.setNull(2, 4); + + if (preparedStatement.execute()) { + try (ResultSet resultSet = preparedStatement.getResultSet()) { + resultSet.next(); + assertEquals(1, resultSet.getInt(1)); + resultSet.next(); + assertEquals(2, resultSet.getInt(1)); + resultSet.next(); + assertEquals(8, resultSet.getInt(1)); + } + } else { + fail("Could not execute preparedStatement with OFFSET set to empty " + "string"); + } } - } else { - fail("Could not execute constant preparedStatement with OFFSET and " + "LIMIT set to NULL"); - } + //////////////////////////// + // OFFSET and LIMIT NULL for constant select query + try (PreparedStatement preparedStatement = + connection.prepareStatement("SELECT 1 FROM t " + "ORDER BY a LIMIT " + "? OFFSET ?")) { + preparedStatement.setNull(1, 4); // int + preparedStatement.setNull(2, 4); // int + if (preparedStatement.execute()) { + try (ResultSet resultSet = preparedStatement.getResultSet()) { + for (int i = 0; i < 4; i++) { + resultSet.next(); + assertEquals(1, resultSet.getInt(1)); + } + } + } else { + fail( + "Could not execute constant preparedStatement with OFFSET and " + + "LIMIT set to NULL"); + } - //////////////////////////// - // OFFSET and LIMIT empty string for constant select query - preparedStatement.setString(1, ""); // int - preparedStatement.setString(2, ""); // int - if (preparedStatement.execute()) { - resultSet = preparedStatement.getResultSet(); - for (int i = 0; i < 4; i++) { - resultSet.next(); - assertEquals(1, resultSet.getInt(1)); + //////////////////////////// + // OFFSET and LIMIT empty string for constant select query + preparedStatement.setString(1, ""); // int + preparedStatement.setString(2, ""); // int + if (preparedStatement.execute()) { + try (ResultSet resultSet = preparedStatement.getResultSet()) { + for (int i = 0; i < 4; i++) { + resultSet.next(); + assertEquals(1, resultSet.getInt(1)); + } + } + } else { + fail( + "Could not execute constant preparedStatement with OFFSET and " + + "LIMIT set to empty string"); + } } - } else { - fail( - "Could not execute constant preparedStatement with OFFSET and " - + "LIMIT set to empty string"); - } - - } finally { - if (regularStatement != null) { + } finally { regularStatement.execute("drop table t"); - regularStatement.close(); } - - closeSQLObjects(resultSet, preparedStatement, connection); } } @@ -820,46 +796,37 @@ public void testSnow76376() throws Throwable { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testGeoOutputTypes() throws Throwable { - Connection connection = null; - Statement regularStatement = null; - - try { - Properties paramProperties = new Properties(); - paramProperties.put("ENABLE_USER_DEFINED_TYPE_EXPANSION", true); - paramProperties.put("ENABLE_GEOGRAPHY_TYPE", true); - - connection = getConnection(paramProperties); + Properties paramProperties = new Properties(); - regularStatement = connection.createStatement(); + paramProperties.put("ENABLE_USER_DEFINED_TYPE_EXPANSION", true); + paramProperties.put("ENABLE_GEOGRAPHY_TYPE", true); - regularStatement.execute("create or replace table t_geo(geo geography);"); + try (Connection connection = getConnection(paramProperties); + Statement regularStatement = connection.createStatement()) { + try { + regularStatement.execute("create or replace table t_geo(geo geography);"); - regularStatement.execute("insert into t_geo values ('POINT(0 0)'), ('LINESTRING(1 1, 2 2)')"); + regularStatement.execute( + "insert into t_geo values ('POINT(0 0)'), ('LINESTRING(1 1, 2 2)')"); - testGeoOutputTypeSingle( - regularStatement, false, "geoJson", "OBJECT", "java.lang.String", Types.VARCHAR); + testGeoOutputTypeSingle( + regularStatement, false, "geoJson", "OBJECT", "java.lang.String", Types.VARCHAR); - testGeoOutputTypeSingle( - regularStatement, true, "geoJson", "GEOGRAPHY", "java.lang.String", Types.VARCHAR); + testGeoOutputTypeSingle( + regularStatement, true, "geoJson", "GEOGRAPHY", "java.lang.String", Types.VARCHAR); - testGeoOutputTypeSingle( - regularStatement, false, "wkt", "VARCHAR", "java.lang.String", Types.VARCHAR); + testGeoOutputTypeSingle( + regularStatement, false, "wkt", "VARCHAR", "java.lang.String", Types.VARCHAR); - testGeoOutputTypeSingle( - regularStatement, true, "wkt", "GEOGRAPHY", "java.lang.String", Types.VARCHAR); + testGeoOutputTypeSingle( + regularStatement, true, "wkt", "GEOGRAPHY", "java.lang.String", Types.VARCHAR); - testGeoOutputTypeSingle(regularStatement, false, "wkb", "BINARY", "[B", Types.BINARY); + testGeoOutputTypeSingle(regularStatement, false, "wkb", "BINARY", "[B", Types.BINARY); - testGeoOutputTypeSingle(regularStatement, true, "wkb", "GEOGRAPHY", "[B", Types.BINARY); - } finally { - if (regularStatement != null) { + testGeoOutputTypeSingle(regularStatement, true, "wkb", "GEOGRAPHY", "[B", Types.BINARY); + } finally { regularStatement.execute("drop table t_geo"); - regularStatement.close(); - } - - if (connection != null) { - connection.close(); } } } @@ -872,16 +839,13 @@ private void testGeoOutputTypeSingle( String expectedColumnClassName, int expectedColumnType) throws Throwable { - ResultSet resultSet = null; - try { - regularStatement.execute("alter session set GEOGRAPHY_OUTPUT_FORMAT='" + outputFormat + "'"); - - regularStatement.execute( - "alter session set ENABLE_UDT_EXTERNAL_TYPE_NAMES=" + enableExternalTypeNames); + regularStatement.execute("alter session set GEOGRAPHY_OUTPUT_FORMAT='" + outputFormat + "'"); - resultSet = regularStatement.executeQuery("select * from t_geo"); + regularStatement.execute( + "alter session set ENABLE_UDT_EXTERNAL_TYPE_NAMES=" + enableExternalTypeNames); + try (ResultSet resultSet = regularStatement.executeQuery("select * from t_geo")) { ResultSetMetaData metadata = resultSet.getMetaData(); assertEquals(1, metadata.getColumnCount()); @@ -890,51 +854,34 @@ private void testGeoOutputTypeSingle( assertEquals(expectedColumnTypeName, metadata.getColumnTypeName(1)); assertEquals(expectedColumnClassName, metadata.getColumnClassName(1)); assertEquals(expectedColumnType, metadata.getColumnType(1)); - - } finally { - if (resultSet != null) { - resultSet.close(); - } } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testGeoMetadata() throws Throwable { - Connection connection = null; - Statement regularStatement = null; - - try { - Properties paramProperties = new Properties(); - - paramProperties.put("ENABLE_FIX_182763", true); - - connection = getConnection(paramProperties); - - regularStatement = connection.createStatement(); + Properties paramProperties = new Properties(); - regularStatement.execute("create or replace table t_geo(geo geography);"); + paramProperties.put("ENABLE_FIX_182763", true); - testGeoMetadataSingle(connection, regularStatement, "geoJson", Types.VARCHAR); + try (Connection connection = getConnection(paramProperties); + Statement regularStatement = connection.createStatement()) { + try { + regularStatement.execute("create or replace table t_geo(geo geography);"); - testGeoMetadataSingle(connection, regularStatement, "geoJson", Types.VARCHAR); + testGeoMetadataSingle(connection, regularStatement, "geoJson", Types.VARCHAR); - testGeoMetadataSingle(connection, regularStatement, "wkt", Types.VARCHAR); + testGeoMetadataSingle(connection, regularStatement, "geoJson", Types.VARCHAR); - testGeoMetadataSingle(connection, regularStatement, "wkt", Types.VARCHAR); + testGeoMetadataSingle(connection, regularStatement, "wkt", Types.VARCHAR); - testGeoMetadataSingle(connection, regularStatement, "wkb", Types.BINARY); + testGeoMetadataSingle(connection, regularStatement, "wkt", Types.VARCHAR); - testGeoMetadataSingle(connection, regularStatement, "wkb", Types.BINARY); + testGeoMetadataSingle(connection, regularStatement, "wkb", Types.BINARY); - } finally { - if (regularStatement != null) { + testGeoMetadataSingle(connection, regularStatement, "wkb", Types.BINARY); + } finally { regularStatement.execute("drop table t_geo"); - regularStatement.close(); - } - - if (connection != null) { - connection.close(); } } } @@ -945,13 +892,11 @@ private void testGeoMetadataSingle( String outputFormat, int expectedColumnType) throws Throwable { - ResultSet resultSet = null; - try { - regularStatement.execute("alter session set GEOGRAPHY_OUTPUT_FORMAT='" + outputFormat + "'"); + regularStatement.execute("alter session set GEOGRAPHY_OUTPUT_FORMAT='" + outputFormat + "'"); - DatabaseMetaData md = connection.getMetaData(); - resultSet = md.getColumns(null, null, "T_GEO", null); + DatabaseMetaData md = connection.getMetaData(); + try (ResultSet resultSet = md.getColumns(null, null, "T_GEO", null)) { ResultSetMetaData metadata = resultSet.getMetaData(); assertEquals(24, metadata.getColumnCount()); @@ -960,48 +905,32 @@ private void testGeoMetadataSingle( assertEquals(expectedColumnType, resultSet.getInt(5)); assertEquals("GEOGRAPHY", resultSet.getString(6)); - } finally { - if (resultSet != null) { - resultSet.close(); - } } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testGeometryOutputTypes() throws Throwable { - Connection connection = null; - Statement regularStatement = null; - - try { - Properties paramProperties = new Properties(); - - paramProperties.put("ENABLE_USER_DEFINED_TYPE_EXPANSION", true); - paramProperties.put("ENABLE_GEOMETRY_TYPE", true); - - connection = getConnection(paramProperties); - - regularStatement = connection.createStatement(); + Properties paramProperties = new Properties(); - regularStatement.execute("create or replace table t_geo2(geo geometry);"); + paramProperties.put("ENABLE_USER_DEFINED_TYPE_EXPANSION", true); + paramProperties.put("ENABLE_GEOMETRY_TYPE", true); - regularStatement.execute( - "insert into t_geo2 values ('POINT(0 0)'), ('LINESTRING(1 1, 2 2)')"); + try (Connection connection = getConnection(paramProperties); + Statement regularStatement = connection.createStatement()) { + try { + regularStatement.execute("create or replace table t_geo2(geo geometry);"); - testGeometryOutputTypeSingle( - regularStatement, true, "geoJson", "GEOMETRY", "java.lang.String", Types.VARCHAR); + regularStatement.execute( + "insert into t_geo2 values ('POINT(0 0)'), ('LINESTRING(1 1, 2 2)')"); - testGeometryOutputTypeSingle( - regularStatement, true, "wkt", "GEOMETRY", "java.lang.String", Types.VARCHAR); + testGeometryOutputTypeSingle( + regularStatement, true, "geoJson", "GEOMETRY", "java.lang.String", Types.VARCHAR); - } finally { - if (regularStatement != null) { + testGeometryOutputTypeSingle( + regularStatement, true, "wkt", "GEOMETRY", "java.lang.String", Types.VARCHAR); + } finally { regularStatement.execute("drop table t_geo2"); - regularStatement.close(); - } - - if (connection != null) { - connection.close(); } } } @@ -1014,15 +943,13 @@ private void testGeometryOutputTypeSingle( String expectedColumnClassName, int expectedColumnType) throws Throwable { - ResultSet resultSet = null; - try { - regularStatement.execute("alter session set GEOGRAPHY_OUTPUT_FORMAT='" + outputFormat + "'"); + regularStatement.execute("alter session set GEOGRAPHY_OUTPUT_FORMAT='" + outputFormat + "'"); - regularStatement.execute( - "alter session set ENABLE_UDT_EXTERNAL_TYPE_NAMES=" + enableExternalTypeNames); + regularStatement.execute( + "alter session set ENABLE_UDT_EXTERNAL_TYPE_NAMES=" + enableExternalTypeNames); - resultSet = regularStatement.executeQuery("select * from t_geo2"); + try (ResultSet resultSet = regularStatement.executeQuery("select * from t_geo2")) { ResultSetMetaData metadata = resultSet.getMetaData(); @@ -1032,41 +959,25 @@ private void testGeometryOutputTypeSingle( assertEquals(expectedColumnTypeName, metadata.getColumnTypeName(1)); assertEquals(expectedColumnClassName, metadata.getColumnClassName(1)); assertEquals(expectedColumnType, metadata.getColumnType(1)); - - } finally { - if (resultSet != null) { - resultSet.close(); - } } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testGeometryMetadata() throws Throwable { - Connection connection = null; - Statement regularStatement = null; - - try { - Properties paramProperties = new Properties(); - connection = getConnection(paramProperties); - - regularStatement = connection.createStatement(); - - regularStatement.execute("create or replace table t_geo2(geo geometry);"); + Properties paramProperties = new Properties(); - testGeometryMetadataSingle(connection, regularStatement, "geoJson", Types.VARCHAR); + try (Connection connection = getConnection(paramProperties); + Statement regularStatement = connection.createStatement()) { + try { + regularStatement.execute("create or replace table t_geo2(geo geometry);"); - testGeometryMetadataSingle(connection, regularStatement, "wkt", Types.VARCHAR); + testGeometryMetadataSingle(connection, regularStatement, "geoJson", Types.VARCHAR); - } finally { - if (regularStatement != null) { + testGeometryMetadataSingle(connection, regularStatement, "wkt", Types.VARCHAR); + } finally { regularStatement.execute("drop table t_geo2"); - regularStatement.close(); - } - - if (connection != null) { - connection.close(); } } } @@ -1077,13 +988,11 @@ private void testGeometryMetadataSingle( String outputFormat, int expectedColumnType) throws Throwable { - ResultSet resultSet = null; - try { - regularStatement.execute("alter session set GEOGRAPHY_OUTPUT_FORMAT='" + outputFormat + "'"); + regularStatement.execute("alter session set GEOGRAPHY_OUTPUT_FORMAT='" + outputFormat + "'"); - DatabaseMetaData md = connection.getMetaData(); - resultSet = md.getColumns(null, null, "T_GEO2", null); + DatabaseMetaData md = connection.getMetaData(); + try (ResultSet resultSet = md.getColumns(null, null, "T_GEO2", null)) { ResultSetMetaData metadata = resultSet.getMetaData(); assertEquals(24, metadata.getColumnCount()); @@ -1092,10 +1001,6 @@ private void testGeometryMetadataSingle( assertEquals(expectedColumnType, resultSet.getInt(5)); assertEquals("GEOMETRY", resultSet.getString(6)); - } finally { - if (resultSet != null) { - resultSet.close(); - } } } @@ -1183,77 +1088,75 @@ private void putAndGetFile(Statement statement) throws Throwable { public void testPutGetLargeFileGCSDownscopedCredential() throws Throwable { Properties paramProperties = new Properties(); paramProperties.put("GCS_USE_DOWNSCOPED_CREDENTIAL", true); - Connection connection = getConnection("gcpaccount", paramProperties); - Statement statement = connection.createStatement(); - - File destFolder = tmpFolder.newFolder(); - String destFolderCanonicalPath = destFolder.getCanonicalPath(); - String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; - - File largeTempFile = tmpFolder.newFile("largeFile.csv"); - BufferedWriter bw = new BufferedWriter(new FileWriter(largeTempFile)); - bw.write("Creating large test file for GCP PUT/GET test"); - bw.write(System.lineSeparator()); - bw.write("Creating large test file for GCP PUT/GET test"); - bw.write(System.lineSeparator()); - bw.close(); - File largeTempFile2 = tmpFolder.newFile("largeFile2.csv"); + try (Connection connection = getConnection("gcpaccount", paramProperties); + Statement statement = connection.createStatement()) { + try { + File destFolder = tmpFolder.newFolder(); + String destFolderCanonicalPath = destFolder.getCanonicalPath(); + String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; + + File largeTempFile = tmpFolder.newFile("largeFile.csv"); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(largeTempFile))) { + bw.write("Creating large test file for GCP PUT/GET test"); + bw.write(System.lineSeparator()); + bw.write("Creating large test file for GCP PUT/GET test"); + bw.write(System.lineSeparator()); + } + File largeTempFile2 = tmpFolder.newFile("largeFile2.csv"); - String sourceFilePath = largeTempFile.getCanonicalPath(); + String sourceFilePath = largeTempFile.getCanonicalPath(); - try { - // copy info from 1 file to another and continue doubling file size until we reach ~1.5GB, - // which is a large file - for (int i = 0; i < 12; i++) { - copyContentFrom(largeTempFile, largeTempFile2); - copyContentFrom(largeTempFile2, largeTempFile); - } + // copy info from 1 file to another and continue doubling file size until we reach ~1.5GB, + // which is a large file + for (int i = 0; i < 12; i++) { + copyContentFrom(largeTempFile, largeTempFile2); + copyContentFrom(largeTempFile2, largeTempFile); + } - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE largefile_stage"); - assertTrue( - "Failed to put a file", - statement.execute("PUT file://" + sourceFilePath + " @largefile_stage")); + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE largefile_stage"); + assertTrue( + "Failed to put a file", + statement.execute("PUT file://" + sourceFilePath + " @largefile_stage")); - // check that file exists in stage after PUT - findFile(statement, "ls @largefile_stage/"); + // check that file exists in stage after PUT + findFile(statement, "ls @largefile_stage/"); - // create a new table with columns matching CSV file - statement.execute("create or replace table large_table (colA string)"); - // copy rows from file into table - statement.execute("copy into large_table from @largefile_stage/largeFile.csv.gz"); - // copy back from table into different stage - statement.execute("create or replace stage extra_stage"); - statement.execute("copy into @extra_stage/bigFile.csv.gz from large_table single=true"); + // create a new table with columns matching CSV file + statement.execute("create or replace table large_table (colA string)"); + // copy rows from file into table + statement.execute("copy into large_table from @largefile_stage/largeFile.csv.gz"); + // copy back from table into different stage + statement.execute("create or replace stage extra_stage"); + statement.execute("copy into @extra_stage/bigFile.csv.gz from large_table single=true"); - // get file from new stage - assertTrue( - "Failed to get files", - statement.execute( - "GET @extra_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); + // get file from new stage + assertTrue( + "Failed to get files", + statement.execute( + "GET @extra_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); - // Make sure that the downloaded file exists; it should be gzip compressed - File downloaded = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); - assert (downloaded.exists()); + // Make sure that the downloaded file exists; it should be gzip compressed + File downloaded = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); + assert (downloaded.exists()); - // unzip the file - Process p = - Runtime.getRuntime() - .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); - p.waitFor(); + // unzip the file + Process p = + Runtime.getRuntime() + .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); + p.waitFor(); - // compare the original file with the file that's been uploaded, copied into a table, copied - // back into a stage, - // downloaded, and unzipped - File unzipped = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv"); - assert (largeTempFile.length() == unzipped.length()); - assert (FileUtils.contentEquals(largeTempFile, unzipped)); - } finally { - statement.execute("DROP STAGE IF EXISTS largefile_stage"); - statement.execute("DROP STAGE IF EXISTS extra_stage"); - statement.execute("DROP TABLE IF EXISTS large_table"); - statement.close(); - connection.close(); + // compare the original file with the file that's been uploaded, copied into a table, copied + // back into a stage, + // downloaded, and unzipped + File unzipped = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv"); + assert (largeTempFile.length() == unzipped.length()); + assert (FileUtils.contentEquals(largeTempFile, unzipped)); + } finally { + statement.execute("DROP STAGE IF EXISTS largefile_stage"); + statement.execute("DROP STAGE IF EXISTS extra_stage"); + statement.execute("DROP TABLE IF EXISTS large_table"); + } } } @@ -1261,77 +1164,75 @@ public void testPutGetLargeFileGCSDownscopedCredential() throws Throwable { @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPutGetLargeFileAzure() throws Throwable { Properties paramProperties = new Properties(); - Connection connection = getConnection("azureaccount", paramProperties); - Statement statement = connection.createStatement(); - - File destFolder = tmpFolder.newFolder(); - String destFolderCanonicalPath = destFolder.getCanonicalPath(); - String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; - - File largeTempFile = tmpFolder.newFile("largeFile.csv"); - BufferedWriter bw = new BufferedWriter(new FileWriter(largeTempFile)); - bw.write("Creating large test file for Azure PUT/GET test"); - bw.write(System.lineSeparator()); - bw.write("Creating large test file for Azure PUT/GET test"); - bw.write(System.lineSeparator()); - bw.close(); - File largeTempFile2 = tmpFolder.newFile("largeFile2.csv"); + try (Connection connection = getConnection("azureaccount", paramProperties); + Statement statement = connection.createStatement()) { + try { + File destFolder = tmpFolder.newFolder(); + String destFolderCanonicalPath = destFolder.getCanonicalPath(); + String destFolderCanonicalPathWithSeparator = destFolderCanonicalPath + File.separator; + + File largeTempFile = tmpFolder.newFile("largeFile.csv"); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(largeTempFile))) { + bw.write("Creating large test file for Azure PUT/GET test"); + bw.write(System.lineSeparator()); + bw.write("Creating large test file for Azure PUT/GET test"); + bw.write(System.lineSeparator()); + } + File largeTempFile2 = tmpFolder.newFile("largeFile2.csv"); - String sourceFilePath = largeTempFile.getCanonicalPath(); + String sourceFilePath = largeTempFile.getCanonicalPath(); - try { - // copy info from 1 file to another and continue doubling file size until we reach ~1.5GB, - // which is a large file - for (int i = 0; i < 12; i++) { - copyContentFrom(largeTempFile, largeTempFile2); - copyContentFrom(largeTempFile2, largeTempFile); - } + // copy info from 1 file to another and continue doubling file size until we reach ~1.5GB, + // which is a large file + for (int i = 0; i < 12; i++) { + copyContentFrom(largeTempFile, largeTempFile2); + copyContentFrom(largeTempFile2, largeTempFile); + } - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE largefile_stage"); - assertTrue( - "Failed to put a file", - statement.execute("PUT file://" + sourceFilePath + " @largefile_stage")); + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE largefile_stage"); + assertTrue( + "Failed to put a file", + statement.execute("PUT file://" + sourceFilePath + " @largefile_stage")); - // check that file exists in stage after PUT - findFile(statement, "ls @largefile_stage/"); + // check that file exists in stage after PUT + findFile(statement, "ls @largefile_stage/"); - // create a new table with columns matching CSV file - statement.execute("create or replace table large_table (colA string)"); - // copy rows from file into table - statement.execute("copy into large_table from @largefile_stage/largeFile.csv.gz"); - // copy back from table into different stage - statement.execute("create or replace stage extra_stage"); - statement.execute("copy into @extra_stage/bigFile.csv.gz from large_table single=true"); + // create a new table with columns matching CSV file + statement.execute("create or replace table large_table (colA string)"); + // copy rows from file into table + statement.execute("copy into large_table from @largefile_stage/largeFile.csv.gz"); + // copy back from table into different stage + statement.execute("create or replace stage extra_stage"); + statement.execute("copy into @extra_stage/bigFile.csv.gz from large_table single=true"); - // get file from new stage - assertTrue( - "Failed to get files", - statement.execute( - "GET @extra_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); + // get file from new stage + assertTrue( + "Failed to get files", + statement.execute( + "GET @extra_stage 'file://" + destFolderCanonicalPath + "' parallel=8")); - // Make sure that the downloaded file exists; it should be gzip compressed - File downloaded = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); - assert (downloaded.exists()); + // Make sure that the downloaded file exists; it should be gzip compressed + File downloaded = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); + assert (downloaded.exists()); - // unzip the file - Process p = - Runtime.getRuntime() - .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); - p.waitFor(); + // unzip the file + Process p = + Runtime.getRuntime() + .exec("gzip -d " + destFolderCanonicalPathWithSeparator + "bigFile.csv.gz"); + p.waitFor(); - // compare the original file with the file that's been uploaded, copied into a table, copied - // back into a stage, - // downloaded, and unzipped - File unzipped = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv"); - assert (largeTempFile.length() == unzipped.length()); - assert (FileUtils.contentEquals(largeTempFile, unzipped)); - } finally { - statement.execute("DROP STAGE IF EXISTS largefile_stage"); - statement.execute("DROP STAGE IF EXISTS extra_stage"); - statement.execute("DROP TABLE IF EXISTS large_table"); - statement.close(); - connection.close(); + // compare the original file with the file that's been uploaded, copied into a table, copied + // back into a stage, + // downloaded, and unzipped + File unzipped = new File(destFolderCanonicalPathWithSeparator + "bigFile.csv"); + assert (largeTempFile.length() == unzipped.length()); + assert (FileUtils.contentEquals(largeTempFile, unzipped)); + } finally { + statement.execute("DROP STAGE IF EXISTS largefile_stage"); + statement.execute("DROP STAGE IF EXISTS extra_stage"); + statement.execute("DROP TABLE IF EXISTS large_table"); + } } } @@ -1345,115 +1246,114 @@ public void testPutGetLargeFileAzure() throws Throwable { private void copyContentFrom(File file1, File file2) throws Exception { FileInputStream inputStream = new FileInputStream(file1); FileOutputStream outputStream = new FileOutputStream(file2); - FileChannel fIn = inputStream.getChannel(); - FileChannel fOut = outputStream.getChannel(); - fOut.transferFrom(fIn, 0, fIn.size()); - fIn.position(0); - fOut.transferFrom(fIn, fIn.size(), fIn.size()); - fOut.close(); - fIn.close(); + try (FileChannel fIn = inputStream.getChannel(); + FileChannel fOut = outputStream.getChannel()) { + fOut.transferFrom(fIn, 0, fIn.size()); + fIn.position(0); + fOut.transferFrom(fIn, fIn.size(), fIn.size()); + } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPutS3RegionalUrl() throws Throwable { - Connection connection = null; File destFolder = tmpFolder.newFolder(); String destFolderCanonicalPath = destFolder.getCanonicalPath(); List supportedAccounts = Arrays.asList("s3testaccount", "azureaccount"); for (String accountName : supportedAccounts) { - try { - connection = getConnection(accountName); - Statement statement = connection.createStatement(); - - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE " + testStageName); - - SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); + try (Connection connection = getConnection(accountName); + Statement statement = connection.createStatement()) { + try { + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE " + testStageName); - // Test put file with internal compression - String putCommand1 = "put file:///dummy/path/file1.gz @" + testStageName; - SnowflakeFileTransferAgent sfAgent1 = - new SnowflakeFileTransferAgent(putCommand1, sfSession, new SFStatement(sfSession)); - List metadatas1 = sfAgent1.getFileTransferMetadatas(); + SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); - String srcPath1 = getFullPathFileInResource(TEST_DATA_FILE); + // Test put file with internal compression + String putCommand1 = "put file:///dummy/path/file1.gz @" + testStageName; + SnowflakeFileTransferAgent sfAgent1 = + new SnowflakeFileTransferAgent(putCommand1, sfSession, new SFStatement(sfSession)); + List metadatas1 = sfAgent1.getFileTransferMetadatas(); - for (SnowflakeFileTransferMetadata oneMetadata : metadatas1) { - InputStream inputStream = new FileInputStream(srcPath1); - SnowflakeFileTransferAgent.uploadWithoutConnection( - SnowflakeFileTransferConfig.Builder.newInstance() - .setSnowflakeFileTransferMetadata(oneMetadata) - .setUploadStream(inputStream) - .setRequireCompress(true) - .setNetworkTimeoutInMilli(0) - .setOcspMode(OCSPMode.FAIL_OPEN) - .setSFSession(sfSession) - .setCommand(putCommand1) - .setUseS3RegionalUrl(false) - .build()); - } + String srcPath1 = getFullPathFileInResource(TEST_DATA_FILE); - for (SnowflakeFileTransferMetadata oneMetadata : metadatas1) { - InputStream inputStream = new FileInputStream(srcPath1); - SnowflakeFileTransferAgent.uploadWithoutConnection( - SnowflakeFileTransferConfig.Builder.newInstance() - .setSnowflakeFileTransferMetadata(oneMetadata) - .setUploadStream(inputStream) - .setRequireCompress(true) - .setNetworkTimeoutInMilli(0) - .setOcspMode(OCSPMode.FAIL_OPEN) - .setSFSession(sfSession) - .setCommand(putCommand1) - .setUseS3RegionalUrl(true) - .build()); - } + for (SnowflakeFileTransferMetadata oneMetadata : metadatas1) { + InputStream inputStream = new FileInputStream(srcPath1); + SnowflakeFileTransferAgent.uploadWithoutConnection( + SnowflakeFileTransferConfig.Builder.newInstance() + .setSnowflakeFileTransferMetadata(oneMetadata) + .setUploadStream(inputStream) + .setRequireCompress(true) + .setNetworkTimeoutInMilli(0) + .setOcspMode(OCSPMode.FAIL_OPEN) + .setSFSession(sfSession) + .setCommand(putCommand1) + .setUseS3RegionalUrl(false) + .build()); + } - // Test Put file with external compression - String putCommand2 = "put file:///dummy/path/file2.gz @" + testStageName; - SnowflakeFileTransferAgent sfAgent2 = - new SnowflakeFileTransferAgent(putCommand2, sfSession, new SFStatement(sfSession)); - List metadatas2 = sfAgent2.getFileTransferMetadatas(); + for (SnowflakeFileTransferMetadata oneMetadata : metadatas1) { + InputStream inputStream = new FileInputStream(srcPath1); + SnowflakeFileTransferAgent.uploadWithoutConnection( + SnowflakeFileTransferConfig.Builder.newInstance() + .setSnowflakeFileTransferMetadata(oneMetadata) + .setUploadStream(inputStream) + .setRequireCompress(true) + .setNetworkTimeoutInMilli(0) + .setOcspMode(OCSPMode.FAIL_OPEN) + .setSFSession(sfSession) + .setCommand(putCommand1) + .setUseS3RegionalUrl(true) + .build()); + } - String srcPath2 = getFullPathFileInResource(TEST_DATA_FILE_2); - for (SnowflakeFileTransferMetadata oneMetadata : metadatas2) { - String gzfilePath = destFolderCanonicalPath + "/tmp_compress.gz"; - Process p = - Runtime.getRuntime() - .exec("cp -fr " + srcPath2 + " " + destFolderCanonicalPath + "/tmp_compress"); - p.waitFor(); - p = Runtime.getRuntime().exec("gzip " + destFolderCanonicalPath + "/tmp_compress"); - p.waitFor(); + // Test Put file with external compression + String putCommand2 = "put file:///dummy/path/file2.gz @" + testStageName; + SnowflakeFileTransferAgent sfAgent2 = + new SnowflakeFileTransferAgent(putCommand2, sfSession, new SFStatement(sfSession)); + List metadatas2 = sfAgent2.getFileTransferMetadatas(); - InputStream gzInputStream = new FileInputStream(gzfilePath); + String srcPath2 = getFullPathFileInResource(TEST_DATA_FILE_2); + for (SnowflakeFileTransferMetadata oneMetadata : metadatas2) { + String gzfilePath = destFolderCanonicalPath + "/tmp_compress.gz"; + Process p = + Runtime.getRuntime() + .exec("cp -fr " + srcPath2 + " " + destFolderCanonicalPath + "/tmp_compress"); + p.waitFor(); + p = Runtime.getRuntime().exec("gzip " + destFolderCanonicalPath + "/tmp_compress"); + p.waitFor(); - SnowflakeFileTransferAgent.uploadWithoutConnection( - SnowflakeFileTransferConfig.Builder.newInstance() - .setSnowflakeFileTransferMetadata(oneMetadata) - .setUploadStream(gzInputStream) - .setRequireCompress(false) - .setNetworkTimeoutInMilli(0) - .setOcspMode(OCSPMode.FAIL_OPEN) - .setSFSession(sfSession) - .setCommand(putCommand2) - .build()); - } + InputStream gzInputStream = new FileInputStream(gzfilePath); - // Download two files and verify their content. - assertTrue( - "Failed to get files", - statement.execute( - "GET @" + testStageName + " 'file://" + destFolderCanonicalPath + "/' parallel=8")); + SnowflakeFileTransferAgent.uploadWithoutConnection( + SnowflakeFileTransferConfig.Builder.newInstance() + .setSnowflakeFileTransferMetadata(oneMetadata) + .setUploadStream(gzInputStream) + .setRequireCompress(false) + .setNetworkTimeoutInMilli(0) + .setOcspMode(OCSPMode.FAIL_OPEN) + .setSFSession(sfSession) + .setCommand(putCommand2) + .build()); + } - // Make sure that the downloaded files are EQUAL, - // they should be gzip compressed - assert (isFileContentEqual(srcPath1, false, destFolderCanonicalPath + "/file1.gz", true)); - assert (isFileContentEqual(srcPath2, false, destFolderCanonicalPath + "/file2.gz", true)); - } finally { - if (connection != null) { - connection.createStatement().execute("DROP STAGE if exists " + testStageName); - connection.close(); + // Download two files and verify their content. + assertTrue( + "Failed to get files", + statement.execute( + "GET @" + + testStageName + + " 'file://" + + destFolderCanonicalPath + + "/' parallel=8")); + + // Make sure that the downloaded files are EQUAL, + // they should be gzip compressed + assert (isFileContentEqual(srcPath1, false, destFolderCanonicalPath + "/file1.gz", true)); + assert (isFileContentEqual(srcPath2, false, destFolderCanonicalPath + "/file2.gz", true)); + } finally { + statement.execute("DROP STAGE if exists " + testStageName); } } } @@ -1466,66 +1366,62 @@ public void testPutS3RegionalUrl() throws Throwable { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testAzureS3UploadStreamingIngestFileMetadata() throws Throwable { - Connection connection = null; String clientName = "clientName"; String clientKey = "clientKey"; List supportedAccounts = Arrays.asList("s3testaccount", "azureaccount"); for (String accountName : supportedAccounts) { - try { - connection = getConnection(accountName); - Statement statement = connection.createStatement(); + try (Connection connection = getConnection(accountName); + Statement statement = connection.createStatement()) { + try { + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE " + testStageName); - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE " + testStageName); + SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); - SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); + // Test put file with internal compression + String putCommand = "put file:///dummy/path/file1.gz @" + testStageName; + SnowflakeFileTransferAgent sfAgent = + new SnowflakeFileTransferAgent(putCommand, sfSession, new SFStatement(sfSession)); + List metadata = sfAgent.getFileTransferMetadatas(); - // Test put file with internal compression - String putCommand = "put file:///dummy/path/file1.gz @" + testStageName; - SnowflakeFileTransferAgent sfAgent = - new SnowflakeFileTransferAgent(putCommand, sfSession, new SFStatement(sfSession)); - List metadata = sfAgent.getFileTransferMetadatas(); - - String srcPath1 = getFullPathFileInResource(TEST_DATA_FILE); - for (SnowflakeFileTransferMetadata oneMetadata : metadata) { - InputStream inputStream = new FileInputStream(srcPath1); + String srcPath1 = getFullPathFileInResource(TEST_DATA_FILE); + for (SnowflakeFileTransferMetadata oneMetadata : metadata) { + InputStream inputStream = new FileInputStream(srcPath1); - SnowflakeFileTransferAgent.uploadWithoutConnection( - SnowflakeFileTransferConfig.Builder.newInstance() - .setSnowflakeFileTransferMetadata(oneMetadata) - .setUploadStream(inputStream) - .setRequireCompress(true) - .setNetworkTimeoutInMilli(0) - .setOcspMode(OCSPMode.FAIL_OPEN) - .setSFSession(sfSession) - .setCommand(putCommand) - .setStreamingIngestClientName(clientName) - .setStreamingIngestClientKey(clientKey) - .build()); + SnowflakeFileTransferAgent.uploadWithoutConnection( + SnowflakeFileTransferConfig.Builder.newInstance() + .setSnowflakeFileTransferMetadata(oneMetadata) + .setUploadStream(inputStream) + .setRequireCompress(true) + .setNetworkTimeoutInMilli(0) + .setOcspMode(OCSPMode.FAIL_OPEN) + .setSFSession(sfSession) + .setCommand(putCommand) + .setStreamingIngestClientName(clientName) + .setStreamingIngestClientKey(clientKey) + .build()); - SnowflakeStorageClient client = - StorageClientFactory.getFactory() - .createClient( - ((SnowflakeFileTransferMetadataV1) oneMetadata).getStageInfo(), - 1, - null, - /* session= */ null); - - String location = - ((SnowflakeFileTransferMetadataV1) oneMetadata).getStageInfo().getLocation(); - int idx = location.indexOf('/'); - String remoteStageLocation = location.substring(0, idx); - String path = location.substring(idx + 1) + "file1.gz"; - StorageObjectMetadata meta = client.getObjectMetadata(remoteStageLocation, path); - - // Verify that we are able to fetch the metadata - assertEquals(clientName, client.getStreamingIngestClientName(meta)); - assertEquals(clientKey, client.getStreamingIngestClientKey(meta)); - } - } finally { - if (connection != null) { - connection.createStatement().execute("DROP STAGE if exists " + testStageName); - connection.close(); + SnowflakeStorageClient client = + StorageClientFactory.getFactory() + .createClient( + ((SnowflakeFileTransferMetadataV1) oneMetadata).getStageInfo(), + 1, + null, + /* session= */ null); + + String location = + ((SnowflakeFileTransferMetadataV1) oneMetadata).getStageInfo().getLocation(); + int idx = location.indexOf('/'); + String remoteStageLocation = location.substring(0, idx); + String path = location.substring(idx + 1) + "file1.gz"; + StorageObjectMetadata meta = client.getObjectMetadata(remoteStageLocation, path); + + // Verify that we are able to fetch the metadata + assertEquals(clientName, client.getStreamingIngestClientName(meta)); + assertEquals(clientKey, client.getStreamingIngestClientKey(meta)); + } + } finally { + statement.execute("DROP STAGE if exists " + testStageName); } } } @@ -1533,38 +1429,36 @@ public void testAzureS3UploadStreamingIngestFileMetadata() throws Throwable { @Test(expected = SnowflakeSQLException.class) public void testNoSpaceLeftOnDeviceException() throws SQLException { - Connection connection = null; List supportedAccounts = Arrays.asList("gcpaccount", "s3testaccount", "azureaccount"); for (String accountName : supportedAccounts) { - try { - connection = getConnection(accountName); + try (Connection connection = getConnection(accountName)) { SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); - Statement statement = connection.createStatement(); - SFStatement sfStatement = statement.unwrap(SnowflakeStatementV1.class).getSfStatement(); - statement.execute("CREATE OR REPLACE STAGE testPutGet_stage"); - statement.execute( - "PUT file://" + getFullPathFileInResource(TEST_DATA_FILE) + " @testPutGet_stage"); - String command = "get @testPutGet_stage/" + TEST_DATA_FILE + " 'file:///tmp'"; - SnowflakeFileTransferAgent sfAgent = - new SnowflakeFileTransferAgent(command, sfSession, sfStatement); - StageInfo info = sfAgent.getStageInfo(); - SnowflakeStorageClient client = - StorageClientFactory.getFactory().createClient(info, 1, null, /* session= */ null); - - client.handleStorageException( - new StorageException( + try (Statement statement = connection.createStatement()) { + try { + SFStatement sfStatement = statement.unwrap(SnowflakeStatementV1.class).getSfStatement(); + statement.execute("CREATE OR REPLACE STAGE testPutGet_stage"); + statement.execute( + "PUT file://" + getFullPathFileInResource(TEST_DATA_FILE) + " @testPutGet_stage"); + String command = "get @testPutGet_stage/" + TEST_DATA_FILE + " 'file:///tmp'"; + SnowflakeFileTransferAgent sfAgent = + new SnowflakeFileTransferAgent(command, sfSession, sfStatement); + StageInfo info = sfAgent.getStageInfo(); + SnowflakeStorageClient client = + StorageClientFactory.getFactory().createClient(info, 1, null, /* session= */ null); + + client.handleStorageException( + new StorageException( + client.getMaxRetries(), + Constants.NO_SPACE_LEFT_ON_DEVICE_ERR, + new IOException(Constants.NO_SPACE_LEFT_ON_DEVICE_ERR)), client.getMaxRetries(), - Constants.NO_SPACE_LEFT_ON_DEVICE_ERR, - new IOException(Constants.NO_SPACE_LEFT_ON_DEVICE_ERR)), - client.getMaxRetries(), - "download", - null, - command, - null); - } finally { - if (connection != null) { - connection.createStatement().execute("DROP STAGE if exists testPutGet_stage"); - connection.close(); + "download", + null, + command, + null); + } finally { + statement.execute("DROP STAGE if exists testPutGet_stage"); + } } } } @@ -1573,51 +1467,47 @@ public void testNoSpaceLeftOnDeviceException() throws SQLException { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testUploadWithGCSPresignedUrlWithoutConnection() throws Throwable { - Connection connection = null; File destFolder = tmpFolder.newFolder(); String destFolderCanonicalPath = destFolder.getCanonicalPath(); - try { - // set parameter for presignedUrl upload instead of downscoped token - Properties paramProperties = new Properties(); - paramProperties.put("GCS_USE_DOWNSCOPED_CREDENTIAL", false); - connection = getConnection("gcpaccount", paramProperties); - Statement statement = connection.createStatement(); + // set parameter for presignedUrl upload instead of downscoped token + Properties paramProperties = new Properties(); + paramProperties.put("GCS_USE_DOWNSCOPED_CREDENTIAL", false); + try (Connection connection = getConnection("gcpaccount", paramProperties); + Statement statement = connection.createStatement()) { + try { + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE " + testStageName); - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE " + testStageName); + SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); - SFSession sfSession = connection.unwrap(SnowflakeConnectionV1.class).getSfSession(); + // Test put file with internal compression + String putCommand = "put file:///dummy/path/file1.gz @" + testStageName; + SnowflakeFileTransferAgent sfAgent = + new SnowflakeFileTransferAgent(putCommand, sfSession, new SFStatement(sfSession)); + List metadata = sfAgent.getFileTransferMetadatas(); - // Test put file with internal compression - String putCommand = "put file:///dummy/path/file1.gz @" + testStageName; - SnowflakeFileTransferAgent sfAgent = - new SnowflakeFileTransferAgent(putCommand, sfSession, new SFStatement(sfSession)); - List metadata = sfAgent.getFileTransferMetadatas(); - - String srcPath = getFullPathFileInResource(TEST_DATA_FILE); - for (SnowflakeFileTransferMetadata oneMetadata : metadata) { - InputStream inputStream = new FileInputStream(srcPath); - - assert (oneMetadata.isForOneFile()); - SnowflakeFileTransferAgent.uploadWithoutConnection( - SnowflakeFileTransferConfig.Builder.newInstance() - .setSnowflakeFileTransferMetadata(oneMetadata) - .setUploadStream(inputStream) - .setRequireCompress(true) - .setNetworkTimeoutInMilli(0) - .setOcspMode(OCSPMode.FAIL_OPEN) - .build()); - } + String srcPath = getFullPathFileInResource(TEST_DATA_FILE); + for (SnowflakeFileTransferMetadata oneMetadata : metadata) { + InputStream inputStream = new FileInputStream(srcPath); - assertTrue( - "Failed to get files", - statement.execute( - "GET @" + testStageName + " 'file://" + destFolderCanonicalPath + "/' parallel=8")); - assert (isFileContentEqual(srcPath, false, destFolderCanonicalPath + "/file1.gz", true)); - } finally { - if (connection != null) { - connection.createStatement().execute("DROP STAGE if exists " + testStageName); - connection.close(); + assert (oneMetadata.isForOneFile()); + SnowflakeFileTransferAgent.uploadWithoutConnection( + SnowflakeFileTransferConfig.Builder.newInstance() + .setSnowflakeFileTransferMetadata(oneMetadata) + .setUploadStream(inputStream) + .setRequireCompress(true) + .setNetworkTimeoutInMilli(0) + .setOcspMode(OCSPMode.FAIL_OPEN) + .build()); + } + + assertTrue( + "Failed to get files", + statement.execute( + "GET @" + testStageName + " 'file://" + destFolderCanonicalPath + "/' parallel=8")); + assert (isFileContentEqual(srcPath, false, destFolderCanonicalPath + "/file1.gz", true)); + } finally { + statement.execute("DROP STAGE if exists " + testStageName); } } } @@ -1785,39 +1675,47 @@ public void testHTAPStatementParameterCaching() throws SQLException { + TestUtil.systemGetEnv("SNOWFLAKE_TEST_ACCOUNT") + " set ENABLE_SNOW_654741_FOR_TESTING=true"); } - Connection con = getConnection(); - Statement statement = con.createStatement(); - // Set up a test table with time, date, and timestamp values - statement.execute("create or replace table timetable (t1 time, t2 timestamp, t3 date)"); - statement.execute( - "insert into timetable values ('13:53:11', '2023-08-17 13:53:33', '2023-08-17')"); - // Set statement- level parameters that will affect the output (set output format params) - statement - .unwrap(SnowflakeStatement.class) - .setParameter("TIME_OUTPUT_FORMAT", "HH12:MI:SS.FF AM"); - statement.unwrap(SnowflakeStatement.class).setParameter("DATE_OUTPUT_FORMAT", "DD-MON-YYYY"); - statement - .unwrap(SnowflakeStatement.class) - .setParameter("TIMESTAMP_OUTPUT_FORMAT", "YYYY-MM-DD\"T\"HH24:MI:SS"); - ResultSet resultSet = statement.executeQuery("select * from timetable"); - resultSet.next(); - // Assert that the values match the format of the specified statement parameter output format - // values - assertEquals("01:53:11.000000000 PM", resultSet.getString(1)); - assertEquals("2023-08-17T13:53:33", resultSet.getString(2)); - assertEquals("17-Aug-2023", resultSet.getString(3)); - // Set a different statement parameter value for DATE_OUTPUT_FORMAT - statement.unwrap(SnowflakeStatement.class).setParameter("DATE_OUTPUT_FORMAT", "MM/DD/YYYY"); - resultSet = statement.executeQuery("select * from timetable"); - resultSet.next(); - // Verify it matches the new statement parameter specified output format - assertEquals("08/17/2023", resultSet.getString(3)); - statement.execute("drop table if exists timetable"); - statement.close(); - con.close(); + try (Connection con = getConnection(); + Statement statement = con.createStatement()) { + // Set up a test table with time, date, and timestamp values + try { + statement.execute("create or replace table timetable (t1 time, t2 timestamp, t3 date)"); + statement.execute( + "insert into timetable values ('13:53:11', '2023-08-17 13:53:33', '2023-08-17')"); + // Set statement- level parameters that will affect the output (set output format params) + statement + .unwrap(SnowflakeStatement.class) + .setParameter("TIME_OUTPUT_FORMAT", "HH12:MI:SS.FF AM"); + statement + .unwrap(SnowflakeStatement.class) + .setParameter("DATE_OUTPUT_FORMAT", "DD-MON-YYYY"); + statement + .unwrap(SnowflakeStatement.class) + .setParameter("TIMESTAMP_OUTPUT_FORMAT", "YYYY-MM-DD\"T\"HH24:MI:SS"); + try (ResultSet resultSet = statement.executeQuery("select * from timetable")) { + resultSet.next(); + // Assert that the values match the format of the specified statement parameter output + // format + // values + assertEquals("01:53:11.000000000 PM", resultSet.getString(1)); + assertEquals("2023-08-17T13:53:33", resultSet.getString(2)); + assertEquals("17-Aug-2023", resultSet.getString(3)); + } + + // Set a different statement parameter value for DATE_OUTPUT_FORMAT + statement.unwrap(SnowflakeStatement.class).setParameter("DATE_OUTPUT_FORMAT", "MM/DD/YYYY"); + try (ResultSet resultSet = statement.executeQuery("select * from timetable")) { + resultSet.next(); + // Verify it matches the new statement parameter specified output format + assertEquals("08/17/2023", resultSet.getString(3)); + } + } finally { + statement.execute("drop table if exists timetable"); + } + } // cleanup - try (Connection con2 = getSnowflakeAdminConnection()) { - statement = con2.createStatement(); + try (Connection con2 = getSnowflakeAdminConnection(); + Statement statement = con2.createStatement()) { statement.execute( "alter account " + TestUtil.systemGetEnv("SNOWFLAKE_TEST_ACCOUNT") @@ -1828,40 +1726,36 @@ public void testHTAPStatementParameterCaching() throws SQLException { @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testS3PutInGS() throws Throwable { - Connection connection = null; File destFolder = tmpFolder.newFolder(); String destFolderCanonicalPath = destFolder.getCanonicalPath(); - try { - Properties paramProperties = new Properties(); - connection = getConnection("s3testaccount", paramProperties); - Statement statement = connection.createStatement(); - - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE " + testStageName); - - // put file using GS system commmand, this is internal GS behavior - final String fileName = "testFile.json"; - final String content = "testName: testS3PutInGs"; - String putSystemCall = - String.format( - "call system$it('PUT_FILE_TO_STAGE', '%s', '%s', '%s', '%s')", - testStageName, fileName, content, "false"); - statement.execute(putSystemCall); - - // get file using jdbc - String getCall = - String.format("GET @%s 'file://%s/'", testStageName, destFolderCanonicalPath); - statement.execute(getCall); - - InputStream downloadedFileStream = - new FileInputStream(destFolderCanonicalPath + "/" + fileName); - String downloadedFile = IOUtils.toString(downloadedFileStream, StandardCharsets.UTF_8); - assertTrue( - "downloaded content does not equal uploaded content", content.equals(downloadedFile)); - } finally { - if (connection != null) { - connection.createStatement().execute("DROP STAGE if exists " + testStageName); - connection.close(); + Properties paramProperties = new Properties(); + try (Connection connection = getConnection("s3testaccount", paramProperties); + Statement statement = connection.createStatement()) { + try { + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE " + testStageName); + + // put file using GS system commmand, this is internal GS behavior + final String fileName = "testFile.json"; + final String content = "testName: testS3PutInGs"; + String putSystemCall = + String.format( + "call system$it('PUT_FILE_TO_STAGE', '%s', '%s', '%s', '%s')", + testStageName, fileName, content, "false"); + statement.execute(putSystemCall); + + // get file using jdbc + String getCall = + String.format("GET @%s 'file://%s/'", testStageName, destFolderCanonicalPath); + statement.execute(getCall); + + InputStream downloadedFileStream = + new FileInputStream(destFolderCanonicalPath + "/" + fileName); + String downloadedFile = IOUtils.toString(downloadedFileStream, StandardCharsets.UTF_8); + assertTrue( + "downloaded content does not equal uploaded content", content.equals(downloadedFile)); + } finally { + statement.execute("DROP STAGE if exists " + testStageName); } } } diff --git a/src/test/java/net/snowflake/client/jdbc/SnowflakeResultSetSerializableIT.java b/src/test/java/net/snowflake/client/jdbc/SnowflakeResultSetSerializableIT.java index 20f986542..0db1cadbd 100644 --- a/src/test/java/net/snowflake/client/jdbc/SnowflakeResultSetSerializableIT.java +++ b/src/test/java/net/snowflake/client/jdbc/SnowflakeResultSetSerializableIT.java @@ -56,17 +56,16 @@ public Connection init() throws SQLException { public Connection init(@Nullable Properties properties) throws SQLException { Connection conn = BaseJDBCTest.getConnection(properties); - Statement stmt = conn.createStatement(); - stmt.execute("alter session set jdbc_query_result_format = '" + queryResultFormat + "'"); - - // Set up theses parameters as smaller values in order to generate - // multiple file chunks with small data volumes. - stmt.execute("alter session set result_first_chunk_max_size = 512"); - stmt.execute("alter session set result_min_chunk_size = 512"); - stmt.execute("alter session set arrow_result_rb_flush_size = 512"); - stmt.execute("alter session set result_chunk_size_multiplier = 1.2"); - stmt.close(); - + try (Statement stmt = conn.createStatement()) { + stmt.execute("alter session set jdbc_query_result_format = '" + queryResultFormat + "'"); + + // Set up theses parameters as smaller values in order to generate + // multiple file chunks with small data volumes. + stmt.execute("alter session set result_first_chunk_max_size = 512"); + stmt.execute("alter session set result_min_chunk_size = 512"); + stmt.execute("alter session set arrow_result_rb_flush_size = 512"); + stmt.execute("alter session set result_chunk_size_multiplier = 1.2"); + } return conn; } @@ -123,12 +122,11 @@ private List serializeResultSet( // Write object to file String tmpFileName = tmpFolder.getRoot().getPath() + "_result_" + i + "." + fileNameAppendix; - FileOutputStream fo = new FileOutputStream(tmpFileName); - ObjectOutputStream so = new ObjectOutputStream(fo); - so.writeObject(entry); - so.flush(); - so.close(); - + try (FileOutputStream fo = new FileOutputStream(tmpFileName); + ObjectOutputStream so = new ObjectOutputStream(fo)) { + so.writeObject(entry); + so.flush(); + } result.add(tmpFileName); } @@ -161,67 +159,68 @@ private String deserializeResultSetWithProperties(List files, Properties for (String filename : files) { // Read Object from file - FileInputStream fi = new FileInputStream(filename); - ObjectInputStream si = new ObjectInputStream(fi); - SnowflakeResultSetSerializableV1 resultSetChunk = - (SnowflakeResultSetSerializableV1) si.readObject(); - fi.close(); + try (FileInputStream fi = new FileInputStream(filename); + ObjectInputStream si = new ObjectInputStream(fi)) { + SnowflakeResultSetSerializableV1 resultSetChunk = + (SnowflakeResultSetSerializableV1) si.readObject(); - if (developPrint) { - System.out.println( - "\nFormat: " - + resultSetChunk.getQueryResultFormat() - + " UncompChunksize: " - + resultSetChunk.getUncompressedDataSizeInBytes() - + " firstChunkContent: " - + (resultSetChunk.getFirstChunkStringData() == null ? " null " : " not null ")); - for (SnowflakeResultSetSerializableV1.ChunkFileMetadata chunkFileMetadata : - resultSetChunk.chunkFileMetadatas) { + if (developPrint) { System.out.println( - "RowCount=" - + chunkFileMetadata.getRowCount() - + ", cpsize=" - + chunkFileMetadata.getCompressedByteSize() - + ", uncpsize=" - + chunkFileMetadata.getUncompressedByteSize() - + ", URL= " - + chunkFileMetadata.getFileURL()); + "\nFormat: " + + resultSetChunk.getQueryResultFormat() + + " UncompChunksize: " + + resultSetChunk.getUncompressedDataSizeInBytes() + + " firstChunkContent: " + + (resultSetChunk.getFirstChunkStringData() == null ? " null " : " not null ")); + for (SnowflakeResultSetSerializableV1.ChunkFileMetadata chunkFileMetadata : + resultSetChunk.chunkFileMetadatas) { + System.out.println( + "RowCount=" + + chunkFileMetadata.getRowCount() + + ", cpsize=" + + chunkFileMetadata.getCompressedByteSize() + + ", uncpsize=" + + chunkFileMetadata.getUncompressedByteSize() + + ", URL= " + + chunkFileMetadata.getFileURL()); + } } - } - // Read data from object - ResultSet rs = - resultSetChunk.getResultSet( - SnowflakeResultSetSerializable.ResultSetRetrieveConfig.Builder.newInstance() - .setProxyProperties(props) - .setSfFullURL(sfFullURL) - .build()); - - // print result set meta data - ResultSetMetaData metadata = rs.getMetaData(); - int colCount = metadata.getColumnCount(); - if (developPrint) { - for (int j = 1; j <= colCount; j++) { - System.out.print(" table: " + metadata.getTableName(j)); - System.out.print(" schema: " + metadata.getSchemaName(j)); - System.out.print(" type: " + metadata.getColumnTypeName(j)); - System.out.print(" name: " + metadata.getColumnName(j)); - System.out.print(" precision: " + metadata.getPrecision(j)); - System.out.println(" scale:" + metadata.getScale(j)); - } - } + // Read data from object + try (ResultSet rs = + resultSetChunk.getResultSet( + SnowflakeResultSetSerializable.ResultSetRetrieveConfig.Builder.newInstance() + .setProxyProperties(props) + .setSfFullURL(sfFullURL) + .build())) { + + // print result set meta data + ResultSetMetaData metadata = rs.getMetaData(); + int colCount = metadata.getColumnCount(); + if (developPrint) { + for (int j = 1; j <= colCount; j++) { + System.out.print(" table: " + metadata.getTableName(j)); + System.out.print(" schema: " + metadata.getSchemaName(j)); + System.out.print(" type: " + metadata.getColumnTypeName(j)); + System.out.print(" name: " + metadata.getColumnName(j)); + System.out.print(" precision: " + metadata.getPrecision(j)); + System.out.println(" scale:" + metadata.getScale(j)); + } + } - // Print and count data - while (rs.next()) { - for (int i = 1; i <= colCount; i++) { - rs.getObject(i); - if (rs.wasNull()) { - builder.append("\"").append("null").append("\","); - } else { - builder.append("\"").append(rs.getString(i)).append("\","); + // Print and count data + while (rs.next()) { + for (int i = 1; i <= colCount; i++) { + rs.getObject(i); + if (rs.wasNull()) { + builder.append("\"").append("null").append("\","); + } else { + builder.append("\"").append(rs.getString(i)).append("\","); + } + } + builder.append("\n"); } } - builder.append("\n"); } } @@ -275,15 +274,15 @@ private void testBasicTableHarness( } String sqlSelect = "select * from table_basic " + whereClause; - ResultSet rs = + try (ResultSet rs = async ? statement.unwrap(SnowflakeStatement.class).executeAsyncQuery(sqlSelect) - : statement.executeQuery(sqlSelect); + : statement.executeQuery(sqlSelect)) { - fileNameList = serializeResultSet((SnowflakeResultSet) rs, maxSizeInBytes, "txt"); + fileNameList = serializeResultSet((SnowflakeResultSet) rs, maxSizeInBytes, "txt"); - originalResultCSVString = generateCSVResult(rs); - rs.close(); + originalResultCSVString = generateCSVResult(rs); + } } String chunkResultString = deserializeResultSet(fileNameList); @@ -370,25 +369,14 @@ private void testTimestampHarness( throws Throwable { List fileNameList = null; String originalResultCSVString = null; - try (Connection connection = init()) { - connection - .createStatement() - .execute("alter session set DATE_OUTPUT_FORMAT = '" + format_date + "'"); - connection - .createStatement() - .execute("alter session set TIME_OUTPUT_FORMAT = '" + format_time + "'"); - connection - .createStatement() - .execute("alter session set TIMESTAMP_NTZ_OUTPUT_FORMAT = '" + format_ntz + "'"); - connection - .createStatement() - .execute("alter session set TIMESTAMP_LTZ_OUTPUT_FORMAT = '" + format_ltz + "'"); - connection - .createStatement() - .execute("alter session set TIMESTAMP_TZ_OUTPUT_FORMAT = '" + format_tz + "'"); - connection.createStatement().execute("alter session set TIMEZONE = '" + timezone + "'"); - - Statement statement = connection.createStatement(); + try (Connection connection = init(); + Statement statement = connection.createStatement()) { + statement.execute("alter session set DATE_OUTPUT_FORMAT = '" + format_date + "'"); + statement.execute("alter session set TIME_OUTPUT_FORMAT = '" + format_time + "'"); + statement.execute("alter session set TIMESTAMP_NTZ_OUTPUT_FORMAT = '" + format_ntz + "'"); + statement.execute("alter session set TIMESTAMP_LTZ_OUTPUT_FORMAT = '" + format_ltz + "'"); + statement.execute("alter session set TIMESTAMP_TZ_OUTPUT_FORMAT = '" + format_tz + "'"); + statement.execute("alter session set TIMEZONE = '" + timezone + "'"); statement.execute( "Create or replace table all_timestamps (" @@ -403,30 +391,28 @@ private void testTimestampHarness( + ")"); if (rowCount > 0) { - connection - .createStatement() - .execute( - "insert into all_timestamps " - + "select seq4(), '2015-10-25' , " - + "'23:59:59.123456789', '23:59:59', '23:59:59.123', '23:59:59.123456', " - + " '2014-01-11 06:12:13.123456789', '2014-01-11 06:12:13'," - + " '2014-01-11 06:12:13.123', '2014-01-11 06:12:13.123456'," - + " '2014-01-11 06:12:13.123456789', '2014-01-11 06:12:13'," - + " '2014-01-11 06:12:13.123', '2014-01-11 06:12:13.123456'," - + " '2014-01-11 06:12:13.123456789', '2014-01-11 06:12:13'," - + " '2014-01-11 06:12:13.123', '2014-01-11 06:12:13.123456'" - + " from table(generator(rowcount=>" - + rowCount - + "))"); + statement.execute( + "insert into all_timestamps " + + "select seq4(), '2015-10-25' , " + + "'23:59:59.123456789', '23:59:59', '23:59:59.123', '23:59:59.123456', " + + " '2014-01-11 06:12:13.123456789', '2014-01-11 06:12:13'," + + " '2014-01-11 06:12:13.123', '2014-01-11 06:12:13.123456'," + + " '2014-01-11 06:12:13.123456789', '2014-01-11 06:12:13'," + + " '2014-01-11 06:12:13.123', '2014-01-11 06:12:13.123456'," + + " '2014-01-11 06:12:13.123456789', '2014-01-11 06:12:13'," + + " '2014-01-11 06:12:13.123', '2014-01-11 06:12:13.123456'" + + " from table(generator(rowcount=>" + + rowCount + + "))"); } String sqlSelect = "select * from all_timestamps " + whereClause; - ResultSet rs = statement.executeQuery(sqlSelect); + try (ResultSet rs = statement.executeQuery(sqlSelect)) { - fileNameList = serializeResultSet((SnowflakeResultSet) rs, maxSizeInBytes, "txt"); + fileNameList = serializeResultSet((SnowflakeResultSet) rs, maxSizeInBytes, "txt"); - originalResultCSVString = generateCSVResult(rs); - rs.close(); + originalResultCSVString = generateCSVResult(rs); + } } String chunkResultString = deserializeResultSet(fileNameList); @@ -464,9 +450,8 @@ public void testTimestamp() throws Throwable { public void testBasicTableWithSerializeObjectsAfterReadResultSet() throws Throwable { List fileNameList = null; String originalResultCSVString = null; - try (Connection connection = init()) { - Statement statement = connection.createStatement(); - + try (Connection connection = init(); + Statement statement = connection.createStatement()) { statement.execute("create or replace schema testschema"); statement.execute( @@ -481,16 +466,15 @@ public void testBasicTableWithSerializeObjectsAfterReadResultSet() throws Throwa + "))"); String sqlSelect = "select * from table_basic "; - ResultSet rs = statement.executeQuery(sqlSelect); + try (ResultSet rs = statement.executeQuery(sqlSelect)) { - originalResultCSVString = generateCSVResult(rs); + originalResultCSVString = generateCSVResult(rs); - // In previous test, the serializable objects are serialized before - // reading the ResultSet. This test covers the case that serializes the - // object after reading the result set. - fileNameList = serializeResultSet((SnowflakeResultSet) rs, 1 * 1024 * 1024, "txt"); - - rs.close(); + // In previous test, the serializable objects are serialized before + // reading the ResultSet. This test covers the case that serializes the + // object after reading the result set. + fileNameList = serializeResultSet((SnowflakeResultSet) rs, 1 * 1024 * 1024, "txt"); + } } String chunkResultString = deserializeResultSet(fileNameList); @@ -511,29 +495,29 @@ private synchronized List splitResultSetSerializables( for (String filename : files) { // Read Object from file - FileInputStream fi = new FileInputStream(filename); - ObjectInputStream si = new ObjectInputStream(fi); - SnowflakeResultSetSerializableV1 resultSetChunk = - (SnowflakeResultSetSerializableV1) si.readObject(); - fi.close(); - - // Get ResultSet from object - ResultSet rs = - resultSetChunk.getResultSet( - SnowflakeResultSetSerializable.ResultSetRetrieveConfig.Builder.newInstance() - .setProxyProperties(new Properties()) - .setSfFullURL(sfFullURL) - .build()); - - String[] filePathParts = filename.split(File.separator); - String appendix = filePathParts[filePathParts.length - 1]; - - List thisFileList = - serializeResultSet((SnowflakeResultSet) rs, maxSizeInBytes, appendix); - for (int i = 0; i < thisFileList.size(); i++) { - resultFileList.add(thisFileList.get(i)); + try (FileInputStream fi = new FileInputStream(filename); + ObjectInputStream si = new ObjectInputStream(fi)) { + SnowflakeResultSetSerializableV1 resultSetChunk = + (SnowflakeResultSetSerializableV1) si.readObject(); + + // Get ResultSet from object + try (ResultSet rs = + resultSetChunk.getResultSet( + SnowflakeResultSetSerializable.ResultSetRetrieveConfig.Builder.newInstance() + .setProxyProperties(new Properties()) + .setSfFullURL(sfFullURL) + .build())) { + + String[] filePathParts = filename.split(File.separator); + String appendix = filePathParts[filePathParts.length - 1]; + + List thisFileList = + serializeResultSet((SnowflakeResultSet) rs, maxSizeInBytes, appendix); + for (int i = 0; i < thisFileList.size(); i++) { + resultFileList.add(thisFileList.get(i)); + } + } } - rs.close(); } if (developPrint) { @@ -550,8 +534,8 @@ public void testSplitResultSetSerializable() throws Throwable { List fileNameList = null; String originalResultCSVString = null; int rowCount = 90000; - try (Connection connection = init()) { - Statement statement = connection.createStatement(); + try (Connection connection = init(); + Statement statement = connection.createStatement()) { statement.execute( "create or replace table table_basic " + " (int_c int, string_c string(128))"); @@ -565,12 +549,12 @@ public void testSplitResultSetSerializable() throws Throwable { + "))"); String sqlSelect = "select * from table_basic "; - ResultSet rs = statement.executeQuery(sqlSelect); + try (ResultSet rs = statement.executeQuery(sqlSelect)) { - fileNameList = serializeResultSet((SnowflakeResultSet) rs, 100 * 1024 * 1024, "txt"); + fileNameList = serializeResultSet((SnowflakeResultSet) rs, 100 * 1024 * 1024, "txt"); - originalResultCSVString = generateCSVResult(rs); - rs.close(); + originalResultCSVString = generateCSVResult(rs); + } } // Split deserializedResultSet by 3M, the result should be the same @@ -613,28 +597,30 @@ private void hackToSetupWrongURL(List resultSetS @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testCloseUnconsumedResultSet() throws Throwable { - try (Connection connection = init()) { - Statement statement = connection.createStatement(); - - statement.execute( - "create or replace table table_basic " + " (int_c int, string_c string(128))"); + try (Connection connection = init(); + Statement statement = connection.createStatement()) { + try { + statement.execute( + "create or replace table table_basic " + " (int_c int, string_c string(128))"); - int rowCount = 100000; - statement.execute( - "insert into table_basic select " - + "seq4(), " - + "'arrow_1234567890arrow_1234567890arrow_1234567890arrow_1234567890'" - + " from table(generator(rowcount=>" - + rowCount - + "))"); + int rowCount = 100000; + statement.execute( + "insert into table_basic select " + + "seq4(), " + + "'arrow_1234567890arrow_1234567890arrow_1234567890arrow_1234567890'" + + " from table(generator(rowcount=>" + + rowCount + + "))"); - int testCount = 5; - while (testCount-- > 0) { - String sqlSelect = "select * from table_basic "; - ResultSet rs = statement.executeQuery(sqlSelect); - rs.close(); + int testCount = 5; + while (testCount-- > 0) { + String sqlSelect = "select * from table_basic "; + try (ResultSet rs = statement.executeQuery(sqlSelect)) {} + ; + } + } finally { + statement.execute("drop table if exists table_basic"); } - statement.execute("drop table if exists table_basic"); } } @@ -645,50 +631,50 @@ public void testNegativeWithChunkFileNotExist() throws Throwable { Properties properties = new Properties(); properties.put("networkTimeout", 10000); // 10000 millisec try (Connection connection = init(properties)) { - Statement statement = connection.createStatement(); - - statement.execute( - "create or replace table table_basic " + " (int_c int, string_c string(128))"); - - int rowCount = 300; - statement.execute( - "insert into table_basic select " - + "seq4(), " - + "'arrow_1234567890arrow_1234567890arrow_1234567890arrow_1234567890'" - + " from table(generator(rowcount=>" - + rowCount - + "))"); - - String sqlSelect = "select * from table_basic "; - ResultSet rs = statement.executeQuery(sqlSelect); - - // Test case 1: Generate one Serializable object - List resultSetSerializables = - ((SnowflakeResultSet) rs).getResultSetSerializables(100 * 1024 * 1024); - - hackToSetupWrongURL(resultSetSerializables); - - // Expected to hit credential issue when access the result. - assertEquals(resultSetSerializables.size(), 1); - try { - SnowflakeResultSetSerializable resultSetSerializable = resultSetSerializables.get(0); + try (Statement statement = connection.createStatement()) { + statement.execute( + "create or replace table table_basic " + " (int_c int, string_c string(128))"); - ResultSet resultSet = - resultSetSerializable.getResultSet( - SnowflakeResultSetSerializable.ResultSetRetrieveConfig.Builder.newInstance() - .setProxyProperties(new Properties()) - .setSfFullURL(sfFullURL) - .build()); + int rowCount = 300; + statement.execute( + "insert into table_basic select " + + "seq4(), " + + "'arrow_1234567890arrow_1234567890arrow_1234567890arrow_1234567890'" + + " from table(generator(rowcount=>" + + rowCount + + "))"); - while (resultSet.next()) { - resultSet.getString(1); + String sqlSelect = "select * from table_basic "; + try (ResultSet rs = statement.executeQuery(sqlSelect)) { + // Test case 1: Generate one Serializable object + List resultSetSerializables = + ((SnowflakeResultSet) rs).getResultSetSerializables(100 * 1024 * 1024); + + hackToSetupWrongURL(resultSetSerializables); + + // Expected to hit credential issue when access the result. + assertEquals(resultSetSerializables.size(), 1); + try { + SnowflakeResultSetSerializable resultSetSerializable = resultSetSerializables.get(0); + + ResultSet resultSet = + resultSetSerializable.getResultSet( + SnowflakeResultSetSerializable.ResultSetRetrieveConfig.Builder.newInstance() + .setProxyProperties(new Properties()) + .setSfFullURL(sfFullURL) + .build()); + + while (resultSet.next()) { + resultSet.getString(1); + } + fail( + "error should happen when accessing the data because the " + + "file URL is corrupted."); + } catch (SQLException ex) { + assertEquals((long) ErrorCode.INTERNAL_ERROR.getMessageCode(), ex.getErrorCode()); + } } - fail("error should happen when accessing the data because the " + "file URL is corrupted."); - } catch (SQLException ex) { - assertEquals((long) ErrorCode.INTERNAL_ERROR.getMessageCode(), ex.getErrorCode()); } - - rs.close(); } } @@ -791,25 +777,27 @@ public void testCustomProxyWithFiles() throws Throwable { private void generateTestFiles() throws Throwable { try (Connection connection = init()) { - Statement statement = connection.createStatement(); + try (Statement statement = connection.createStatement()) { - statement.execute( - "create or replace table table_basic " + " (int_c int, string_c string(128))"); + statement.execute( + "create or replace table table_basic " + " (int_c int, string_c string(128))"); - int rowCount = 60000; - statement.execute( - "insert into table_basic select " - + "seq4(), " - + "'arrow_1234567890arrow_1234567890arrow_1234567890arrow_1234567890'" - + " from table(generator(rowcount=>" - + rowCount - + "))"); + int rowCount = 60000; + statement.execute( + "insert into table_basic select " + + "seq4(), " + + "'arrow_1234567890arrow_1234567890arrow_1234567890arrow_1234567890'" + + " from table(generator(rowcount=>" + + rowCount + + "))"); - String sqlSelect = "select * from table_basic "; - ResultSet rs = statement.executeQuery(sqlSelect); - developPrint = true; - serializeResultSet((SnowflakeResultSet) rs, 2 * 1024 * 1024, "txt"); - System.exit(-1); + String sqlSelect = "select * from table_basic "; + try (ResultSet rs = statement.executeQuery(sqlSelect)) { + developPrint = true; + serializeResultSet((SnowflakeResultSet) rs, 2 * 1024 * 1024, "txt"); + System.exit(-1); + } + } } } @@ -822,48 +810,46 @@ public void testRetrieveMetadata() throws Throwable { long expectedTotalCompressedSize = 0; long expectedTotalUncompressedSize = 0; try (Connection connection = init()) { - Statement statement = connection.createStatement(); - - statement.execute( - "create or replace table table_basic " + " (int_c int, string_c string(128))"); + try (Statement statement = connection.createStatement()) { - statement.execute( - "insert into table_basic select " - + "seq4(), " - + "'arrow_1234567890arrow_1234567890arrow_1234567890arrow_1234567890'" - + " from table(generator(rowcount=>" - + rowCount - + "))"); - - String sqlSelect = "select * from table_basic "; - ResultSet rs = statement.executeQuery(sqlSelect); - - // Split deserializedResultSet by 3M - fileNameList = serializeResultSet((SnowflakeResultSet) rs, 100 * 1024 * 1024, "txt"); - - // Only one serializable object is generated with 100M data. - assertEquals(fileNameList.size(), 1); + statement.execute( + "create or replace table table_basic " + " (int_c int, string_c string(128))"); - FileInputStream fi = new FileInputStream(fileNameList.get(0)); - ObjectInputStream si = new ObjectInputStream(fi); - SnowflakeResultSetSerializableV1 wholeResultSetChunk = - (SnowflakeResultSetSerializableV1) si.readObject(); - fi.close(); - expectedTotalRowCount = wholeResultSetChunk.getRowCount(); - expectedTotalCompressedSize = wholeResultSetChunk.getCompressedDataSizeInBytes(); - expectedTotalUncompressedSize = wholeResultSetChunk.getUncompressedDataSizeInBytes(); + statement.execute( + "insert into table_basic select " + + "seq4(), " + + "'arrow_1234567890arrow_1234567890arrow_1234567890arrow_1234567890'" + + " from table(generator(rowcount=>" + + rowCount + + "))"); - if (developPrint) { - System.out.println( - "Total statistic: RowCount=" - + expectedTotalRowCount - + " CompSize=" - + expectedTotalCompressedSize - + " UncompSize=" - + expectedTotalUncompressedSize); + String sqlSelect = "select * from table_basic "; + try (ResultSet rs = statement.executeQuery(sqlSelect)) { + // Split deserializedResultSet by 3M + fileNameList = serializeResultSet((SnowflakeResultSet) rs, 100 * 1024 * 1024, "txt"); + + // Only one serializable object is generated with 100M data. + assertEquals(fileNameList.size(), 1); + + try (FileInputStream fi = new FileInputStream(fileNameList.get(0)); + ObjectInputStream si = new ObjectInputStream(fi)) { + SnowflakeResultSetSerializableV1 wholeResultSetChunk = + (SnowflakeResultSetSerializableV1) si.readObject(); + expectedTotalRowCount = wholeResultSetChunk.getRowCount(); + expectedTotalCompressedSize = wholeResultSetChunk.getCompressedDataSizeInBytes(); + expectedTotalUncompressedSize = wholeResultSetChunk.getUncompressedDataSizeInBytes(); + } + if (developPrint) { + System.out.println( + "Total statistic: RowCount=" + + expectedTotalRowCount + + " CompSize=" + + expectedTotalCompressedSize + + " UncompSize=" + + expectedTotalUncompressedSize); + } + } } - - rs.close(); } assertEquals(expectedTotalRowCount, rowCount); assertThat(expectedTotalCompressedSize, greaterThan((long) 0)); @@ -938,56 +924,55 @@ private boolean isMetadataConsistent( for (String filename : files) { // Read Object from file - FileInputStream fi = new FileInputStream(filename); - ObjectInputStream si = new ObjectInputStream(fi); - SnowflakeResultSetSerializableV1 resultSetChunk = - (SnowflakeResultSetSerializableV1) si.readObject(); - fi.close(); - - // Accumulate statistic from metadata - actualRowCountFromMetadata += resultSetChunk.getRowCount(); - actualTotalCompressedSize += resultSetChunk.getCompressedDataSizeInBytes(); - actualTotalUncompressedSize += resultSetChunk.getUncompressedDataSizeInBytes(); - chunkFileCount += resultSetChunk.chunkFileCount; - - // Get actual row count from result set. - // sfFullURL is used to support private link URL. - // This test case is not for private link env, so just use a valid URL for testing purpose. - ResultSet rs = - resultSetChunk.getResultSet( - SnowflakeResultSetSerializable.ResultSetRetrieveConfig.Builder.newInstance() - .setProxyProperties(props) - .setSfFullURL(sfFullURL) - .build()); - - // Accumulate the actual row count from result set. - while (rs.next()) { - actualRowCount++; - } - } + try (FileInputStream fi = new FileInputStream(filename); + ObjectInputStream si = new ObjectInputStream(fi)) { + SnowflakeResultSetSerializableV1 resultSetChunk = + (SnowflakeResultSetSerializableV1) si.readObject(); + + // Accumulate statistic from metadata + actualRowCountFromMetadata += resultSetChunk.getRowCount(); + actualTotalCompressedSize += resultSetChunk.getCompressedDataSizeInBytes(); + actualTotalUncompressedSize += resultSetChunk.getUncompressedDataSizeInBytes(); + chunkFileCount += resultSetChunk.chunkFileCount; + + // Get actual row count from result set. + // sfFullURL is used to support private link URL. + // This test case is not for private link env, so just use a valid URL for testing purpose. + try (ResultSet rs = + resultSetChunk.getResultSet( + SnowflakeResultSetSerializable.ResultSetRetrieveConfig.Builder.newInstance() + .setProxyProperties(props) + .setSfFullURL(sfFullURL) + .build())) { - if (developPrint) { - System.out.println( - "isMetadataConsistent: FileCount=" - + files.size() - + " RowCounts=" - + expectedTotalRowCount - + " " - + actualRowCountFromMetadata - + " (" - + actualRowCount - + ") CompSize=" - + expectedTotalCompressedSize - + " " - + actualTotalCompressedSize - + " UncompSize=" - + expectedTotalUncompressedSize - + " " - + actualTotalUncompressedSize - + " chunkFileCount=" - + chunkFileCount); + // Accumulate the actual row count from result set. + while (rs.next()) { + actualRowCount++; + } + } + } + if (developPrint) { + System.out.println( + "isMetadataConsistent: FileCount=" + + files.size() + + " RowCounts=" + + expectedTotalRowCount + + " " + + actualRowCountFromMetadata + + " (" + + actualRowCount + + ") CompSize=" + + expectedTotalCompressedSize + + " " + + actualTotalCompressedSize + + " UncompSize=" + + expectedTotalUncompressedSize + + " " + + actualTotalUncompressedSize + + " chunkFileCount=" + + chunkFileCount); + } } - return actualRowCount == expectedTotalRowCount && actualRowCountFromMetadata == expectedTotalRowCount && actualTotalCompressedSize == expectedTotalCompressedSize diff --git a/src/test/java/net/snowflake/client/jdbc/StatementIT.java b/src/test/java/net/snowflake/client/jdbc/StatementIT.java index 82c9725b4..f27e63533 100644 --- a/src/test/java/net/snowflake/client/jdbc/StatementIT.java +++ b/src/test/java/net/snowflake/client/jdbc/StatementIT.java @@ -41,9 +41,9 @@ public class StatementIT extends BaseJDBCTest { public static Connection getConnection() throws SQLException { Connection conn = BaseJDBCTest.getConnection(); - Statement stmt = conn.createStatement(); - stmt.execute("alter session set jdbc_query_result_format = '" + queryResultFormat + "'"); - stmt.close(); + try (Statement stmt = conn.createStatement()) { + stmt.execute("alter session set jdbc_query_result_format = '" + queryResultFormat + "'"); + } return conn; } @@ -51,209 +51,207 @@ public static Connection getConnection() throws SQLException { @Test public void testFetchDirection() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - assertEquals(ResultSet.FETCH_FORWARD, statement.getFetchDirection()); - try { - statement.setFetchDirection(ResultSet.FETCH_REVERSE); - } catch (SQLFeatureNotSupportedException e) { - assertTrue(true); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + assertEquals(ResultSet.FETCH_FORWARD, statement.getFetchDirection()); + try { + statement.setFetchDirection(ResultSet.FETCH_REVERSE); + } catch (SQLFeatureNotSupportedException e) { + assertTrue(true); + } } - statement.close(); - connection.close(); } @Ignore("Not working for setFetchSize") @Test public void testFetchSize() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - assertEquals(50, statement.getFetchSize()); - statement.setFetchSize(1); - ResultSet rs = statement.executeQuery("select * from JDBC_STATEMENT"); - assertEquals(1, getSizeOfResultSet(rs)); - - statement.close(); - connection.close(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + assertEquals(50, statement.getFetchSize()); + statement.setFetchSize(1); + ResultSet rs = statement.executeQuery("select * from JDBC_STATEMENT"); + assertEquals(1, getSizeOfResultSet(rs)); + } } @Test public void testMaxRows() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - String sqlSelect = "select seq4() from table(generator(rowcount=>3))"; - assertEquals(0, statement.getMaxRows()); - - // statement.setMaxRows(1); - // assertEquals(1, statement.getMaxRows()); - ResultSet rs = statement.executeQuery(sqlSelect); - int resultSizeCount = getSizeOfResultSet(rs); - // assertEquals(1, resultSizeCount); - - statement.setMaxRows(0); - rs = statement.executeQuery(sqlSelect); - // assertEquals(3, getSizeOfResultSet(rs)); - - statement.setMaxRows(-1); - rs = statement.executeQuery(sqlSelect); - // assertEquals(3, getSizeOfResultSet(rs)); - statement.close(); - - connection.close(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + String sqlSelect = "select seq4() from table(generator(rowcount=>3))"; + assertEquals(0, statement.getMaxRows()); + + // statement.setMaxRows(1); + // assertEquals(1, statement.getMaxRows()); + try (ResultSet rs = statement.executeQuery(sqlSelect)) { + int resultSizeCount = getSizeOfResultSet(rs); + // assertEquals(1, resultSizeCount); + } + statement.setMaxRows(0); + try (ResultSet rs = statement.executeQuery(sqlSelect)) { + // assertEquals(3, getSizeOfResultSet(rs)); + } + statement.setMaxRows(-1); + try (ResultSet rs = statement.executeQuery(sqlSelect)) { + // assertEquals(3, getSizeOfResultSet(rs)); + } + } } @Test public void testQueryTimeOut() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - assertEquals(0, statement.getQueryTimeout()); - statement.setQueryTimeout(5); - assertEquals(5, statement.getQueryTimeout()); - try { - statement.executeQuery("select count(*) from table(generator(timeLimit => 100))"); - } catch (SQLException e) { - assertTrue(true); - assertEquals(SqlState.QUERY_CANCELED, e.getSQLState()); - assertEquals("SQL execution canceled", e.getMessage()); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + assertEquals(0, statement.getQueryTimeout()); + statement.setQueryTimeout(5); + assertEquals(5, statement.getQueryTimeout()); + try { + statement.executeQuery("select count(*) from table(generator(timeLimit => 100))"); + } catch (SQLException e) { + assertTrue(true); + assertEquals(SqlState.QUERY_CANCELED, e.getSQLState()); + assertEquals("SQL execution canceled", e.getMessage()); + } } - statement.close(); - connection.close(); } @Test public void testStatementClose() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - assertEquals(connection, statement.getConnection()); - assertTrue(!statement.isClosed()); - statement.close(); - assertTrue(statement.isClosed()); - connection.close(); + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertEquals(connection, statement.getConnection()); + assertTrue(!statement.isClosed()); + statement.close(); + assertTrue(statement.isClosed()); + } } @Test public void testExecuteSelect() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - - String sqlSelect = "select seq4() from table(generator(rowcount=>3))"; - boolean success = statement.execute(sqlSelect); - assertTrue(success); - String queryID1 = statement.unwrap(SnowflakeStatement.class).getQueryID(); - assertNotNull(queryID1); - - ResultSet rs = statement.getResultSet(); - assertEquals(3, getSizeOfResultSet(rs)); - assertEquals(-1, statement.getUpdateCount()); - assertEquals(-1L, statement.getLargeUpdateCount()); - String queryID2 = rs.unwrap(SnowflakeResultSet.class).getQueryID(); - assertEquals(queryID2, queryID1); - - rs = statement.executeQuery(sqlSelect); - assertEquals(3, getSizeOfResultSet(rs)); - String queryID4 = rs.unwrap(SnowflakeResultSet.class).getQueryID(); - assertNotEquals(queryID4, queryID1); - rs.close(); - - statement.close(); - connection.close(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + + String sqlSelect = "select seq4() from table(generator(rowcount=>3))"; + boolean success = statement.execute(sqlSelect); + assertTrue(success); + String queryID1 = statement.unwrap(SnowflakeStatement.class).getQueryID(); + assertNotNull(queryID1); + + try (ResultSet rs = statement.getResultSet()) { + assertEquals(3, getSizeOfResultSet(rs)); + assertEquals(-1, statement.getUpdateCount()); + assertEquals(-1L, statement.getLargeUpdateCount()); + String queryID2 = rs.unwrap(SnowflakeResultSet.class).getQueryID(); + assertEquals(queryID2, queryID1); + } + try (ResultSet rs = statement.executeQuery(sqlSelect)) { + assertEquals(3, getSizeOfResultSet(rs)); + String queryID4 = rs.unwrap(SnowflakeResultSet.class).getQueryID(); + assertNotEquals(queryID4, queryID1); + } + } } @Test public void testExecuteInsert() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - statement.execute("create or replace table test_insert(cola number)"); - - String insertSQL = "insert into test_insert values(2),(3)"; - int updateCount; - boolean success; - updateCount = statement.executeUpdate(insertSQL); - assertEquals(2, updateCount); - - success = statement.execute(insertSQL); - assertFalse(success); - assertEquals(2, statement.getUpdateCount()); - assertEquals(2L, statement.getLargeUpdateCount()); - assertNull(statement.getResultSet()); - - ResultSet rs = statement.executeQuery("select count(*) from test_insert"); - rs.next(); - assertEquals(4, rs.getInt(1)); - rs.close(); - - assertTrue(statement.execute("select 1")); - ResultSet rs0 = statement.getResultSet(); - rs0.next(); - assertEquals(rs0.getInt(1), 1); - rs0.close(); - - statement.execute("drop table if exists test_insert"); - statement.close(); - connection.close(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + statement.execute("create or replace table test_insert(cola number)"); + + String insertSQL = "insert into test_insert values(2),(3)"; + int updateCount; + boolean success; + updateCount = statement.executeUpdate(insertSQL); + assertEquals(2, updateCount); + + success = statement.execute(insertSQL); + assertFalse(success); + assertEquals(2, statement.getUpdateCount()); + assertEquals(2L, statement.getLargeUpdateCount()); + assertNull(statement.getResultSet()); + + try (ResultSet rs = statement.executeQuery("select count(*) from test_insert")) { + rs.next(); + assertEquals(4, rs.getInt(1)); + } + + assertTrue(statement.execute("select 1")); + try (ResultSet rs0 = statement.getResultSet()) { + rs0.next(); + assertEquals(rs0.getInt(1), 1); + } + } finally { + statement.execute("drop table if exists test_insert"); + } + } } @Test public void testExecuteUpdateAndDelete() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - - statement.execute( - "create or replace table test_update(cola number, colb string) " + "as select 1, 'str1'"); - - statement.execute("insert into test_update values(2, 'str2')"); - - int updateCount; - boolean success; - updateCount = statement.executeUpdate("update test_update set COLB = 'newStr' where COLA = 1"); - assertEquals(1, updateCount); - - success = statement.execute("update test_update set COLB = 'newStr' where COLA = 2"); - assertFalse(success); - assertEquals(1, statement.getUpdateCount()); - assertEquals(1L, statement.getLargeUpdateCount()); - assertNull(statement.getResultSet()); - - updateCount = statement.executeUpdate("delete from test_update where colA = 1"); - assertEquals(1, updateCount); - - success = statement.execute("delete from test_update where colA = 2"); - assertFalse(success); - assertEquals(1, statement.getUpdateCount()); - assertEquals(1L, statement.getLargeUpdateCount()); - assertNull(statement.getResultSet()); - - statement.execute("drop table if exists test_update"); - statement.close(); - - connection.close(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + statement.execute( + "create or replace table test_update(cola number, colb string) " + + "as select 1, 'str1'"); + + statement.execute("insert into test_update values(2, 'str2')"); + + int updateCount; + boolean success; + updateCount = + statement.executeUpdate("update test_update set COLB = 'newStr' where COLA = 1"); + assertEquals(1, updateCount); + + success = statement.execute("update test_update set COLB = 'newStr' where COLA = 2"); + assertFalse(success); + assertEquals(1, statement.getUpdateCount()); + assertEquals(1L, statement.getLargeUpdateCount()); + assertNull(statement.getResultSet()); + + updateCount = statement.executeUpdate("delete from test_update where colA = 1"); + assertEquals(1, updateCount); + + success = statement.execute("delete from test_update where colA = 2"); + assertFalse(success); + assertEquals(1, statement.getUpdateCount()); + assertEquals(1L, statement.getLargeUpdateCount()); + assertNull(statement.getResultSet()); + } finally { + statement.execute("drop table if exists test_update"); + } + } } @Test public void testExecuteMerge() throws SQLException { - Connection connection = getConnection(); - String mergeSQL = - "merge into target using source on target.id = source.id " - + "when matched and source.sb =22 then update set ta = 'newStr' " - + "when not matched then insert (ta, tb) values (source.sa, source.sb)"; - Statement statement = connection.createStatement(); - statement.execute("create or replace table target(id integer, ta string, tb integer)"); - statement.execute("create or replace table source(id integer, sa string, sb integer)"); - statement.execute("insert into target values(1, 'str', 1)"); - statement.execute("insert into target values(2, 'str', 2)"); - statement.execute("insert into target values(3, 'str', 3)"); - statement.execute("insert into source values(1, 'str1', 11)"); - statement.execute("insert into source values(2, 'str2', 22)"); - statement.execute("insert into source values(3, 'str3', 33)"); - - int updateCount = statement.executeUpdate(mergeSQL); - - assertEquals(1, updateCount); - - statement.execute("drop table if exists target"); - statement.execute("drop table if exists source"); - statement.close(); - connection.close(); + try (Connection connection = getConnection()) { + String mergeSQL = + "merge into target using source on target.id = source.id " + + "when matched and source.sb =22 then update set ta = 'newStr' " + + "when not matched then insert (ta, tb) values (source.sa, source.sb)"; + try (Statement statement = connection.createStatement()) { + + try { + statement.execute("create or replace table target(id integer, ta string, tb integer)"); + statement.execute("create or replace table source(id integer, sa string, sb integer)"); + statement.execute("insert into target values(1, 'str', 1)"); + statement.execute("insert into target values(2, 'str', 2)"); + statement.execute("insert into target values(3, 'str', 3)"); + statement.execute("insert into source values(1, 'str1', 11)"); + statement.execute("insert into source values(2, 'str2', 22)"); + statement.execute("insert into source values(3, 'str3', 33)"); + + int updateCount = statement.executeUpdate(mergeSQL); + + assertEquals(1, updateCount); + } finally { + statement.execute("drop table if exists target"); + statement.execute("drop table if exists source"); + } + } + } } /** @@ -264,164 +262,176 @@ public void testExecuteMerge() throws SQLException { @Test public void testAutogenerateKey() throws Throwable { try (Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - statement.execute("create or replace table t(c1 int)"); - statement.execute("insert into t values(1)", Statement.NO_GENERATED_KEYS); - try { - statement.execute("insert into t values(2)", Statement.RETURN_GENERATED_KEYS); - fail("no autogenerate key is supported"); - } catch (SQLFeatureNotSupportedException ex) { - // nop + try (Statement statement = connection.createStatement()) { + statement.execute("create or replace table t(c1 int)"); + statement.execute("insert into t values(1)", Statement.NO_GENERATED_KEYS); + try { + statement.execute("insert into t values(2)", Statement.RETURN_GENERATED_KEYS); + fail("no autogenerate key is supported"); + } catch (SQLFeatureNotSupportedException ex) { + // nop + } + // empty result + try (ResultSet rset = statement.getGeneratedKeys()) { + assertFalse(rset.next()); + } } - // empty result - ResultSet rset = statement.getGeneratedKeys(); - assertFalse(rset.next()); - rset.close(); } } @Test public void testExecuteMultiInsert() throws SQLException { - Connection connection = getConnection(); - String multiInsertionSQL = - " insert all " - + "into foo " - + "into foo1 " - + "into bar (b1, b2, b3) values (s3, s2, s1) " - + "select s1, s2, s3 from source"; - - Statement statement = connection.createStatement(); - assertFalse( - statement.execute("create or replace table foo (f1 integer, f2 integer, f3 integer)")); - assertFalse( - statement.execute("create or replace table foo1 (f1 integer, f2 integer, f3 integer)")); - assertFalse( - statement.execute("create or replace table bar (b1 integer, b2 integer, b3 integer)")); - assertFalse( - statement.execute("create or replace table source(s1 integer, s2 integer, s3 integer)")); - assertFalse(statement.execute("insert into source values(1, 2, 3)")); - assertFalse(statement.execute("insert into source values(11, 22, 33)")); - assertFalse(statement.execute("insert into source values(111, 222, 333)")); - - int updateCount = statement.executeUpdate(multiInsertionSQL); - assertEquals(9, updateCount); - - statement.execute("drop table if exists foo"); - statement.execute("drop table if exists foo1"); - statement.execute("drop table if exists bar"); - statement.execute("drop table if exists source"); - - statement.close(); - connection.close(); + try (Connection connection = getConnection()) { + String multiInsertionSQL = + " insert all " + + "into foo " + + "into foo1 " + + "into bar (b1, b2, b3) values (s3, s2, s1) " + + "select s1, s2, s3 from source"; + + try (Statement statement = connection.createStatement()) { + try { + assertFalse( + statement.execute( + "create or replace table foo (f1 integer, f2 integer, f3 integer)")); + assertFalse( + statement.execute( + "create or replace table foo1 (f1 integer, f2 integer, f3 integer)")); + assertFalse( + statement.execute( + "create or replace table bar (b1 integer, b2 integer, b3 integer)")); + assertFalse( + statement.execute( + "create or replace table source(s1 integer, s2 integer, s3 integer)")); + assertFalse(statement.execute("insert into source values(1, 2, 3)")); + assertFalse(statement.execute("insert into source values(11, 22, 33)")); + assertFalse(statement.execute("insert into source values(111, 222, 333)")); + + int updateCount = statement.executeUpdate(multiInsertionSQL); + assertEquals(9, updateCount); + } finally { + statement.execute("drop table if exists foo"); + statement.execute("drop table if exists foo1"); + statement.execute("drop table if exists bar"); + statement.execute("drop table if exists source"); + } + } + } } @Test public void testExecuteBatch() throws Exception { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - - connection.setAutoCommit(false); - // mixed of ddl/dml in batch - statement.addBatch("create or replace table test_batch(a string, b integer)"); - statement.addBatch("insert into test_batch values('str1', 1), ('str2', 2)"); - statement.addBatch( - "update test_batch set test_batch.b = src.b + 5 from " - + "(select 'str1' as a, 2 as b) src where test_batch.a = src.a"); - - int[] rowCounts = statement.executeBatch(); - connection.commit(); - - assertThat(rowCounts.length, is(3)); - assertThat(rowCounts[0], is(0)); - assertThat(rowCounts[1], is(2)); - assertThat(rowCounts[2], is(1)); - - List batchQueryIDs = statement.unwrap(SnowflakeStatement.class).getBatchQueryIDs(); - assertEquals(3, batchQueryIDs.size()); - assertEquals(statement.unwrap(SnowflakeStatement.class).getQueryID(), batchQueryIDs.get(2)); - - ResultSet resultSet = statement.executeQuery("select * from test_batch order by b asc"); - resultSet.next(); - assertThat(resultSet.getInt("B"), is(2)); - resultSet.next(); - assertThat(resultSet.getInt("B"), is(7)); - statement.clearBatch(); - - // one of the batch is query instead of ddl/dml - // it should continuing processing - try { - statement.addBatch("insert into test_batch values('str3', 3)"); - statement.addBatch("select * from test_batch"); - statement.addBatch("select * from test_batch_not_exist"); - statement.addBatch("insert into test_batch values('str4', 4)"); - statement.executeBatch(); - fail(); - } catch (BatchUpdateException e) { - rowCounts = e.getUpdateCounts(); - assertThat(e.getErrorCode(), is(ERROR_CODE_DOMAIN_OBJECT_DOES_NOT_EXIST)); - assertThat(rowCounts[0], is(1)); - assertThat(rowCounts[1], is(Statement.SUCCESS_NO_INFO)); - assertThat(rowCounts[2], is(Statement.EXECUTE_FAILED)); - assertThat(rowCounts[3], is(1)); - - connection.rollback(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + connection.setAutoCommit(false); + // mixed of ddl/dml in batch + statement.addBatch("create or replace table test_batch(a string, b integer)"); + statement.addBatch("insert into test_batch values('str1', 1), ('str2', 2)"); + statement.addBatch( + "update test_batch set test_batch.b = src.b + 5 from " + + "(select 'str1' as a, 2 as b) src where test_batch.a = src.a"); + + int[] rowCounts = statement.executeBatch(); + connection.commit(); + + assertThat(rowCounts.length, is(3)); + assertThat(rowCounts[0], is(0)); + assertThat(rowCounts[1], is(2)); + assertThat(rowCounts[2], is(1)); + + List batchQueryIDs = statement.unwrap(SnowflakeStatement.class).getBatchQueryIDs(); + assertEquals(3, batchQueryIDs.size()); + assertEquals(statement.unwrap(SnowflakeStatement.class).getQueryID(), batchQueryIDs.get(2)); + + try (ResultSet resultSet = + statement.executeQuery("select * from test_batch order by b asc")) { + resultSet.next(); + assertThat(resultSet.getInt("B"), is(2)); + resultSet.next(); + assertThat(resultSet.getInt("B"), is(7)); + statement.clearBatch(); + + // one of the batch is query instead of ddl/dml + // it should continuing processing + try { + statement.addBatch("insert into test_batch values('str3', 3)"); + statement.addBatch("select * from test_batch"); + statement.addBatch("select * from test_batch_not_exist"); + statement.addBatch("insert into test_batch values('str4', 4)"); + statement.executeBatch(); + fail(); + } catch (BatchUpdateException e) { + rowCounts = e.getUpdateCounts(); + assertThat(e.getErrorCode(), is(ERROR_CODE_DOMAIN_OBJECT_DOES_NOT_EXIST)); + assertThat(rowCounts[0], is(1)); + assertThat(rowCounts[1], is(Statement.SUCCESS_NO_INFO)); + assertThat(rowCounts[2], is(Statement.EXECUTE_FAILED)); + assertThat(rowCounts[3], is(1)); + + connection.rollback(); + } + + statement.clearBatch(); + + statement.addBatch( + "put file://" + + getFullPathFileInResource(TEST_DATA_FILE) + + " @%test_batch auto_compress=false"); + File tempFolder = tmpFolder.newFolder("test_downloads_folder"); + statement.addBatch("get @%test_batch file://" + tempFolder); + + rowCounts = statement.executeBatch(); + assertThat(rowCounts.length, is(2)); + assertThat(rowCounts[0], is(Statement.SUCCESS_NO_INFO)); + assertThat(rowCounts[0], is(Statement.SUCCESS_NO_INFO)); + statement.clearBatch(); + } + } finally { + statement.execute("drop table if exists test_batch"); + } } - - statement.clearBatch(); - - statement.addBatch( - "put file://" - + getFullPathFileInResource(TEST_DATA_FILE) - + " @%test_batch auto_compress=false"); - File tempFolder = tmpFolder.newFolder("test_downloads_folder"); - statement.addBatch("get @%test_batch file://" + tempFolder); - - rowCounts = statement.executeBatch(); - assertThat(rowCounts.length, is(2)); - assertThat(rowCounts[0], is(Statement.SUCCESS_NO_INFO)); - assertThat(rowCounts[0], is(Statement.SUCCESS_NO_INFO)); - statement.clearBatch(); - - statement.execute("drop table if exists test_batch"); - statement.close(); - connection.close(); } @Test public void testExecuteLargeBatch() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - /** - * Generate a table with several rows and 1 column named test_large_batch Note: to truly test - * that executeLargeBatch works with a number of rows greater than MAX_INT, replace rowcount => - * 15 in next code line with rowcount => 2147483648, or some other number larger than MAX_INT. - * Test will take about 15 minutes to run. - */ - statement.execute( - "create or replace table test_large_batch (a number) as (select * from (select 5 from table" - + "(generator(rowcount => 15)) v));"); - // update values in table so that all rows are updated - statement.addBatch("update test_large_batch set a = 7 where a = 5;"); - long[] rowsUpdated = statement.executeLargeBatch(); - assertThat(rowsUpdated.length, is(1)); - long testVal = 15L; - assertThat(rowsUpdated[0], is(testVal)); - statement.clearBatch(); - /** - * To test SQLException for integer overflow when using executeBatch() for row updates of larger - * than MAX_INT, uncomment the following lines of code. Test will take about 15 minutes to run. - * - *

statement.execute("create or replace table test_large_batch (a number) as (select * from - * (select 5 from table" + "(generator(rowcount => 2147483648)) v));"); - * statement.addBatch("update test_large_batch set a = 7 where a = 5;"); try { int[] rowsUpdated - * = statement.executeBatch(); fail(); } catch (SnowflakeSQLException e) { assertEquals((int) - * ErrorCode.EXECUTE_BATCH_INTEGER_OVERFLOW.getMessageCode(), e.getErrorCode()); - * assertEquals(ErrorCode.EXECUTE_BATCH_INTEGER_OVERFLOW.getSqlState(), e.getSQLState()); } - * statement.clearBatch(); - */ - statement.execute("drop table if exists test_large_batch"); - statement.close(); - connection.close(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + /** + * Generate a table with several rows and 1 column named test_large_batch Note: to truly test + * that executeLargeBatch works with a number of rows greater than MAX_INT, replace rowcount + * => 15 in next code line with rowcount => 2147483648, or some other number larger than + * MAX_INT. Test will take about 15 minutes to run. + */ + try { + statement.execute( + "create or replace table test_large_batch (a number) as (select * from (select 5 from table" + + "(generator(rowcount => 15)) v));"); + // update values in table so that all rows are updated + statement.addBatch("update test_large_batch set a = 7 where a = 5;"); + long[] rowsUpdated = statement.executeLargeBatch(); + assertThat(rowsUpdated.length, is(1)); + long testVal = 15L; + assertThat(rowsUpdated[0], is(testVal)); + statement.clearBatch(); + + /** + * To test SQLException for integer overflow when using executeBatch() for row updates of + * larger than MAX_INT, uncomment the following lines of code. Test will take about 15 + * minutes to run. + * + *

statement.execute("create or replace table test_large_batch (a number) as (select * + * from (select 5 from table" + "(generator(rowcount => 2147483648)) v));"); + * statement.addBatch("update test_large_batch set a = 7 where a = 5;"); try { int[] + * rowsUpdated = statement.executeBatch(); fail(); } catch (SnowflakeSQLException e) { + * assertEquals((int) ErrorCode.EXECUTE_BATCH_INTEGER_OVERFLOW.getMessageCode(), + * e.getErrorCode()); assertEquals(ErrorCode.EXECUTE_BATCH_INTEGER_OVERFLOW.getSqlState(), + * e.getSQLState()); } statement.clearBatch(); + */ + } finally { + statement.execute("drop table if exists test_large_batch"); + } + } } /** @@ -433,7 +443,6 @@ public void testExecuteLargeBatch() throws SQLException { @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testExecuteUpdateZeroCount() throws SQLException { try (Connection connection = getConnection()) { - String[] testCommands = { "use role accountadmin", "use database testdb", @@ -463,11 +472,12 @@ public void testExecuteUpdateZeroCount() throws SQLException { statement.close(); } } finally { - Statement statement = connection.createStatement(); - statement.execute("use role accountadmin"); - statement.execute("drop table if exists testExecuteUpdate"); - statement.execute("drop role if exists testrole"); - statement.execute("drop user if exists testuser"); + try (Statement statement = connection.createStatement()) { + statement.execute("use role accountadmin"); + statement.execute("drop table if exists testExecuteUpdate"); + statement.execute("drop role if exists testrole"); + statement.execute("drop user if exists testuser"); + } } } } @@ -475,27 +485,27 @@ public void testExecuteUpdateZeroCount() throws SQLException { @Test public void testExecuteUpdateFail() throws Exception { try (Connection connection = getConnection()) { + try (Statement statement = connection.createStatement()) { + String[] testCommands = { + "list @~", + "ls @~", + "remove @~/testfile", + "rm @~/testfile", + "select 1", + "show databases", + "desc database " + AbstractDriverIT.getConnectionParameters().get("database") + }; - String[] testCommands = { - "list @~", - "ls @~", - "remove @~/testfile", - "rm @~/testfile", - "select 1", - "show databases", - "desc database " + AbstractDriverIT.getConnectionParameters().get("database") - }; - - for (String testCommand : testCommands) { - try { - Statement statement = connection.createStatement(); - statement.executeUpdate(testCommand); - fail("TestCommand: " + testCommand + " is expected to be failed to execute"); - } catch (SQLException e) { - assertThat( - testCommand, - e.getErrorCode(), - is(ErrorCode.UNSUPPORTED_STATEMENT_TYPE_IN_EXECUTION_API.getMessageCode())); + for (String testCommand : testCommands) { + try { + statement.executeUpdate(testCommand); + fail("TestCommand: " + testCommand + " is expected to be failed to execute"); + } catch (SQLException e) { + assertThat( + testCommand, + e.getErrorCode(), + is(ErrorCode.UNSUPPORTED_STATEMENT_TYPE_IN_EXECUTION_API.getMessageCode())); + } } } } @@ -503,85 +513,81 @@ public void testExecuteUpdateFail() throws Exception { @Test public void testTelemetryBatch() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - - ResultSet rs; - String sqlSelect = "select seq4() from table(generator(rowcount=>3))"; - statement.execute(sqlSelect); - - rs = statement.getResultSet(); - assertEquals(3, getSizeOfResultSet(rs)); - assertEquals(-1, statement.getUpdateCount()); - assertEquals(-1L, statement.getLargeUpdateCount()); + Telemetry telemetryClient = null; + try (Connection connection = getConnection()) { + try (Statement statement = connection.createStatement()) { - rs = statement.executeQuery(sqlSelect); - assertEquals(3, getSizeOfResultSet(rs)); - rs.close(); + String sqlSelect = "select seq4() from table(generator(rowcount=>3))"; + statement.execute(sqlSelect); - Telemetry telemetryClient = - ((SnowflakeStatementV1) statement).connection.getSfSession().getTelemetryClient(); + try (ResultSet rs = statement.getResultSet()) { + assertEquals(3, getSizeOfResultSet(rs)); + assertEquals(-1, statement.getUpdateCount()); + assertEquals(-1L, statement.getLargeUpdateCount()); + } - // there should be logs ready to be sent - assertTrue(((TelemetryClient) telemetryClient).bufferSize() > 0); + try (ResultSet rs = statement.executeQuery(sqlSelect)) { + assertEquals(3, getSizeOfResultSet(rs)); + } - statement.close(); + telemetryClient = + ((SnowflakeStatementV1) statement).connection.getSfSession().getTelemetryClient(); - // closing the statement should flush the buffer, however, flush is async, - // sleep some time before check buffer size - try { - Thread.sleep(1000); - } catch (Throwable e) { + // there should be logs ready to be sent + assertTrue(((TelemetryClient) telemetryClient).bufferSize() > 0); + } + // closing the statement should flush the buffer, however, flush is async, + // sleep some time before check buffer size + try { + Thread.sleep(1000); + } catch (Throwable e) { + } + assertEquals(((TelemetryClient) telemetryClient).bufferSize(), 0); } - assertEquals(((TelemetryClient) telemetryClient).bufferSize(), 0); - connection.close(); } @Test public void testMultiStmtNotEnabled() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - String multiStmtQuery = - "create or replace temporary table test_multi (cola int);\n" - + "insert into test_multi VALUES (1), (2);\n" - + "select cola from test_multi order by cola asc"; - - try { - statement.execute(multiStmtQuery); - fail("Using a multi-statement query without the parameter set should fail"); - } catch (SnowflakeSQLException ex) { - assertEquals(SqlState.FEATURE_NOT_SUPPORTED, ex.getSQLState()); - } + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + String multiStmtQuery = + "create or replace temporary table test_multi (cola int);\n" + + "insert into test_multi VALUES (1), (2);\n" + + "select cola from test_multi order by cola asc"; - statement.close(); - connection.close(); + try { + statement.execute(multiStmtQuery); + fail("Using a multi-statement query without the parameter set should fail"); + } catch (SnowflakeSQLException ex) { + assertEquals(SqlState.FEATURE_NOT_SUPPORTED, ex.getSQLState()); + } + } } @Test public void testCallStoredProcedure() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - statement.execute( - "create or replace procedure SP()\n" - + "returns string not null\n" - + "language javascript\n" - + "as $$\n" - + " snowflake.execute({sqlText:'select seq4() from table(generator(rowcount=>5))'});\n" - + " return 'done';\n" - + "$$"); - - assertTrue(statement.execute("call SP()")); - ResultSet rs = statement.getResultSet(); - assertNotNull(rs); - assertTrue(rs.next()); - assertEquals("done", rs.getString(1)); - assertFalse(rs.next()); - assertFalse(statement.getMoreResults()); - assertEquals(-1, statement.getUpdateCount()); - assertEquals(-1L, statement.getLargeUpdateCount()); - - statement.close(); - connection.close(); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + statement.execute( + "create or replace procedure SP()\n" + + "returns string not null\n" + + "language javascript\n" + + "as $$\n" + + " snowflake.execute({sqlText:'select seq4() from table(generator(rowcount=>5))'});\n" + + " return 'done';\n" + + "$$"); + + assertTrue(statement.execute("call SP()")); + try (ResultSet rs = statement.getResultSet()) { + assertNotNull(rs); + assertTrue(rs.next()); + assertEquals("done", rs.getString(1)); + assertFalse(rs.next()); + assertFalse(statement.getMoreResults()); + assertEquals(-1, statement.getUpdateCount()); + assertEquals(-1L, statement.getLargeUpdateCount()); + } + } } @Test @@ -613,19 +619,20 @@ public void testCreateStatementWithParameters() throws Throwable { @Test public void testUnwrapper() throws Throwable { try (Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - if (statement.isWrapperFor(SnowflakeStatementV1.class)) { - statement.execute("select 1"); - SnowflakeStatement sfstatement = statement.unwrap(SnowflakeStatement.class); - assertNotNull(sfstatement.getQueryID()); - } else { - fail("should be able to unwrap"); - } - try { - statement.unwrap(SnowflakeConnectionV1.class); - fail("should fail to cast"); - } catch (SQLException ex) { - // nop + try (Statement statement = connection.createStatement()) { + if (statement.isWrapperFor(SnowflakeStatementV1.class)) { + statement.execute("select 1"); + SnowflakeStatement sfstatement = statement.unwrap(SnowflakeStatement.class); + assertNotNull(sfstatement.getQueryID()); + } else { + fail("should be able to unwrap"); + } + try { + statement.unwrap(SnowflakeConnectionV1.class); + fail("should fail to cast"); + } catch (SQLException ex) { + // nop + } } } } diff --git a/src/test/java/net/snowflake/client/jdbc/StatementLargeUpdateIT.java b/src/test/java/net/snowflake/client/jdbc/StatementLargeUpdateIT.java index cdd3527f7..d041b1694 100644 --- a/src/test/java/net/snowflake/client/jdbc/StatementLargeUpdateIT.java +++ b/src/test/java/net/snowflake/client/jdbc/StatementLargeUpdateIT.java @@ -13,18 +13,21 @@ public class StatementLargeUpdateIT extends BaseJDBCTest { @Test public void testLargeUpdate() throws Throwable { - try (Connection con = getConnection()) { + try (Connection con = getConnection(); + Statement statement = con.createStatement()) { long expectedUpdateRows = (long) Integer.MAX_VALUE + 10L; - con.createStatement().execute("create or replace table test_large_update(c1 boolean)"); - Statement st = con.createStatement(); - long updatedRows = - st.executeLargeUpdate( - "insert into test_large_update select true from table(generator(rowcount=>" - + expectedUpdateRows - + "))"); - assertEquals(expectedUpdateRows, updatedRows); - assertEquals(expectedUpdateRows, st.getLargeUpdateCount()); - con.createStatement().execute("drop table if exists test_large_update"); + try { + statement.execute("create or replace table test_large_update(c1 boolean)"); + long updatedRows = + statement.executeLargeUpdate( + "insert into test_large_update select true from table(generator(rowcount=>" + + expectedUpdateRows + + "))"); + assertEquals(expectedUpdateRows, updatedRows); + assertEquals(expectedUpdateRows, statement.getLargeUpdateCount()); + } finally { + statement.execute("drop table if exists test_large_update"); + } } } } diff --git a/src/test/java/net/snowflake/client/jdbc/StatementLatestIT.java b/src/test/java/net/snowflake/client/jdbc/StatementLatestIT.java index 0a003957c..66bf17373 100644 --- a/src/test/java/net/snowflake/client/jdbc/StatementLatestIT.java +++ b/src/test/java/net/snowflake/client/jdbc/StatementLatestIT.java @@ -46,9 +46,9 @@ public class StatementLatestIT extends BaseJDBCTest { public static Connection getConnection() throws SQLException { Connection conn = BaseJDBCTest.getConnection(); - Statement stmt = conn.createStatement(); - stmt.execute("alter session set jdbc_query_result_format = '" + queryResultFormat + "'"); - stmt.close(); + try (Statement stmt = conn.createStatement()) { + stmt.execute("alter session set jdbc_query_result_format = '" + queryResultFormat + "'"); + } return conn; } @@ -56,111 +56,119 @@ public static Connection getConnection() throws SQLException { @Test public void testExecuteCreateAndDrop() throws SQLException { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); - - boolean success = statement.execute("create or replace table test_create(colA integer)"); - assertFalse(success); - assertEquals(0, statement.getUpdateCount()); - assertEquals(0, statement.getLargeUpdateCount()); - assertNull(statement.getResultSet()); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { - int rowCount = statement.executeUpdate("create or replace table test_create_2(colA integer)"); - assertEquals(0, rowCount); - assertEquals(0, statement.getUpdateCount()); + boolean success = statement.execute("create or replace table test_create(colA integer)"); + assertFalse(success); + assertEquals(0, statement.getUpdateCount()); + assertEquals(0, statement.getLargeUpdateCount()); + assertNull(statement.getResultSet()); - success = statement.execute("drop table if exists TEST_CREATE"); - assertFalse(success); - assertEquals(0, statement.getUpdateCount()); - assertEquals(0, statement.getLargeUpdateCount()); - assertNull(statement.getResultSet()); + int rowCount = statement.executeUpdate("create or replace table test_create_2(colA integer)"); + assertEquals(0, rowCount); + assertEquals(0, statement.getUpdateCount()); - rowCount = statement.executeUpdate("drop table if exists TEST_CREATE_2"); - assertEquals(0, rowCount); - assertEquals(0, statement.getUpdateCount()); - assertEquals(0, statement.getLargeUpdateCount()); - assertNull(statement.getResultSet()); + success = statement.execute("drop table if exists TEST_CREATE"); + assertFalse(success); + assertEquals(0, statement.getUpdateCount()); + assertEquals(0, statement.getLargeUpdateCount()); + assertNull(statement.getResultSet()); - statement.close(); - connection.close(); + rowCount = statement.executeUpdate("drop table if exists TEST_CREATE_2"); + assertEquals(0, rowCount); + assertEquals(0, statement.getUpdateCount()); + assertEquals(0, statement.getLargeUpdateCount()); + assertNull(statement.getResultSet()); + } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testCopyAndUpload() throws Exception { - - Connection connection = null; - Statement statement = null; File tempFolder = tmpFolder.newFolder("test_downloads_folder"); List accounts = Arrays.asList(null, "s3testaccount", "azureaccount", "gcpaccount"); for (int i = 0; i < accounts.size(); i++) { String fileName = "test_copy.csv"; URL resource = StatementIT.class.getResource(fileName); - connection = getConnection(accounts.get(i)); - statement = connection.createStatement(); - - statement.execute("create or replace table test_copy(c1 number, c2 number, c3 string)"); - assertEquals(0, statement.getUpdateCount()); - assertEquals(0, statement.getLargeUpdateCount()); - - String path = resource.getFile(); - - // put files - ResultSet rset = statement.executeQuery("PUT file://" + path + " @%test_copy"); - try { - rset.getString(1); - fail("Should raise No row found exception, because no next() is called."); - } catch (SQLException ex) { - assertThat( - "No row found error", ex.getErrorCode(), equalTo(ROW_DOES_NOT_EXIST.getMessageCode())); - } - int cnt = 0; - while (rset.next()) { - assertThat("uploaded file name", rset.getString(1), equalTo(fileName)); - ++cnt; + try (Connection connection = getConnection(accounts.get(i)); + Statement statement = connection.createStatement()) { + try { + statement.execute("create or replace table test_copy(c1 number, c2 number, c3 string)"); + assertEquals(0, statement.getUpdateCount()); + assertEquals(0, statement.getLargeUpdateCount()); + + String path = resource.getFile(); + + // put files + try (ResultSet rset = statement.executeQuery("PUT file://" + path + " @%test_copy")) { + try { + rset.getString(1); + fail("Should raise No row found exception, because no next() is called."); + } catch (SQLException ex) { + assertThat( + "No row found error", + ex.getErrorCode(), + equalTo(ROW_DOES_NOT_EXIST.getMessageCode())); + } + int cnt = 0; + while (rset.next()) { + assertThat("uploaded file name", rset.getString(1), equalTo(fileName)); + ++cnt; + } + assertEquals(0, statement.getUpdateCount()); + assertEquals(0, statement.getLargeUpdateCount()); + assertThat("number of files", cnt, equalTo(1)); + int numRows = statement.executeUpdate("copy into test_copy"); + assertEquals(2, numRows); + assertEquals(2, statement.getUpdateCount()); + assertEquals(2L, statement.getLargeUpdateCount()); + + // get files + statement.executeQuery( + "get @%test_copy 'file://" + tempFolder.getCanonicalPath() + "' parallel=8"); + + // Make sure that the downloaded file exists, it should be gzip compressed + File downloaded = + new File(tempFolder.getCanonicalPath() + File.separator + fileName + ".gz"); + assert (downloaded.exists()); + } + // unzip the new file + Process p = + Runtime.getRuntime() + .exec( + "gzip -d " + + tempFolder.getCanonicalPath() + + File.separator + + fileName + + ".gz"); + p.waitFor(); + File newCopy = new File(tempFolder.getCanonicalPath() + File.separator + fileName); + // check that the get worked by uploading new file again to a different table and + // comparing it + // to original table + statement.execute("create or replace table test_copy_2(c1 number, c2 number, c3 string)"); + + // put copy of file + statement.executeQuery("PUT file://" + newCopy.getPath() + " @%test_copy_2"); + // assert that the result set is empty when you subtract each table from the other + try (ResultSet rset = + statement.executeQuery( + "select * from @%test_copy minus select * from @%test_copy_2")) { + assertFalse(rset.next()); + } + try (ResultSet rset = + statement.executeQuery( + "select * from @%test_copy_2 minus select * from @%test_copy")) { + assertFalse(rset.next()); + } + } finally { + statement.execute("drop table if exists test_copy"); + statement.execute("drop table if exists test_copy_2"); + } } - assertEquals(0, statement.getUpdateCount()); - assertEquals(0, statement.getLargeUpdateCount()); - assertThat("number of files", cnt, equalTo(1)); - int numRows = statement.executeUpdate("copy into test_copy"); - assertEquals(2, numRows); - assertEquals(2, statement.getUpdateCount()); - assertEquals(2L, statement.getLargeUpdateCount()); - - // get files - statement.executeQuery( - "get @%test_copy 'file://" + tempFolder.getCanonicalPath() + "' parallel=8"); - - // Make sure that the downloaded file exists, it should be gzip compressed - File downloaded = new File(tempFolder.getCanonicalPath() + File.separator + fileName + ".gz"); - assert (downloaded.exists()); - - // unzip the new file - Process p = - Runtime.getRuntime() - .exec("gzip -d " + tempFolder.getCanonicalPath() + File.separator + fileName + ".gz"); - p.waitFor(); - File newCopy = new File(tempFolder.getCanonicalPath() + File.separator + fileName); - - // check that the get worked by uploading new file again to a different table and comparing it - // to original table - statement.execute("create or replace table test_copy_2(c1 number, c2 number, c3 string)"); - - // put copy of file - rset = statement.executeQuery("PUT file://" + newCopy.getPath() + " @%test_copy_2"); - // assert that the result set is empty when you subtract each table from the other - rset = statement.executeQuery("select * from @%test_copy minus select * from @%test_copy_2"); - assertFalse(rset.next()); - rset = statement.executeQuery("select * from @%test_copy_2 minus select * from @%test_copy"); - assertFalse(rset.next()); - - statement.execute("drop table if exists test_copy"); - statement.execute("drop table if exists test_copy_2"); } - - statement.close(); - connection.close(); } /** @@ -170,36 +178,34 @@ public void testCopyAndUpload() throws Exception { */ @Test public void testExecuteOpenResultSets() throws SQLException { - Connection con = getConnection(); - Statement statement = con.createStatement(); - ResultSet resultSet; + try (Connection con = getConnection()) { + try (Statement statement = con.createStatement()) { + for (int i = 0; i < 10; i++) { + statement.execute("select 1"); + statement.getResultSet(); + } - for (int i = 0; i < 10; i++) { - statement.execute("select 1"); - statement.getResultSet(); - } + assertEquals(9, statement.unwrap(SnowflakeStatementV1.class).getOpenResultSets().size()); + } - assertEquals(9, statement.unwrap(SnowflakeStatementV1.class).getOpenResultSets().size()); - statement.close(); + try (Statement statement = con.createStatement()) { + for (int i = 0; i < 10; i++) { + statement.execute("select 1"); + ResultSet resultSet = statement.getResultSet(); + resultSet.close(); + } - statement = con.createStatement(); - for (int i = 0; i < 10; i++) { - statement.execute("select 1"); - resultSet = statement.getResultSet(); - resultSet.close(); + assertEquals(0, statement.unwrap(SnowflakeStatementV1.class).getOpenResultSets().size()); + } } - - assertEquals(0, statement.unwrap(SnowflakeStatementV1.class).getOpenResultSets().size()); - - statement.close(); - con.close(); } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testPreparedStatementLogging() throws SQLException { - try (Connection con = getConnection()) { - try (Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); + Statement stmt = con.createStatement()) { + try { SFSession sfSession = con.unwrap(SnowflakeConnectionV1.class).getSfSession(); sfSession.setPreparedStatementLogging(true); @@ -229,7 +235,7 @@ public void testPreparedStatementLogging() throws SQLException { int bindValues = BindUploader.arrayBindValueCount(bindings); assertEquals(8008, bindValues); pstatement.executeBatch(); - + } finally { stmt.execute("drop table if exists mytab"); } } @@ -252,17 +258,16 @@ public void testSchemaWith255CharactersDoesNotCauseException() throws SQLExcepti /** Added in > 3.14.4 */ @Test public void testQueryIdIsSetOnFailedQueryExecute() throws SQLException { - try (Connection con = getConnection()) { - try (Statement stmt = con.createStatement()) { - assertNull(stmt.unwrap(SnowflakeStatement.class).getQueryID()); - try { - stmt.execute("use database not_existing_database"); - fail("Statement should fail with exception"); - } catch (SnowflakeSQLException e) { - String queryID = stmt.unwrap(SnowflakeStatement.class).getQueryID(); - TestUtil.assertValidQueryId(queryID); - assertEquals(queryID, e.getQueryId()); - } + try (Connection con = getConnection(); + Statement stmt = con.createStatement()) { + assertNull(stmt.unwrap(SnowflakeStatement.class).getQueryID()); + try { + stmt.execute("use database not_existing_database"); + fail("Statement should fail with exception"); + } catch (SnowflakeSQLException e) { + String queryID = stmt.unwrap(SnowflakeStatement.class).getQueryID(); + TestUtil.assertValidQueryId(queryID); + assertEquals(queryID, e.getQueryId()); } } } @@ -270,17 +275,16 @@ public void testQueryIdIsSetOnFailedQueryExecute() throws SQLException { /** Added in > 3.14.4 */ @Test public void testQueryIdIsSetOnFailedExecuteUpdate() throws SQLException { - try (Connection con = getConnection()) { - try (Statement stmt = con.createStatement()) { - assertNull(stmt.unwrap(SnowflakeStatement.class).getQueryID()); - try { - stmt.executeUpdate("update not_existing_table set a = 1 where id = 42"); - fail("Statement should fail with exception"); - } catch (SnowflakeSQLException e) { - String queryID = stmt.unwrap(SnowflakeStatement.class).getQueryID(); - TestUtil.assertValidQueryId(queryID); - assertEquals(queryID, e.getQueryId()); - } + try (Connection con = getConnection(); + Statement stmt = con.createStatement()) { + assertNull(stmt.unwrap(SnowflakeStatement.class).getQueryID()); + try { + stmt.executeUpdate("update not_existing_table set a = 1 where id = 42"); + fail("Statement should fail with exception"); + } catch (SnowflakeSQLException e) { + String queryID = stmt.unwrap(SnowflakeStatement.class).getQueryID(); + TestUtil.assertValidQueryId(queryID); + assertEquals(queryID, e.getQueryId()); } } } @@ -288,17 +292,16 @@ public void testQueryIdIsSetOnFailedExecuteUpdate() throws SQLException { /** Added in > 3.14.4 */ @Test public void testQueryIdIsSetOnFailedExecuteQuery() throws SQLException { - try (Connection con = getConnection()) { - try (Statement stmt = con.createStatement()) { - assertNull(stmt.unwrap(SnowflakeStatement.class).getQueryID()); - try { - stmt.executeQuery("select * from not_existing_table"); - fail("Statement should fail with exception"); - } catch (SnowflakeSQLException e) { - String queryID = stmt.unwrap(SnowflakeStatement.class).getQueryID(); - TestUtil.assertValidQueryId(queryID); - assertEquals(queryID, e.getQueryId()); - } + try (Connection con = getConnection(); + Statement stmt = con.createStatement()) { + assertNull(stmt.unwrap(SnowflakeStatement.class).getQueryID()); + try { + stmt.executeQuery("select * from not_existing_table"); + fail("Statement should fail with exception"); + } catch (SnowflakeSQLException e) { + String queryID = stmt.unwrap(SnowflakeStatement.class).getQueryID(); + TestUtil.assertValidQueryId(queryID); + assertEquals(queryID, e.getQueryId()); } } } diff --git a/src/test/java/net/snowflake/client/jdbc/StreamIT.java b/src/test/java/net/snowflake/client/jdbc/StreamIT.java index f36fd5d34..d1762904d 100644 --- a/src/test/java/net/snowflake/client/jdbc/StreamIT.java +++ b/src/test/java/net/snowflake/client/jdbc/StreamIT.java @@ -32,40 +32,32 @@ public class StreamIT extends BaseJDBCTest { @Test public void testUploadStream() throws Throwable { final String DEST_PREFIX = TEST_UUID + "/testUploadStream"; - Connection connection = null; - Statement statement = null; - try { - connection = getConnection(); - - statement = connection.createStatement(); - - FileBackedOutputStream outputStream = new FileBackedOutputStream(1000000); - outputStream.write("hello".getBytes(StandardCharsets.UTF_8)); - outputStream.flush(); - - // upload the data to user stage under testUploadStream with name hello.txt - connection - .unwrap(SnowflakeConnection.class) - .uploadStream( - "~", DEST_PREFIX, outputStream.asByteSource().openStream(), "hello.txt", false); - - // select from the file to make sure the data is uploaded - ResultSet rset = statement.executeQuery("SELECT $1 FROM @~/" + DEST_PREFIX); - - String ret = null; - - while (rset.next()) { - ret = rset.getString(1); - } - rset.close(); - assertEquals("Unexpected string value: " + ret + " expect: hello", "hello", ret); - } finally { - if (statement != null) { + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + FileBackedOutputStream outputStream = new FileBackedOutputStream(1000000); + outputStream.write("hello".getBytes(StandardCharsets.UTF_8)); + outputStream.flush(); + + // upload the data to user stage under testUploadStream with name hello.txt + connection + .unwrap(SnowflakeConnection.class) + .uploadStream( + "~", DEST_PREFIX, outputStream.asByteSource().openStream(), "hello.txt", false); + + // select from the file to make sure the data is uploaded + try (ResultSet rset = statement.executeQuery("SELECT $1 FROM @~/" + DEST_PREFIX)) { + String ret = null; + + while (rset.next()) { + ret = rset.getString(1); + } + assertEquals("Unexpected string value: " + ret + " expect: hello", "hello", ret); + } + } finally { statement.execute("rm @~/" + DEST_PREFIX); - statement.close(); } - closeSQLObjects(statement, connection); } } @@ -80,38 +72,37 @@ public void testUploadStream() throws Throwable { @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testDownloadStream() throws Throwable { final String DEST_PREFIX = TEST_UUID + "/testUploadStream"; - Connection connection = null; - Statement statement = null; List supportedAccounts = Arrays.asList("s3testaccount", "azureaccount"); for (String accountName : supportedAccounts) { - try { - connection = getConnection(accountName); - statement = connection.createStatement(); - ResultSet rset = - statement.executeQuery( - "PUT file://" + getFullPathFileInResource(TEST_DATA_FILE) + " @~/" + DEST_PREFIX); - assertTrue(rset.next()); - assertEquals("UPLOADED", rset.getString(7)); - - InputStream out = - connection - .unwrap(SnowflakeConnection.class) - .downloadStream("~", DEST_PREFIX + "/" + TEST_DATA_FILE + ".gz", true); - StringWriter writer = new StringWriter(); - IOUtils.copy(out, writer, "UTF-8"); - String output = writer.toString(); - // the first 2 characters - assertEquals("1|", output.substring(0, 2)); - - // the number of lines - String[] lines = output.split("\n"); - assertEquals(28, lines.length); - } finally { - if (statement != null) { + try (Connection connection = getConnection(accountName); + Statement statement = connection.createStatement()) { + try { + try (ResultSet rset = + statement.executeQuery( + "PUT file://" + + getFullPathFileInResource(TEST_DATA_FILE) + + " @~/" + + DEST_PREFIX)) { + assertTrue(rset.next()); + assertEquals("UPLOADED", rset.getString(7)); + + InputStream out = + connection + .unwrap(SnowflakeConnection.class) + .downloadStream("~", DEST_PREFIX + "/" + TEST_DATA_FILE + ".gz", true); + StringWriter writer = new StringWriter(); + IOUtils.copy(out, writer, "UTF-8"); + String output = writer.toString(); + // the first 2 characters + assertEquals("1|", output.substring(0, 2)); + + // the number of lines + String[] lines = output.split("\n"); + assertEquals(28, lines.length); + } + } finally { statement.execute("rm @~/" + DEST_PREFIX); - statement.close(); } - closeSQLObjects(statement, connection); } } } @@ -119,42 +110,34 @@ public void testDownloadStream() throws Throwable { @Test public void testCompressAndUploadStream() throws Throwable { final String DEST_PREFIX = TEST_UUID + "/" + "testCompressAndUploadStream"; - Connection connection = null; - Statement statement = null; - ResultSet resultSet = null; - - try { - connection = getConnection(); - - statement = connection.createStatement(); - - FileBackedOutputStream outputStream = new FileBackedOutputStream(1000000); - outputStream.write("hello".getBytes(StandardCharsets.UTF_8)); - outputStream.flush(); - - // upload the data to user stage under testCompressAndUploadStream - // with name hello.txt - // upload the data to user stage under testUploadStream with name hello.txt - connection - .unwrap(SnowflakeConnectionV1.class) - .uploadStream( - "~", DEST_PREFIX, outputStream.asByteSource().openStream(), "hello.txt", true); - - // select from the file to make sure the data is uploaded - ResultSet rset = statement.executeQuery("SELECT $1 FROM @~/" + DEST_PREFIX); + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + FileBackedOutputStream outputStream = new FileBackedOutputStream(1000000); + outputStream.write("hello".getBytes(StandardCharsets.UTF_8)); + outputStream.flush(); + + // upload the data to user stage under testCompressAndUploadStream + // with name hello.txt + // upload the data to user stage under testUploadStream with name hello.txt + connection + .unwrap(SnowflakeConnectionV1.class) + .uploadStream( + "~", DEST_PREFIX, outputStream.asByteSource().openStream(), "hello.txt", true); + + // select from the file to make sure the data is uploaded + try (ResultSet rset = statement.executeQuery("SELECT $1 FROM @~/" + DEST_PREFIX)) { + + String ret = null; + while (rset.next()) { + ret = rset.getString(1); + } + assertEquals("Unexpected string value: " + ret + " expect: hello", "hello", ret); + } - String ret = null; - while (rset.next()) { - ret = rset.getString(1); - } - rset.close(); - assertEquals("Unexpected string value: " + ret + " expect: hello", "hello", ret); - } finally { - if (statement != null) { + } finally { statement.execute("rm @~/" + DEST_PREFIX); - statement.close(); } - closeSQLObjects(resultSet, statement, connection); } } } diff --git a/src/test/java/net/snowflake/client/jdbc/StreamLatestIT.java b/src/test/java/net/snowflake/client/jdbc/StreamLatestIT.java index f7e3d0d74..3ab179b70 100644 --- a/src/test/java/net/snowflake/client/jdbc/StreamLatestIT.java +++ b/src/test/java/net/snowflake/client/jdbc/StreamLatestIT.java @@ -47,58 +47,56 @@ public class StreamLatestIT extends BaseJDBCTest { */ @Test public void testUnusualStageName() throws Throwable { - Connection connection = getConnection(); - Statement statement = connection.createStatement(); + String ret = null; + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { - try { - statement.execute("CREATE or replace TABLE \"ice cream (nice)\" (types STRING)"); + try { + statement.execute("CREATE or replace TABLE \"ice cream (nice)\" (types STRING)"); - FileBackedOutputStream outputStream = new FileBackedOutputStream(1000000); - outputStream.write("hello".getBytes(StandardCharsets.UTF_8)); - outputStream.flush(); + FileBackedOutputStream outputStream = new FileBackedOutputStream(1000000); + outputStream.write("hello".getBytes(StandardCharsets.UTF_8)); + outputStream.flush(); - // upload the data to user stage under testUploadStream with name hello.txt - connection - .unwrap(SnowflakeConnection.class) - .uploadStream( - "'@%\"ice cream (nice)\"'", - null, outputStream.asByteSource().openStream(), "hello.txt", false); - - // select from the file to make sure the data is uploaded - ResultSet rset = statement.executeQuery("SELECT $1 FROM '@%\"ice cream (nice)\"/'"); - - String ret = null; - - while (rset.next()) { - ret = rset.getString(1); - } - rset.close(); - assertEquals("Unexpected string value: " + ret + " expect: hello", "hello", ret); - - statement.execute("CREATE or replace TABLE \"ice cream (nice)\" (types STRING)"); - - // upload the data to user stage under testUploadStream with name hello.txt - connection - .unwrap(SnowflakeConnection.class) - .uploadStream( - "$$@%\"ice cream (nice)\"$$", - null, outputStream.asByteSource().openStream(), "hello.txt", false); - - // select from the file to make sure the data is uploaded - rset = statement.executeQuery("SELECT $1 FROM $$@%\"ice cream (nice)\"/$$"); - - ret = null; - - while (rset.next()) { - ret = rset.getString(1); + // upload the data to user stage under testUploadStream with name hello.txt + connection + .unwrap(SnowflakeConnection.class) + .uploadStream( + "'@%\"ice cream (nice)\"'", + null, outputStream.asByteSource().openStream(), "hello.txt", false); + + // select from the file to make sure the data is uploaded + try (ResultSet rset = statement.executeQuery("SELECT $1 FROM '@%\"ice cream (nice)\"/'")) { + ret = null; + + while (rset.next()) { + ret = rset.getString(1); + } + assertEquals("Unexpected string value: " + ret + " expect: hello", "hello", ret); + } + statement.execute("CREATE or replace TABLE \"ice cream (nice)\" (types STRING)"); + + // upload the data to user stage under testUploadStream with name hello.txt + connection + .unwrap(SnowflakeConnection.class) + .uploadStream( + "$$@%\"ice cream (nice)\"$$", + null, outputStream.asByteSource().openStream(), "hello.txt", false); + + // select from the file to make sure the data is uploaded + try (ResultSet rset = + statement.executeQuery("SELECT $1 FROM $$@%\"ice cream (nice)\"/$$")) { + + ret = null; + + while (rset.next()) { + ret = rset.getString(1); + } + assertEquals("Unexpected string value: " + ret + " expect: hello", "hello", ret); + } + } finally { + statement.execute("DROP TABLE IF EXISTS \"ice cream (nice)\""); } - rset.close(); - assertEquals("Unexpected string value: " + ret + " expect: hello", "hello", ret); - - } finally { - statement.execute("DROP TABLE IF EXISTS \"ice cream (nice)\""); - statement.close(); - connection.close(); } } @@ -106,28 +104,25 @@ public void testUnusualStageName() throws Throwable { @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testDownloadToStreamBlobNotFoundGCS() throws SQLException { final String DEST_PREFIX = TEST_UUID + "/testUploadStream"; - Connection connection = null; - Statement statement = null; - try { - Properties paramProperties = new Properties(); - paramProperties.put("GCS_USE_DOWNSCOPED_CREDENTIAL", true); - connection = getConnection("gcpaccount", paramProperties); - statement = connection.createStatement(); - connection - .unwrap(SnowflakeConnection.class) - .downloadStream("~", DEST_PREFIX + "/abc.gz", true); - fail("should throw a storage provider exception for blob not found"); - } catch (Exception ex) { - assertTrue(ex instanceof SQLException); - assertTrue( - "Wrong exception message: " + ex.getMessage(), - ex.getMessage().matches(".*Blob.*not found in bucket.*")); - } finally { - if (statement != null) { + Properties paramProperties = new Properties(); + paramProperties.put("GCS_USE_DOWNSCOPED_CREDENTIAL", true); + + try (Connection connection = getConnection("gcpaccount", paramProperties); + Statement statement = connection.createStatement()) { + + try { + connection + .unwrap(SnowflakeConnection.class) + .downloadStream("~", DEST_PREFIX + "/abc.gz", true); + fail("should throw a storage provider exception for blob not found"); + } catch (Exception ex) { + assertTrue(ex instanceof SQLException); + assertTrue( + "Wrong exception message: " + ex.getMessage(), + ex.getMessage().matches(".*Blob.*not found in bucket.*")); + } finally { statement.execute("rm @~/" + DEST_PREFIX); - statement.close(); } - closeSQLObjects(statement, connection); } } @@ -135,121 +130,111 @@ public void testDownloadToStreamBlobNotFoundGCS() throws SQLException { @Ignore public void testDownloadToStreamGCSPresignedUrl() throws SQLException, IOException { final String DEST_PREFIX = "testUploadStream"; - Connection connection = null; - Statement statement = null; - connection = getConnection("gcpaccount"); - statement = connection.createStatement(); - statement.execute("create or replace stage testgcpstage"); - ResultSet rset = - statement.executeQuery( - "PUT file://" - + getFullPathFileInResource(TEST_DATA_FILE) - + " @testgcpstage/" - + DEST_PREFIX); - assertTrue(rset.next()); - assertEquals("Error message:" + rset.getString(8), "UPLOADED", rset.getString(7)); - - InputStream out = - connection - .unwrap(SnowflakeConnection.class) - .downloadStream("@testgcpstage", DEST_PREFIX + "/" + TEST_DATA_FILE + ".gz", true); - StringWriter writer = new StringWriter(); - IOUtils.copy(out, writer, "UTF-8"); - String output = writer.toString(); - // the first 2 characters - assertEquals("1|", output.substring(0, 2)); - // the number of lines - String[] lines = output.split("\n"); - assertEquals(28, lines.length); - - statement.execute("rm @~/" + DEST_PREFIX); - statement.close(); - closeSQLObjects(statement, connection); + try (Connection connection = getConnection("gcpaccount"); + Statement statement = connection.createStatement()) { + statement.execute("create or replace stage testgcpstage"); + try (ResultSet rset = + statement.executeQuery( + "PUT file://" + + getFullPathFileInResource(TEST_DATA_FILE) + + " @testgcpstage/" + + DEST_PREFIX)) { + assertTrue(rset.next()); + assertEquals("Error message:" + rset.getString(8), "UPLOADED", rset.getString(7)); + + InputStream out = + connection + .unwrap(SnowflakeConnection.class) + .downloadStream("@testgcpstage", DEST_PREFIX + "/" + TEST_DATA_FILE + ".gz", true); + StringWriter writer = new StringWriter(); + IOUtils.copy(out, writer, "UTF-8"); + String output = writer.toString(); + // the first 2 characters + assertEquals("1|", output.substring(0, 2)); + + // the number of lines + String[] lines = output.split("\n"); + assertEquals(28, lines.length); + } + statement.execute("rm @~/" + DEST_PREFIX); + } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class) public void testDownloadToStreamGCS() throws SQLException, IOException { final String DEST_PREFIX = TEST_UUID + "/testUploadStream"; - Connection connection = null; - Statement statement = null; Properties paramProperties = new Properties(); paramProperties.put("GCS_USE_DOWNSCOPED_CREDENTIAL", true); - try { - connection = getConnection("gcpaccount", paramProperties); - statement = connection.createStatement(); - ResultSet rset = - statement.executeQuery( - "PUT file://" + getFullPathFileInResource(TEST_DATA_FILE) + " @~/" + DEST_PREFIX); - assertTrue(rset.next()); - assertEquals("UPLOADED", rset.getString(7)); - - InputStream out = - connection - .unwrap(SnowflakeConnection.class) - .downloadStream("~", DEST_PREFIX + "/" + TEST_DATA_FILE + ".gz", true); - StringWriter writer = new StringWriter(); - IOUtils.copy(out, writer, "UTF-8"); - String output = writer.toString(); - // the first 2 characters - assertEquals("1|", output.substring(0, 2)); - // the number of lines - String[] lines = output.split("\n"); - assertEquals(28, lines.length); - } finally { - if (statement != null) { + try (Connection connection = getConnection("gcpaccount", paramProperties); + Statement statement = connection.createStatement(); + ResultSet rset = + statement.executeQuery( + "PUT file://" + getFullPathFileInResource(TEST_DATA_FILE) + " @~/" + DEST_PREFIX)) { + try { + assertTrue(rset.next()); + assertEquals("UPLOADED", rset.getString(7)); + + InputStream out = + connection + .unwrap(SnowflakeConnection.class) + .downloadStream("~", DEST_PREFIX + "/" + TEST_DATA_FILE + ".gz", true); + StringWriter writer = new StringWriter(); + IOUtils.copy(out, writer, "UTF-8"); + String output = writer.toString(); + // the first 2 characters + assertEquals("1|", output.substring(0, 2)); + + // the number of lines + String[] lines = output.split("\n"); + assertEquals(28, lines.length); + } finally { statement.execute("rm @~/" + DEST_PREFIX); - statement.close(); } - closeSQLObjects(statement, connection); } } @Test public void testSpecialCharactersInFileName() throws SQLException, IOException { - Connection connection = null; - Statement statement = null; - try { - connection = getConnection(); - statement = connection.createStatement(); - - // Create a temporary file with special characters in the name and write to it - File specialCharFile = tmpFolder.newFile("(special char@).txt"); - BufferedWriter bw = new BufferedWriter(new FileWriter(specialCharFile)); - bw.write("Creating test file for downloadStream test"); - bw.close(); - - String sourceFilePath = specialCharFile.getCanonicalPath(); - String sourcePathEscaped; - if (System.getProperty("file.separator").equals("\\")) { - // windows separator needs to be escaped because of quotes - sourcePathEscaped = sourceFilePath.replace("\\", "\\\\"); - } else { - sourcePathEscaped = sourceFilePath; - } - - // create a stage to put the file in - statement.execute("CREATE OR REPLACE STAGE downloadStream_stage"); - statement.execute( - "PUT 'file://" + sourcePathEscaped + "' @~/downloadStream_stage auto_compress=false"); - - // download file stream - InputStream out = - connection - .unwrap(SnowflakeConnection.class) - .downloadStream("~", "/downloadStream_stage/" + specialCharFile.getName(), false); - - // Read file stream and check the result - StringWriter writer = new StringWriter(); - IOUtils.copy(out, writer, "UTF-8"); - String output = writer.toString(); - assertEquals("Creating test file for downloadStream test", output); - } finally { - if (statement != null) { + try (Connection connection = getConnection(); + Statement statement = connection.createStatement()) { + try { + // Create a temporary file with special characters in the name and write to it + File specialCharFile = tmpFolder.newFile("(special char@).txt"); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(specialCharFile))) { + bw.write("Creating test file for downloadStream test"); + } + + String sourceFilePath = specialCharFile.getCanonicalPath(); + String sourcePathEscaped; + if (System.getProperty("file.separator").equals("\\")) { + // windows separator needs to be escaped because of quotes + sourcePathEscaped = sourceFilePath.replace("\\", "\\\\"); + } else { + sourcePathEscaped = sourceFilePath; + } + + // create a stage to put the file in + statement.execute("CREATE OR REPLACE STAGE downloadStream_stage"); + statement.execute( + "PUT 'file://" + sourcePathEscaped + "' @~/downloadStream_stage auto_compress=false"); + + // download file stream + try (InputStream out = + connection + .unwrap(SnowflakeConnection.class) + .downloadStream("~", "/downloadStream_stage/" + specialCharFile.getName(), false)) { + + // Read file stream and check the result + StringWriter writer = new StringWriter(); + IOUtils.copy(out, writer, "UTF-8"); + String output = writer.toString(); + assertEquals("Creating test file for downloadStream test", output); + } + } finally { statement.execute("DROP STAGE IF EXISTS downloadStream_stage"); - statement.close(); } } }