diff --git a/cpp/src/arrow/flight/sql/odbc/entry_points.cc b/cpp/src/arrow/flight/sql/odbc/entry_points.cc index c03089ffcc6d..231b7d27f812 100644 --- a/cpp/src/arrow/flight/sql/odbc/entry_points.cc +++ b/cpp/src/arrow/flight/sql/odbc/entry_points.cc @@ -201,12 +201,7 @@ SQLRETURN SQL_API SQLBindCol(SQLHSTMT stmt, SQLUSMALLINT record_number, } SQLRETURN SQL_API SQLCancel(SQLHSTMT stmt) { - ARROW_LOG(DEBUG) << "SQLCancel called with stmt: " << stmt; - return ODBC::ODBCStatement::ExecuteWithDiagnostics(stmt, SQL_ERROR, [=]() { - throw arrow::flight::sql::odbc::DriverException("SQLCancel is not implemented", - "IM001"); - return SQL_ERROR; - }); + return arrow::flight::sql::odbc::SQLCancel(stmt); } SQLRETURN SQL_API SQLCloseCursor(SQLHSTMT stmt) { diff --git a/cpp/src/arrow/flight/sql/odbc/odbc_api.cc b/cpp/src/arrow/flight/sql/odbc/odbc_api.cc index eebc83b68d17..74f4dcc5f057 100644 --- a/cpp/src/arrow/flight/sql/odbc/odbc_api.cc +++ b/cpp/src/arrow/flight/sql/odbc/odbc_api.cc @@ -1083,6 +1083,28 @@ SQLRETURN SQLExecute(SQLHSTMT stmt) { }); } +SQLRETURN SQLCancel(SQLHSTMT stmt) { + ARROW_LOG(DEBUG) << "SQLCancel called with stmt: " << stmt; + + using ODBC::ODBCStatement; + + if (!stmt) { + return SQL_INVALID_HANDLE; + } + + // Bypass ExecuteWithDiagnostics: it would lock the same mutex SQLFetch holds while + // blocked, so SQLCancel would wait for the very call it's meant to interrupt. It + // also shares Diagnostics with that in-progress SQLFetch. + // GH-55816 TODO: post a diagnostic record here on failure instead of swallowing + // the exception, without reintroducing the lock contention bypassed above. + try { + ODBCStatement::Of(stmt)->Cancel(); + } catch (...) { + return SQL_ERROR; + } + return SQL_SUCCESS; +} + SQLRETURN SQLFetch(SQLHSTMT stmt) { ARROW_LOG(DEBUG) << "SQLFetch called with stmt: " << stmt; diff --git a/cpp/src/arrow/flight/sql/odbc/odbc_api_internal.h b/cpp/src/arrow/flight/sql/odbc/odbc_api_internal.h index 0f581d734e1d..31d51ae64f7d 100644 --- a/cpp/src/arrow/flight/sql/odbc/odbc_api_internal.h +++ b/cpp/src/arrow/flight/sql/odbc/odbc_api_internal.h @@ -81,6 +81,7 @@ namespace arrow::flight::sql::odbc { [[nodiscard]] SQLRETURN SQLPrepare(SQLHSTMT stmt, SQLWCHAR* queryText, SQLINTEGER text_length); [[nodiscard]] SQLRETURN SQLExecute(SQLHSTMT stmt); +[[nodiscard]] SQLRETURN SQLCancel(SQLHSTMT stmt); [[nodiscard]] SQLRETURN SQLFetch(SQLHSTMT stmt); [[nodiscard]] SQLRETURN SQLExtendedFetch(SQLHSTMT stmt, SQLUSMALLINT fetch_orientation, SQLLEN fetch_offset, SQLULEN* row_count_ptr, diff --git a/cpp/src/arrow/flight/sql/odbc/odbc_impl/blocking_queue.h b/cpp/src/arrow/flight/sql/odbc/odbc_impl/blocking_queue.h index 55ec3a7beaec..eefc4aa4d01f 100644 --- a/cpp/src/arrow/flight/sql/odbc/odbc_impl/blocking_queue.h +++ b/cpp/src/arrow/flight/sql/odbc/odbc_impl/blocking_queue.h @@ -95,6 +95,8 @@ class BlockingQueue { return true; } + bool HasActiveProducers() const { return active_threads_ > 0; } + void Close() { std::unique_lock unique_lock(mtx_); diff --git a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_result_set.cc b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_result_set.cc index 5b4c699781c6..760f36df497d 100644 --- a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_result_set.cc +++ b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_result_set.cc @@ -66,6 +66,10 @@ size_t FlightSqlResultSet::Move(size_t rows, size_t bind_offset, size_t bind_typ // Consider it might be the first call to Move() and current_chunk is not // populated yet assert(rows > 0); + // Mark the whole call, not just whichever GetNext() calls happen inside it, as an + // in-progress fetch: Cancel() must be able to interrupt rows being read out of an + // already-buffered chunk too, not only a GetNext() blocked waiting for the next one. + FlightStreamChunkBuffer::FetchGuard fetch_guard(chunk_buffer_); if (current_chunk_.data == nullptr) { if (!chunk_buffer_.GetNext(¤t_chunk_)) { return 0; @@ -212,8 +216,9 @@ void FlightSqlResultSet::Close() { } void FlightSqlResultSet::Cancel() { - chunk_buffer_.Close(); - current_chunk_.data = nullptr; + // GH-55800 TODO: Cancel the query on the server via the Flight SQL protocol's + // CancelFlightInfo, instead of only cancelling the client-side stream below. + chunk_buffer_.Cancel(); } SQLRETURN FlightSqlResultSet::GetData(int column_n, int16_t target_type, int precision, diff --git a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_statement.cc b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_statement.cc index 46456e8c3c91..fe5e829737f7 100644 --- a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_statement.cc +++ b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_statement.cc @@ -129,9 +129,9 @@ bool FlightSqlStatement::ExecutePrepared() { prepared_statement_->Execute(call_options_); ThrowIfNotOK(result.status()); - current_result_set_ = std::make_shared( + SetCurrentResultSet(std::make_shared( sql_client_, client_options_, call_options_, result.ValueOrDie(), nullptr, - diagnostics_, metadata_settings_); + diagnostics_, metadata_settings_)); return true; } @@ -142,14 +142,22 @@ bool FlightSqlStatement::Execute(const std::string& query) { Result> result = sql_client_.Execute(call_options_, query); ThrowIfNotOK(result.status()); - current_result_set_ = std::make_shared( + SetCurrentResultSet(std::make_shared( sql_client_, client_options_, call_options_, result.ValueOrDie(), nullptr, - diagnostics_, metadata_settings_); + diagnostics_, metadata_settings_)); return true; } std::shared_ptr FlightSqlStatement::GetResultSet() { + std::lock_guard guard(current_result_set_mutex_); + return current_result_set_; +} + +std::shared_ptr FlightSqlStatement::SetCurrentResultSet( + std::shared_ptr result_set) { + std::lock_guard guard(current_result_set_mutex_); + current_result_set_ = std::move(result_set); return current_result_set_; } @@ -165,32 +173,30 @@ std::shared_ptr FlightSqlStatement::GetTables( if ((catalog_name && *catalog_name == "%") && (schema_name && schema_name->empty()) && (table_name && table_name->empty())) { - current_result_set_ = + return SetCurrentResultSet( GetTablesForSQLAllCatalogs(column_names, client_options_, call_options_, - sql_client_, diagnostics_, metadata_settings_); + sql_client_, diagnostics_, metadata_settings_)); } else if ((catalog_name && catalog_name->empty()) && (schema_name && *schema_name == "%") && (table_name && table_name->empty())) { - current_result_set_ = GetTablesForSQLAllDbSchemas( + return SetCurrentResultSet(GetTablesForSQLAllDbSchemas( column_names, client_options_, call_options_, sql_client_, schema_name, - diagnostics_, metadata_settings_); + diagnostics_, metadata_settings_)); } else if ((catalog_name && catalog_name->empty()) && (schema_name && schema_name->empty()) && (table_name && table_name->empty()) && (table_type && *table_type == "%")) { - current_result_set_ = + return SetCurrentResultSet( GetTablesForSQLAllTableTypes(column_names, client_options_, call_options_, - sql_client_, diagnostics_, metadata_settings_); + sql_client_, diagnostics_, metadata_settings_)); } else { if (table_type) { ParseTableTypes(*table_type, table_types); } - current_result_set_ = GetTablesForGenericUse( + return SetCurrentResultSet(GetTablesForGenericUse( column_names, client_options_, call_options_, sql_client_, catalog_name, - schema_name, table_name, table_types, diagnostics_, metadata_settings_); + schema_name, table_name, table_types, diagnostics_, metadata_settings_)); } - - return current_result_set_; } std::shared_ptr FlightSqlStatement::GetTables_V2( @@ -225,11 +231,9 @@ std::shared_ptr FlightSqlStatement::GetColumns_V2( auto transformer = std::make_shared( metadata_settings_, OdbcVersion::V_2, column_name); - current_result_set_ = std::make_shared( + return SetCurrentResultSet(std::make_shared( sql_client_, client_options_, call_options_, flight_info, transformer, diagnostics_, - metadata_settings_); - - return current_result_set_; + metadata_settings_)); } std::shared_ptr FlightSqlStatement::GetColumns_V3( @@ -246,11 +250,9 @@ std::shared_ptr FlightSqlStatement::GetColumns_V3( auto transformer = std::make_shared( metadata_settings_, OdbcVersion::V_3, column_name); - current_result_set_ = std::make_shared( + return SetCurrentResultSet(std::make_shared( sql_client_, client_options_, call_options_, flight_info, transformer, diagnostics_, - metadata_settings_); - - return current_result_set_; + metadata_settings_)); } std::shared_ptr FlightSqlStatement::GetTypeInfo_V2(int16_t data_type) { @@ -264,11 +266,9 @@ std::shared_ptr FlightSqlStatement::GetTypeInfo_V2(int16_t data_type) auto transformer = std::make_shared( metadata_settings_, OdbcVersion::V_2, data_type); - current_result_set_ = std::make_shared( + return SetCurrentResultSet(std::make_shared( sql_client_, client_options_, call_options_, flight_info, transformer, diagnostics_, - metadata_settings_); - - return current_result_set_; + metadata_settings_)); } std::shared_ptr FlightSqlStatement::GetTypeInfo_V3(int16_t data_type) { @@ -282,18 +282,21 @@ std::shared_ptr FlightSqlStatement::GetTypeInfo_V3(int16_t data_type) auto transformer = std::make_shared( metadata_settings_, OdbcVersion::V_3, data_type); - current_result_set_ = std::make_shared( + return SetCurrentResultSet(std::make_shared( sql_client_, client_options_, call_options_, flight_info, transformer, diagnostics_, - metadata_settings_); - - return current_result_set_; + metadata_settings_)); } Diagnostics& FlightSqlStatement::GetDiagnostics() { return diagnostics_; } void FlightSqlStatement::Cancel() { - if (!current_result_set_) return; - current_result_set_->Cancel(); + std::shared_ptr result_set; + { + std::lock_guard guard(current_result_set_mutex_); + result_set = current_result_set_; + } + if (!result_set) return; + result_set->Cancel(); } } // namespace arrow::flight::sql::odbc diff --git a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_statement.h b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_statement.h index f9b9cd75611d..1024ea791c49 100644 --- a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_statement.h +++ b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_statement.h @@ -26,6 +26,7 @@ #include "arrow/flight/sql/api.h" #include "arrow/flight/types.h" +#include #include namespace arrow::flight::sql::odbc { @@ -37,6 +38,9 @@ class FlightSqlStatement : public Statement { FlightClientOptions client_options_; FlightCallOptions call_options_; FlightSqlClient& sql_client_; + // Guards current_result_set_, since Cancel() (SQLCancel) must be safe to call + // from a thread other than the one currently executing/fetching this statement. + std::mutex current_result_set_mutex_; std::shared_ptr current_result_set_; std::shared_ptr prepared_statement_; const MetadataSettings& metadata_settings_; @@ -47,6 +51,9 @@ class FlightSqlStatement : public Statement { const std::string* table_type, const ColumnNames& column_names); + // Thread-safe setter/getter for current_result_set_ + std::shared_ptr SetCurrentResultSet(std::shared_ptr result_set); + public: FlightSqlStatement(const Diagnostics& diagnostics, FlightSqlClient& sql_client, FlightClientOptions client_options, FlightCallOptions call_options, diff --git a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer.cc b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer.cc index 45c5f3a91263..d0dcf81ec625 100644 --- a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer.cc +++ b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer.cc @@ -58,6 +58,11 @@ FlightStreamChunkBuffer::FlightStreamChunkBuffer( util::ThrowIfNotOK(result.status()); std::shared_ptr stream_reader_ptr(std::move(result.ValueOrDie())); + { + std::lock_guard guard(readers_mutex_); + stream_readers_.push_back(stream_reader_ptr); + } + BlockingQueue, std::shared_ptr>>::Supplier supplier = [=]() -> std::optional< @@ -82,15 +87,24 @@ FlightStreamChunkBuffer::FlightStreamChunkBuffer( } bool FlightStreamChunkBuffer::GetNext(FlightStreamChunk* chunk) { + // fetch_in_progress_ is set by the caller's FetchGuard for the whole fetch + // operation, which may span several GetNext() calls; this call itself does not + // own that flag. std::pair, std::shared_ptr> closeable_endpoint_stream_pair; if (!queue_.Pop(&closeable_endpoint_stream_pair)) { + if (cancelled_) { + throw DriverException("Query was canceled", "HY008"); + } return false; } Result result = closeable_endpoint_stream_pair.first; if (!result.status().ok()) { Close(); + if (cancelled_) { + throw DriverException("Query was canceled", "HY008"); + } throw DriverException(result.status().message()); } *chunk = std::move(result.ValueOrDie()); @@ -99,6 +113,22 @@ bool FlightStreamChunkBuffer::GetNext(FlightStreamChunk* chunk) { void FlightStreamChunkBuffer::Close() { queue_.Close(); } +void FlightStreamChunkBuffer::Cancel() { + std::lock_guard guard(readers_mutex_); + // Per ODBC 3.5, SQLCancel has no effect when no processing is active: only + // interrupt a GetNext() that is actually blocked waiting for a chunk, and + // otherwise leave the producers and any already-buffered rows alone. + if (!fetch_in_progress_) { + return; + } + + cancelled_ = true; + for (const auto& reader : stream_readers_) { + reader->Cancel(); + } + queue_.Close(); +} + FlightStreamChunkBuffer::~FlightStreamChunkBuffer() { Close(); } } // namespace arrow::flight::sql::odbc diff --git a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer.h b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer.h index 696e67e5aa7b..61e457487c46 100644 --- a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer.h +++ b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer.h @@ -17,6 +17,10 @@ #pragma once +#include +#include +#include + #include "arrow/flight/client.h" #include "arrow/flight/sql/client.h" #include "arrow/flight/sql/odbc/odbc_impl/blocking_queue.h" @@ -28,6 +32,16 @@ class FlightStreamChunkBuffer { std::pair, std::shared_ptr>> queue_; + // Keep each endpoint’s DoGet stream reader so Cancel() can interrupt a producer + // blocked in Next() while waiting for the network. + std::mutex readers_mutex_; + std::vector> stream_readers_; + // Set only when Cancel() actually interrupts an in-progress fetch (see Cancel()), + // so GetNext() can tell a cancellation apart from a normal end of stream. + std::atomic cancelled_{false}; + // It's true when fetch is operating. + std::atomic fetch_in_progress_{false}; + public: FlightStreamChunkBuffer(FlightSqlClient& flight_sql_client, const FlightClientOptions& client_options, @@ -39,7 +53,29 @@ class FlightStreamChunkBuffer { void Close(); + // Cancels the underlying DoGet stream(s) so any producer thread blocked on a + // network read returns promptly, then closes the queue. Safe to call from a + // different thread than the one fetching rows. + void Cancel(); + bool GetNext(FlightStreamChunk* chunk); + + // This guard marks the fetch as active while it exists, even if the fetch + // reads several chunks with multiple `GetNext()` calls. This allows `Cancel()` + // to stop the fetch between chunks, not just while `GetNext()` is waiting + // for the next chunk. + class FetchGuard { + public: + explicit FetchGuard(FlightStreamChunkBuffer& buffer) : buffer_(buffer) { + buffer_.fetch_in_progress_ = true; + } + FetchGuard(const FetchGuard&) = delete; + FetchGuard& operator=(const FetchGuard&) = delete; + ~FetchGuard() { buffer_.fetch_in_progress_ = false; } + + private: + FlightStreamChunkBuffer& buffer_; + }; }; } // namespace arrow::flight::sql::odbc diff --git a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer_test.cc b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer_test.cc index 79f20cd8c4a0..41c749d61b45 100644 --- a/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer_test.cc +++ b/cpp/src/arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer_test.cc @@ -19,6 +19,7 @@ #include "arrow/testing/gtest_util.h" +#include "arrow/flight/sql/odbc/odbc_impl/exceptions.h" #include "arrow/flight/sql/odbc/odbc_impl/flight_sql_stream_chunk_buffer.h" #include "arrow/flight/sql/odbc/odbc_impl/json_converter.h" #include "arrow/flight/test_flight_server.h" @@ -151,4 +152,32 @@ TEST_F(FlightStreamChunkBufferTest, TestReuseConnectionLocation) { ASSERT_EQ(5, num_chunks); } + +TEST_F(FlightStreamChunkBufferTest, TestCancelDuringFetch) { + ASSERT_OK_AND_ASSIGN(auto client, + arrow::flight::FlightClient::Connect(server_location1)); + FlightSqlClient server1_client(std::move(client)); + + FlightEndpoint endpoint( + {Ticket{"ticket-ints-1"}, {Location::ReuseConnection()}, std::nullopt, {}}); + FlightDescriptor descr{FlightDescriptor::PATH, "", {"examples", "ints"}}; + auto info_ptr = std::make_shared(arrow::flight::MakeFlightInfo( + *arrow::flight::ExampleIntSchema(), descr, {endpoint}, 1000, 100000, false, "")); + + FlightStreamChunkBuffer chunk_buffer(server1_client, FlightClientOptions::Defaults(), + FlightCallOptions(), info_ptr); + FlightStreamChunk chunk; + + // FetchGuard marks the fetch active without ever blocking in GetNext(). Cancel() + // must still take effect here, not only while GetNext() itself is blocked. + FlightStreamChunkBuffer::FetchGuard fetch_guard(chunk_buffer); + chunk_buffer.Cancel(); + + try { + chunk_buffer.GetNext(&chunk); + FAIL() << "Expected GetNext() to throw after Cancel()"; + } catch (const DriverException& e) { + EXPECT_EQ("HY008", e.GetSqlState()); + } +} } // namespace arrow::flight::sql::odbc diff --git a/cpp/src/arrow/flight/sql/odbc/tests/odbc_test_suite.cc b/cpp/src/arrow/flight/sql/odbc/tests/odbc_test_suite.cc index 79a8ed9f88cd..476d7260b39d 100644 --- a/cpp/src/arrow/flight/sql/odbc/tests/odbc_test_suite.cc +++ b/cpp/src/arrow/flight/sql/odbc/tests/odbc_test_suite.cc @@ -499,8 +499,7 @@ bool CompareConnPropertyMap(Connection::ConnPropertyMap map1, return true; } -void VerifyOdbcErrorState(SQLSMALLINT handle_type, SQLHANDLE handle, - std::string_view expected_state) { +std::string GetOdbcErrorState(SQLSMALLINT handle_type, SQLHANDLE handle) { using ODBC::SqlWcharToString; SQLWCHAR sql_state[7] = {}; @@ -514,7 +513,12 @@ void VerifyOdbcErrorState(SQLSMALLINT handle_type, SQLHANDLE handle, SQLGetDiagRec(handle_type, handle, 1, sql_state, &native_code, message, kOdbcBufferSize, &real_len); - EXPECT_EQ(expected_state, SqlWcharToString(sql_state)); + return SqlWcharToString(sql_state); +} + +void VerifyOdbcErrorState(SQLSMALLINT handle_type, SQLHANDLE handle, + std::string_view expected_state) { + EXPECT_EQ(expected_state, GetOdbcErrorState(handle_type, handle)); } std::string GetOdbcErrorMessage(SQLSMALLINT handle_type, SQLHANDLE handle) { diff --git a/cpp/src/arrow/flight/sql/odbc/tests/odbc_test_suite.h b/cpp/src/arrow/flight/sql/odbc/tests/odbc_test_suite.h index f4de85f69938..d3915539df1d 100644 --- a/cpp/src/arrow/flight/sql/odbc/tests/odbc_test_suite.h +++ b/cpp/src/arrow/flight/sql/odbc/tests/odbc_test_suite.h @@ -246,6 +246,9 @@ bool CompareConnPropertyMap(Connection::ConnPropertyMap map1, /// Get error message from ODBC driver using SQLGetDiagRec std::string GetOdbcErrorMessage(SQLSMALLINT handle_type, SQLHANDLE handle); +/// Get SQLSTATE from ODBC driver using SQLGetDiagRec +std::string GetOdbcErrorState(SQLSMALLINT handle_type, SQLHANDLE handle); + static constexpr std::string_view kErrorState01004 = "01004"; static constexpr std::string_view kErrorState01S02 = "01S02"; static constexpr std::string_view kErrorState01S07 = "01S07"; @@ -256,6 +259,7 @@ static constexpr std::string_view kErrorState24000 = "24000"; static constexpr std::string_view kErrorState28000 = "28000"; static constexpr std::string_view kErrorStateHY000 = "HY000"; static constexpr std::string_view kErrorStateHY004 = "HY004"; +static constexpr std::string_view kErrorStateHY008 = "HY008"; static constexpr std::string_view kErrorStateHY009 = "HY009"; static constexpr std::string_view kErrorStateHY010 = "HY010"; static constexpr std::string_view kErrorStateHY017 = "HY017"; diff --git a/cpp/src/arrow/flight/sql/odbc/tests/statement_test.cc b/cpp/src/arrow/flight/sql/odbc/tests/statement_test.cc index ae9e37239fba..0140c9ab7c0e 100644 --- a/cpp/src/arrow/flight/sql/odbc/tests/statement_test.cc +++ b/cpp/src/arrow/flight/sql/odbc/tests/statement_test.cc @@ -22,7 +22,10 @@ #include #include +#include +#include #include +#include #include #include @@ -2276,4 +2279,139 @@ TYPED_TEST(StatementTest, TestSQLCloseCursorWithoutCursor) { VerifyOdbcErrorState(SQL_HANDLE_STMT, this->stmt, kErrorState24000); } +TYPED_TEST(StatementTest, TestSQLCancelBeforeQuery) { + ASSERT_EQ(SQL_SUCCESS, SQLCancel(this->stmt)); + + ASSIGN_SQLWCHAR_ARR_AND_LEN(wsql, L"SELECT 1;"); + ASSERT_EQ(SQL_SUCCESS, SQLExecDirect(this->stmt, wsql, wsql_len)); + ASSERT_EQ(SQL_SUCCESS, SQLFetch(this->stmt)) + << GetOdbcErrorMessage(SQL_HANDLE_STMT, this->stmt); + + SQLINTEGER val; + ASSERT_EQ(SQL_SUCCESS, SQLGetData(this->stmt, 1, SQL_C_LONG, &val, 0, nullptr)); + EXPECT_EQ(1, val); +} + +TYPED_TEST(StatementTest, TestSQLCancelOnIdleStatement) { + ASSIGN_SQLWCHAR_ARR_AND_LEN(wsql, L"SELECT 1;"); + + ASSERT_EQ(SQL_SUCCESS, SQLExecDirect(this->stmt, wsql, wsql_len)); + + ASSERT_EQ(SQL_SUCCESS, SQLCancel(this->stmt)); + +#ifdef _WIN32 + // The Windows Driver Manager forwards SQLCancel straight to the driver, and per + // ODBC 3.5 it has no effect when no fetch is in progress: the cursor stays open + // and fetching proceeds normally. + ASSERT_EQ(SQL_SUCCESS, SQLFetch(this->stmt)) + << GetOdbcErrorMessage(SQL_HANDLE_STMT, this->stmt); + + SQLINTEGER val; + ASSERT_EQ(SQL_SUCCESS, SQLGetData(this->stmt, 1, SQL_C_LONG, &val, 0, nullptr)); + EXPECT_EQ(1, val); +#else + // unixODBC and iODBC instead apply the legacy ODBC 2.x behavior unconditionally: + // SQLCancel with no function in progress and an open cursor closes that cursor, + // the same as SQLFreeStmt(SQL_CLOSE), before the call ever reaches the driver. + // This is a Driver Manager limitation that the driver cannot prevent. + ASSERT_EQ(SQL_ERROR, SQLFetch(this->stmt)); +# ifdef __APPLE__ + VerifyOdbcErrorState(SQL_HANDLE_STMT, this->stmt, kErrorStateS1010); +# else + VerifyOdbcErrorState(SQL_HANDLE_STMT, this->stmt, kErrorStateHY010); +# endif // __APPLE__ +#endif // _WIN32 +} + +// GH-55800 TODO: Implement mock server that can run an interruptible query, and add a +// test that cancels it and verifies execution actually stops server-side. + +// Regression test for GH-55790: SQLCancel must be safe to call from a thread other +// than the one fetching rows, and must cause a blocked/in-progress fetch to stop +// promptly rather than hang until the whole result set has been read. +TYPED_TEST(StatementTest, TestSQLCancelDuringFetch) { + // A plain (non-recursive) CTE cross-joined with itself a few times, to produce + // a large result set (20^4 = 160000 rows) using only portable SQL. + ASSIGN_SQLWCHAR_ARR_AND_LEN( + wsql, + L"WITH v(x) AS (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)," + L"(11),(12),(13),(14),(15),(16),(17),(18),(19),(20)) " + L"SELECT a.x FROM v a CROSS JOIN v b CROSS JOIN v c CROSS JOIN v d;"); + + ASSERT_EQ(SQL_SUCCESS, SQLExecDirect(this->stmt, wsql, wsql_len)) + << GetOdbcErrorMessage(SQL_HANDLE_STMT, this->stmt); + + std::atomic fetch_started{false}; + std::atomic fetch_done{false}; + std::atomic rows_fetched{0}; + std::atomic final_rc{SQL_SUCCESS}; + std::string captured_error_state; + std::thread fetch_thread([&]() { + fetch_started = true; + SQLINTEGER val; + while (true) { + SQLRETURN rc = SQLFetch(this->stmt); + if (rc != SQL_SUCCESS) { + final_rc = rc; + captured_error_state = GetOdbcErrorState(SQL_HANDLE_STMT, this->stmt); + break; + } + rc = SQLGetData(this->stmt, 1, SQL_C_LONG, &val, 0, nullptr); + if (rc != SQL_SUCCESS) { + final_rc = rc; + captured_error_state = GetOdbcErrorState(SQL_HANDLE_STMT, this->stmt); + break; + } + rows_fetched++; + } + fetch_done = true; + }); + // Guarantee fetch_thread is always joined + struct JoinOnExit { + std::thread& t; + ~JoinOnExit() { + if (t.joinable()) { + t.join(); + } + } + } join_fetch_thread_on_exit{fetch_thread}; + + while (!fetch_started) { + std::this_thread::yield(); + } + + // The mock server fetches rows so quickly that SQLCancel may not be called + // before the fetch finishes. Instead, keep calling SQLCancel in a loop + // until the fetch stops, re-checking fetch_done right after each call so we + // stop as soon as possible to avoid redundant calls. + while (!fetch_done.load()) { + SQLCancel(this->stmt); + if (fetch_done.load()) { + break; + } + std::this_thread::yield(); + } + + fetch_thread.join(); + + // The cancel should have interrupted the fetch well before all 160000 rows were + // read, and the interrupted call must report an error. + EXPECT_LT(rows_fetched.load(), 160000); + ASSERT_EQ(SQL_ERROR, final_rc.load()); +#ifdef _WIN32 + // On Windows the cancellation reaches the driver untouched, so the interrupted + // call reports HY008 (operation canceled) as the driver intended. + EXPECT_EQ(kErrorStateHY008, captured_error_state); +#elif defined(__APPLE__) + // iODBC's own sequence bookkeeping (see TestSQLCancelOnIdleStatement) can + // intercept a SQLCancel that races with a concurrent fetch, not just an idle + // one: depending on exactly when it lands, either the driver's own HY008 or + // the Driver Manager's own function sequence error can legitimately surface. + EXPECT_THAT(captured_error_state, ::testing::AnyOf(kErrorStateHY008, kErrorStateS1010)); +#else + // unixODBC's sequence bookkeeping consistently reports HY010 + EXPECT_EQ(kErrorStateHY010, captured_error_state); +#endif +} + } // namespace arrow::flight::sql::odbc