diff --git a/src/test/java/org/duckdb/TestClosure.java b/src/test/java/org/duckdb/TestClosure.java index 9f060376f..05dde2afd 100644 --- a/src/test/java/org/duckdb/TestClosure.java +++ b/src/test/java/org/duckdb/TestClosure.java @@ -10,9 +10,26 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicBoolean; public class TestClosure { + // Query progress is used to find out whether a query is running, + // it is only tracked when the progress bar is enabled. + private static void enableQueryProgress(Statement stmt) throws SQLException { + stmt.execute("SET enable_progress_bar = true"); + stmt.execute("SET enable_progress_bar_print = false"); + } + + // Waits until a query is running on the connection of the specified statement + // or until the query is finished, to not depend on the timing of a fixed sleep. + private static void waitForQueryStart(Statement stmt, AtomicBoolean queryFinished) throws Exception { + DuckDBPreparedStatement duckdbStmt = stmt.unwrap(DuckDBPreparedStatement.class); + while (duckdbStmt.getQueryProgress().getPercentage() < 0 && !queryFinished.get()) { + Thread.sleep(10); + } + } + // https://github.com/duckdb/duckdb-java/issues/101 public static void test_unclosed_statement_does_not_hang() throws Exception { String dbName = "test_issue_101.db"; @@ -195,22 +212,28 @@ public static void test_long_query_conn_close() throws Exception { Statement stmt = conn.createStatement(); stmt.execute("CREATE TABLE test_fib1(i bigint, p double, f double)"); stmt.execute("INSERT INTO test_fib1 values(1, 0, 1)"); + enableQueryProgress(stmt); + AtomicBoolean queryFinished = new AtomicBoolean(false); long start = System.currentTimeMillis(); Thread th = new Thread(() -> { try { - Thread.sleep(1000); + waitForQueryStart(stmt, queryFinished); conn.close(); } catch (Exception e) { e.printStackTrace(); } }); th.start(); - assertThrows(() - -> stmt.executeQuery("WITH RECURSIVE cte AS (" - + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, cte.p + " - + "cte.f from cte WHERE cte.i < 1000000) " - + "SELECT avg(f) FROM cte"), - SQLException.class); + try { + assertThrows(() + -> stmt.executeQuery("WITH RECURSIVE cte AS (" + + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, " + + "cte.p + cte.f from cte WHERE cte.i < 1000000) " + + "SELECT avg(f) FROM cte"), + SQLException.class); + } finally { + queryFinished.set(true); + } th.join(); long elapsed = System.currentTimeMillis() - start; assertTrue(elapsed < 2000); @@ -228,17 +251,23 @@ public static void test_long_query_conn_close_prepared() throws Exception { + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, cte.p + cte.f from cte WHERE cte.i < 1000000) " + "SELECT avg(f) FROM cte"); + enableQueryProgress(stmt); + AtomicBoolean queryFinished = new AtomicBoolean(false); long start = System.currentTimeMillis(); Thread th = new Thread(() -> { try { - Thread.sleep(1000); + waitForQueryStart(ps, queryFinished); conn.close(); } catch (Exception e) { e.printStackTrace(); } }); th.start(); - assertThrows(ps::executeQuery, SQLException.class); + try { + assertThrows(ps::executeQuery, SQLException.class); + } finally { + queryFinished.set(true); + } th.join(); long elapsed = System.currentTimeMillis() - start; assertTrue(elapsed < 2000); @@ -252,10 +281,12 @@ public static void test_long_query_stmt_close() throws Exception { Statement stmt = conn.createStatement(); stmt.execute("CREATE TABLE test_fib1(i bigint, p double, f double)"); stmt.execute("INSERT INTO test_fib1 values(1, 0, 1)"); + enableQueryProgress(stmt); + AtomicBoolean queryFinished = new AtomicBoolean(false); long start = System.currentTimeMillis(); Thread th = new Thread(() -> { try { - Thread.sleep(1000); + waitForQueryStart(stmt, queryFinished); stmt.cancel(); stmt.close(); } catch (Exception e) { @@ -263,12 +294,16 @@ public static void test_long_query_stmt_close() throws Exception { } }); th.start(); - assertThrows(() - -> stmt.executeQuery("WITH RECURSIVE cte AS (" - + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, " - + "cte.p + cte.f from cte WHERE cte.i < 1000000) " - + "SELECT avg(f) FROM cte"), - SQLException.class); + try { + assertThrows(() + -> stmt.executeQuery("WITH RECURSIVE cte AS (" + + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, " + + "cte.p + cte.f from cte WHERE cte.i < 1000000) " + + "SELECT avg(f) FROM cte"), + SQLException.class); + } finally { + queryFinished.set(true); + } th.join(); long elapsed = System.currentTimeMillis() - start; assertTrue(elapsed < 2000); @@ -287,10 +322,12 @@ public static void test_long_query_prepared_stmt_close() throws Exception { + "SELECT avg(f) FROM cte" ); + enableQueryProgress(stmt); + AtomicBoolean queryFinished = new AtomicBoolean(false); long start = System.currentTimeMillis(); Thread th = new Thread(() -> { try { - Thread.sleep(1000); + waitForQueryStart(ps, queryFinished); ps.cancel(); ps.close(); } catch (Exception e) { @@ -298,7 +335,11 @@ public static void test_long_query_prepared_stmt_close() throws Exception { } }); th.start(); - assertThrows(ps::executeQuery, SQLException.class); + try { + assertThrows(ps::executeQuery, SQLException.class); + } finally { + queryFinished.set(true); + } th.join(); long elapsed = System.currentTimeMillis() - start; assertTrue(elapsed < 2000); @@ -309,238 +350,275 @@ public static void test_long_query_prepared_stmt_close() throws Exception { public static void test_conn_close_no_crash() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - for (int i = 0; i < 1 << 7; i++) { - Connection conn = DriverManager.getConnection(JDBC_URL); - Statement stmt = conn.createStatement(); - Future future = executor.submit(() -> { + try { + for (int i = 0; i < 1 << 7; i++) { + Connection conn = DriverManager.getConnection(JDBC_URL); + Statement stmt = conn.createStatement(); + Future future = executor.submit(() -> { + try { + long millis = ThreadLocalRandom.current().nextInt(1, 20); + Thread.sleep(millis); + conn.close(); + } catch (SQLException e) { + fail(); + } catch (InterruptedException e) { + throw new RuntimeException(); + } + }); try { long millis = ThreadLocalRandom.current().nextInt(1, 20); Thread.sleep(millis); - conn.close(); + stmt.executeQuery("SELECT 42"); } catch (SQLException e) { - fail(); - } catch (InterruptedException e) { - throw new RuntimeException(); + // suppress + } finally { + stmt.close(); } - }); - try { - long millis = ThreadLocalRandom.current().nextInt(1, 20); - Thread.sleep(millis); - stmt.executeQuery("SELECT 42"); - } catch (SQLException e) { - // suppress - } finally { - stmt.close(); + future.get(); } - future.get(); + } finally { + executor.shutdownNow(); } } public static void test_conn_close_no_crash_prepared() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - for (int i = 0; i < 1 << 7; i++) { - Connection conn = DriverManager.getConnection(JDBC_URL); - PreparedStatement ps = conn.prepareStatement("SELECT 42"); - Future future = executor.submit(() -> { + try { + for (int i = 0; i < 1 << 7; i++) { + Connection conn = DriverManager.getConnection(JDBC_URL); + PreparedStatement ps = conn.prepareStatement("SELECT 42"); + Future future = executor.submit(() -> { + try { + long millis = ThreadLocalRandom.current().nextInt(1, 20); + Thread.sleep(millis); + conn.close(); + } catch (SQLException e) { + fail(); + } catch (InterruptedException e) { + throw new RuntimeException(); + } + }); try { long millis = ThreadLocalRandom.current().nextInt(1, 20); Thread.sleep(millis); - conn.close(); + ps.executeQuery(); } catch (SQLException e) { - fail(); - } catch (InterruptedException e) { - throw new RuntimeException(); + // suppress + } finally { + ps.close(); } - }); - try { - long millis = ThreadLocalRandom.current().nextInt(1, 20); - Thread.sleep(millis); - ps.executeQuery(); - } catch (SQLException e) { - // suppress - } finally { - ps.close(); + future.get(); } - future.get(); + } finally { + executor.shutdownNow(); } } public static void test_stmt_close_no_crash() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - try (Connection conn = DriverManager.getConnection(JDBC_URL)) { - for (int i = 0; i < 1 << 10; i++) { - Statement stmt = conn.createStatement(); - Future future = executor.submit(() -> { + try { + try (Connection conn = DriverManager.getConnection(JDBC_URL)) { + for (int i = 0; i < 1 << 10; i++) { + Statement stmt = conn.createStatement(); + Future future = executor.submit(() -> { + try { + stmt.close(); + } catch (SQLException e) { + fail(); + } + }); try { - stmt.close(); + stmt.executeQuery("select 42"); } catch (SQLException e) { - fail(); } - }); - try { - stmt.executeQuery("select 42"); - } catch (SQLException e) { + future.get(); } - future.get(); } + } finally { + executor.shutdownNow(); } } public static void test_prepared_stmt_close_no_crash() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - try (Connection conn = DriverManager.getConnection(JDBC_URL)) { - for (int i = 0; i < 1 << 10; i++) { - PreparedStatement ps = conn.prepareStatement("select 42"); - Future future = executor.submit(() -> { + try { + try (Connection conn = DriverManager.getConnection(JDBC_URL)) { + for (int i = 0; i < 1 << 10; i++) { + PreparedStatement ps = conn.prepareStatement("select 42"); + Future future = executor.submit(() -> { + try { + ps.close(); + } catch (SQLException e) { + fail(); + } + }); try { - ps.close(); + ps.executeQuery(); } catch (SQLException e) { - fail(); } - }); - try { - ps.executeQuery(); - } catch (SQLException e) { + future.get(); } - future.get(); } + } finally { + executor.shutdownNow(); } } public static void test_results_close_no_crash() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - try (Connection conn = DriverManager.getConnection(JDBC_URL); Statement stmt = conn.createStatement()) { - for (int i = 0; i < 1 << 12; i++) { - ResultSet rs = stmt.executeQuery("select 42"); - Future future = executor.submit(() -> { + try { + try (Connection conn = DriverManager.getConnection(JDBC_URL); Statement stmt = conn.createStatement()) { + for (int i = 0; i < 1 << 12; i++) { + ResultSet rs = stmt.executeQuery("select 42"); + Future future = executor.submit(() -> { + try { + rs.close(); + } catch (SQLException e) { + fail(); + } + }); try { - rs.close(); + rs.next(); } catch (SQLException e) { - fail(); } - }); - try { - rs.next(); - } catch (SQLException e) { + future.get(); } - future.get(); } + } finally { + executor.shutdownNow(); } } public static void test_results_close_prepared_stmt_no_crash() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - try (Connection conn = DriverManager.getConnection(JDBC_URL); - PreparedStatement stmt = conn.prepareStatement("select 42")) { - for (int i = 0; i < 1 << 12; i++) { - ResultSet rs = stmt.executeQuery(); - Future future = executor.submit(() -> { + try { + try (Connection conn = DriverManager.getConnection(JDBC_URL); + PreparedStatement stmt = conn.prepareStatement("select 42")) { + for (int i = 0; i < 1 << 12; i++) { + ResultSet rs = stmt.executeQuery(); + Future future = executor.submit(() -> { + try { + rs.close(); + } catch (SQLException e) { + fail(); + } + }); try { - rs.close(); + rs.next(); } catch (SQLException e) { - fail(); } - }); - try { - rs.next(); - } catch (SQLException e) { + future.get(); } - future.get(); } + } finally { + executor.shutdownNow(); } } @SuppressWarnings("try") public static void test_results_fetch_no_hang() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - Properties config = new Properties(); - config.put(DuckDBDriver.JDBC_STREAM_RESULTS, true); - long rowsCount = 1 << 26; - int iterations = 1; - for (int i = 0; i < iterations; i++) { - try (Connection conn = DriverManager.getConnection(JDBC_URL, config); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT i, i::VARCHAR FROM range(0, " + rowsCount + ") AS t(i)")) { - executor.submit(() -> { - try { - Thread.sleep(100); - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - }); - long[] resultsCount = new long[1]; - assertThrows(() -> { - while (rs.next()) { - resultsCount[0]++; - } - }, SQLException.class); - assertTrue(resultsCount[0] > 0); - assertTrue(resultsCount[0] < rowsCount); + try { + Properties config = new Properties(); + config.put(DuckDBDriver.JDBC_STREAM_RESULTS, true); + long rowsCount = 1 << 26; + int iterations = 1; + for (int i = 0; i < iterations; i++) { + try (Connection conn = DriverManager.getConnection(JDBC_URL, config); + Statement stmt = conn.createStatement(); + ResultSet rs = + stmt.executeQuery("SELECT i, i::VARCHAR FROM range(0, " + rowsCount + ") AS t(i)")) { + executor.submit(() -> { + try { + Thread.sleep(200); + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + }); + long[] resultsCount = new long[1]; + assertThrows(() -> { + while (rs.next()) { + resultsCount[0]++; + } + }, SQLException.class); + assertTrue(resultsCount[0] > 0); + assertTrue(resultsCount[0] < rowsCount); + } } + } finally { + executor.shutdownNow(); } } @SuppressWarnings("try") public static void test_results_fetch_no_hang_prepared() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - Properties config = new Properties(); - config.put(DuckDBDriver.JDBC_STREAM_RESULTS, true); - long rowsCount = 1 << 26; - int iterations = 1; - for (int i = 0; i < iterations; i++) { - try (Connection conn = DriverManager.getConnection(JDBC_URL, config); - PreparedStatement ps = - conn.prepareStatement("SELECT i, i::VARCHAR FROM range(0, " + rowsCount + ") AS t(i)"); - ResultSet rs = ps.executeQuery()) { - executor.submit(() -> { - try { - Thread.sleep(100); - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - }); - long[] resultsCount = new long[1]; - assertThrows(() -> { - while (rs.next()) { - resultsCount[0]++; - } - }, SQLException.class); - assertTrue(resultsCount[0] > 0); - assertTrue(resultsCount[0] < rowsCount); + try { + Properties config = new Properties(); + config.put(DuckDBDriver.JDBC_STREAM_RESULTS, true); + long rowsCount = 1 << 26; + int iterations = 1; + for (int i = 0; i < iterations; i++) { + try (Connection conn = DriverManager.getConnection(JDBC_URL, config); + PreparedStatement ps = + conn.prepareStatement("SELECT i, i::VARCHAR FROM range(0, " + rowsCount + ") AS t(i)"); + ResultSet rs = ps.executeQuery()) { + executor.submit(() -> { + try { + Thread.sleep(100); + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + }); + long[] resultsCount = new long[1]; + assertThrows(() -> { + while (rs.next()) { + resultsCount[0]++; + } + }, SQLException.class); + assertTrue(resultsCount[0] > 0); + assertTrue(resultsCount[0] < rowsCount); + } } + } finally { + executor.shutdownNow(); } } @SuppressWarnings("try") public static void test_results_fetch_no_hang_prepared_chunked() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - long rowsCount = 1 << 25; - int iterations = 1; - for (int i = 0; i < iterations; i++) { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - DuckDBPreparedStatement ps = - conn.prepare("SELECT i, i::VARCHAR FROM range(0, " + rowsCount + ") AS t(i)"); - DuckDBChunkedResult rs = ps.query()) { - executor.submit(() -> { - try { - Thread.sleep(400); - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - }); - long[] resultsCount = new long[1]; - assertThrows(() -> { - while (rs.nextChunk()) { - resultsCount[0] += rs.chunk().rowCount(); - Thread.sleep(5); - } - }, IllegalStateException.class); - assertTrue(resultsCount[0] > 0); - assertTrue(resultsCount[0] < rowsCount); + try { + long rowsCount = 1 << 25; + int iterations = 1; + for (int i = 0; i < iterations; i++) { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + DuckDBPreparedStatement ps = + conn.prepare("SELECT i, i::VARCHAR FROM range(0, " + rowsCount + ") AS t(i)"); + DuckDBChunkedResult rs = ps.query()) { + executor.submit(() -> { + try { + Thread.sleep(400); + conn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + }); + long[] resultsCount = new long[1]; + assertThrows(() -> { + while (rs.nextChunk()) { + resultsCount[0] += rs.chunk().rowCount(); + Thread.sleep(5); + } + }, IllegalStateException.class); + assertTrue(resultsCount[0] > 0); + assertTrue(resultsCount[0] < rowsCount); + } } + } finally { + executor.shutdownNow(); } } @@ -550,16 +628,21 @@ public static void test_stmt_can_only_cancel_self() throws Exception { stmt1.execute("DROP TABLE IF EXISTS test_fib1"); stmt1.execute("CREATE TABLE test_fib1(i bigint, p double, f double)"); stmt1.execute("INSERT INTO test_fib1 values(1, 0, 1)"); - long start = System.currentTimeMillis(); + enableQueryProgress(stmt1); + AtomicBoolean queryFinished = new AtomicBoolean(false); + AtomicBoolean runningAfterOtherCancel = new AtomicBoolean(false); Thread th = new Thread(() -> { try { - Thread.sleep(200); + waitForQueryStart(stmt2, queryFinished); stmt1.cancel(); } catch (Exception e) { e.printStackTrace(); } try { - Thread.sleep(1000); + // the query on stmt2 must not be interrupted by the cancel on stmt1, + // its bound is set to run it for much longer than this on a fast machine + Thread.sleep(500); + runningAfterOtherCancel.set(!queryFinished.get()); assertFalse(stmt2.isClosed()); stmt2.cancel(); } catch (Exception e) { @@ -567,16 +650,20 @@ public static void test_stmt_can_only_cancel_self() throws Exception { } }); th.start(); - String msg = assertThrows(() -> { - stmt2.executeQuery("WITH RECURSIVE cte AS (" - + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, cte.p + cte.f from " - + "cte WHERE cte.i < 1000000) " - + "SELECT avg(f) FROM cte"); - }, SQLException.class); + String msg; + try { + msg = assertThrows(() -> { + stmt2.executeQuery("WITH RECURSIVE cte AS (" + + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, cte.p + cte.f " + + "from cte WHERE cte.i < 10000000) " + + "SELECT avg(f) FROM cte"); + }, SQLException.class); + } finally { + queryFinished.set(true); + } assertTrue(msg.startsWith("INTERRUPT Error")); th.join(); - long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed > 1000); + assertTrue(runningAfterOtherCancel.get()); assertFalse(conn.isClosed()); assertFalse(stmt1.isClosed()); assertTrue(stmt2.isClosed()); @@ -591,18 +678,23 @@ public static void test_prepared_stmt_can_only_cancel_self() throws Exception { PreparedStatement ps2 = conn.prepareStatement("WITH RECURSIVE cte AS (" + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, cte.p + " - + "cte.f from cte WHERE cte.i < 1000000) " + + "cte.f from cte WHERE cte.i < 10000000) " + "SELECT avg(f) FROM cte")) { - long start = System.currentTimeMillis(); + enableQueryProgress(stmt1); + AtomicBoolean queryFinished = new AtomicBoolean(false); + AtomicBoolean runningAfterOtherCancel = new AtomicBoolean(false); Thread th = new Thread(() -> { try { - Thread.sleep(200); + waitForQueryStart(ps2, queryFinished); ps1.cancel(); } catch (Exception e) { e.printStackTrace(); } try { - Thread.sleep(1000); + // the query on ps2 must not be interrupted by the cancel on ps1, + // its bound is set to run it for much longer than this on a fast machine + Thread.sleep(500); + runningAfterOtherCancel.set(!queryFinished.get()); assertFalse(ps2.isClosed()); ps2.cancel(); } catch (Exception e) { @@ -610,11 +702,15 @@ public static void test_prepared_stmt_can_only_cancel_self() throws Exception { } }); th.start(); - String msg = assertThrows(ps2::executeQuery, SQLException.class); + String msg; + try { + msg = assertThrows(ps2::executeQuery, SQLException.class); + } finally { + queryFinished.set(true); + } assertTrue(msg.startsWith("INTERRUPT Error")); th.join(); - long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed > 1000); + assertTrue(runningAfterOtherCancel.get()); assertFalse(conn.isClosed()); assertFalse(ps1.isClosed()); assertTrue(ps2.isClosed()); @@ -628,10 +724,11 @@ public static void test_stmt_query_timeout() throws Exception { stmt.execute("CREATE TABLE test_fib1(i bigint, p double, f double)"); stmt.execute("INSERT INTO test_fib1 values(1, 0, 1)"); long start = System.currentTimeMillis(); + // the query bound is set to run it for much longer than the timeout on a fast machine assertThrows(() -> stmt.executeQuery("WITH RECURSIVE cte AS (" + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, " - + "cte.p + cte.f from cte WHERE cte.i < 1000000) " + + "cte.p + cte.f from cte WHERE cte.i < 10000000) " + "SELECT avg(f) FROM cte"), SQLTimeoutException.class); long elapsed = System.currentTimeMillis() - start; @@ -651,9 +748,10 @@ public static void test_prepared_stmt_query_timeout() throws Exception { try (Connection conn = DriverManager.getConnection(JDBC_URL); Statement stmt = conn.createStatement();) { stmt.execute("CREATE TABLE test_fib1(i bigint, p double, f double)"); stmt.execute("INSERT INTO test_fib1 values(1, 0, 1)"); + // the query bound is set to run it for much longer than the timeout on a fast machine try (PreparedStatement ps = conn.prepareStatement("WITH RECURSIVE cte AS (" + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, " - + "cte.f, cte.p + cte.f from cte WHERE cte.i < 1000000) " + + "cte.f, cte.p + cte.f from cte WHERE cte.i < 10000000) " + "SELECT avg(f) FROM cte")) { ps.setQueryTimeout(1); long start = System.currentTimeMillis(); diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index 5b1e99e14..04ab9cbe6 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -50,6 +50,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import javax.sql.DataSource; import javax.sql.rowset.CachedRowSet; import javax.sql.rowset.RowSetProvider; @@ -1961,34 +1962,39 @@ public static void test_cancel() throws Exception { stmt.cancel(); String message = thread.get(1, TimeUnit.SECONDS); assertEquals(message, "INTERRUPT Error: Interrupted!"); + } finally { + service.shutdownNow(); } } public static void test_lots_of_races() throws Exception { try (Connection connection = DriverManager.getConnection(JDBC_URL)) { ExecutorService executorService = Executors.newFixedThreadPool(10); + try { + List> tasks = Collections.nCopies(1000, () -> { + try { + try (PreparedStatement ps = connection.prepareStatement( + "SELECT count(*) FROM information_schema.tables WHERE table_name = 'test' LIMIT 1;")) { + ps.execute(); + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + return null; + }); + List> results = executorService.invokeAll(tasks); - List> tasks = Collections.nCopies(1000, () -> { try { - try (PreparedStatement ps = connection.prepareStatement( - "SELECT count(*) FROM information_schema.tables WHERE table_name = 'test' LIMIT 1;")) { - ps.execute(); + for (Future future : results) { + future.get(); } - } catch (SQLException e) { - throw new RuntimeException(e); - } - return null; - }); - List> results = executorService.invokeAll(tasks); - - try { - for (Future future : results) { - future.get(); + } catch (java.util.concurrent.ExecutionException ee) { + assertEquals( + ee.getCause().getCause().getMessage(), + "Invalid Input Error: Attempting to execute an unsuccessful or closed pending query result"); } - } catch (java.util.concurrent.ExecutionException ee) { - assertEquals( - ee.getCause().getCause().getMessage(), - "Invalid Input Error: Attempting to execute an unsuccessful or closed pending query result"); + } finally { + executorService.shutdownNow(); } } } @@ -2454,31 +2460,46 @@ public static void test_query_progress() throws Exception { stmt.execute("INSERT INTO test_fib1 values(1, 0, 1)"); stmt.execute("SET enable_progress_bar = true"); + // The query is cancelled as soon as it reports the progress (in tens of milliseconds), + // its bound is set to run it for about a second on a fast machine. + AtomicBoolean queryFinished = new AtomicBoolean(false); ExecutorService executorService = Executors.newSingleThreadExecutor(); - Future future = executorService.submit(() -> { - try { - Thread.sleep(2000); + try { + Future future = executorService.submit(() -> { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); QueryProgress qp = stmt.getQueryProgress(); - stmt.cancel(); + while (qp.getPercentage() <= 0 && !queryFinished.get() && System.nanoTime() < deadline) { + Thread.sleep(10); + qp = stmt.getQueryProgress(); + } + // Cancel is a no-op when it is called before the query is started, + // keep cancelling until the query is finished. + while (!queryFinished.get()) { + stmt.cancel(); + Thread.sleep(10); + } return qp; - } catch (Exception e) { - e.printStackTrace(); - return null; + }); + String message; + try { + message = assertThrows( + () + -> stmt.executeQuery("WITH RECURSIVE cte AS NOT MATERIALIZED (" + + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, " + + "cte.p + cte.f from cte WHERE cte.i < 1000000) " + + "SELECT avg(f) FROM cte"), + SQLException.class); + } finally { + queryFinished.set(true); } - }); - assertThrows(() - -> stmt.executeQuery("WITH RECURSIVE cte AS NOT MATERIALIZED (" - + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, " - + "cte.p + cte.f from cte WHERE cte.i < 1000000) " - + "SELECT avg(f) FROM cte"), - SQLException.class); - - QueryProgress qpRunning = future.get(); - assertNotNull(qpRunning); - // cannot be reliable asserted under ASan - if (qpRunning.getPercentage() > 0) { + QueryProgress qpRunning = future.get(60, TimeUnit.SECONDS); + assertTrue(message.contains("Interrupted!"), message); + assertNotNull(qpRunning); + assertTrue(qpRunning.getPercentage() > 0); assertTrue(qpRunning.getRowsProcessed() > 0); assertTrue(qpRunning.getTotalRowsToProcess() > 0); + } finally { + executorService.shutdownNow(); } assertThrows(stmt::getQueryProgress, SQLException.class);