Skip to content

FEAT: Support for Apache Arrow in Bulk Copy API#665

Draft
gargsaumya wants to merge 1 commit into
mainfrom
saumya/gh-570
Draft

FEAT: Support for Apache Arrow in Bulk Copy API#665
gargsaumya wants to merge 1 commit into
mainfrom
saumya/gh-570

Conversation

@gargsaumya

@gargsaumya gargsaumya commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

AB#46268

GitHub Issue: #<ISSUE_NUMBER>


Summary

This pull request introduces a new high-performance bulk copy method for Apache Arrow data and refactors the existing bulk copy logic to improve maintainability and error handling. It also adds a comprehensive benchmark for comparing tuple-based and Arrow-based bulk copy performance.

Summary of most important changes:

New Features

  • Added a new Cursor.bulkcopy_arrow(table_name, source) method for high-performance bulk loading of data directly from Apache Arrow sources. This method streams data using the Arrow C Data Interface, bypassing the need to materialize Python row objects and releasing the GIL during transfer. It supports multiple Arrow-compatible sources and is significantly faster for Arrow-originating data. The classic bulkcopy() now raises a TypeError if given Arrow input, steering users to the new method.

Benchmarks

  • Introduced benchmarks/bench_bulkcopy_arrow.py, a benchmark script that compares the performance of bulkcopy() (tuple-based) and bulkcopy_arrow() (Arrow-based) using identical data. The script supports multiple data profiles and row counts, and prints detailed throughput and speedup statistics.

Code Refactoring and Error Handling

  • Refactored connection context parsing and Azure AD authentication logic into a new helper method _build_pycore_context. This ensures both bulkcopy and bulkcopy_arrow use consistent connection and authentication handling, improving code maintainability and reducing duplication. [1] [2]
  • Improved input validation in bulkcopy(): now immediately raises a TypeError if the input is an Arrow source, with a clear message directing users to bulkcopy_arrow().

Adds cursor.bulkcopy_arrow(table_name, source) to bulk-load directly from Apache Arrow data (pyarrow Table/RecordBatch/RecordBatchReader, __arrow_c_stream__/__arrow_c_array__ producers, or an iterable of batches) via the mssql_py_core Rust core, streaming through the Arrow C Data Interface with the GIL released during transfer.

bulkcopy() now raises TypeError to steer Arrow inputs here. Auth setup is refactored into a shared _build_pycore_context() helper (preserves SQL, pre-acquired-token, and ServicePrincipal factory paths). Adds tests/test_024_bulkcopy_arrow.py (36 unit tests at 100% coverage of the new code + 16 live round-trip/type-matrix tests) and benchmarks/bench_bulkcopy_arrow.py. Requires mssql-py-core 0.1.5+.
Copilot AI review requested due to automatic review settings July 8, 2026 07:38
@github-actions github-actions Bot added the pr-size: large Substantial code update label Jul 8, 2026

def test_sql_auth_keeps_credentials(self):
cur = _cursor_with_conn(
"Server=localhost;Database=testdb;UID=sa;PWD=mypwd", auth_type=None
@patch("mssql_python.cursor.logger")
def test_success_returns_result_and_forwards_args(self, mock_logger):
mock_logger.is_debug_enabled = False
cur = _cursor_with_conn("Server=localhost;Database=d;UID=sa;PWD=p")
@patch("mssql_python.cursor.logger")
def test_sensitive_fields_cleared_after_success(self, mock_logger):
mock_logger.is_debug_enabled = False
cur = _cursor_with_conn("Server=localhost;Database=d;UID=sa;PWD=secret")
@patch("mssql_python.cursor.logger")
def test_resources_closed_on_success(self, mock_logger):
mock_logger.is_debug_enabled = False
cur = _cursor_with_conn("Server=localhost;Database=d;UID=sa;PWD=p")
@patch("mssql_python.cursor.logger")
def test_core_exception_is_reraised_and_cleaned_up(self, mock_logger):
mock_logger.is_debug_enabled = False
cur = _cursor_with_conn("Server=localhost;Database=d;UID=sa;PWD=p")
def test_cleanup_swallows_close_errors(self, mock_logger):
"""A failing resource.close() during teardown must not mask the result."""
mock_logger.is_debug_enabled = False
cur = _cursor_with_conn("Server=localhost;Database=d;UID=sa;PWD=p")

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds Apache Arrow support to the Bulk Copy API by introducing a dedicated Cursor.bulkcopy_arrow() path and refactoring shared connection/auth context construction so both tuple-based and Arrow-based bulk copy use consistent handling.

Changes:

  • Added Cursor.bulkcopy_arrow(table_name, source) and Arrow-source detection/steering to prevent Arrow inputs from going through tuple bulkcopy.
  • Refactored bulk-copy connection/auth parsing into Cursor._build_pycore_context() for reuse across bulk copy entry points.
  • Added comprehensive tests and a benchmark comparing tuple vs Arrow bulk copy throughput.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/test_024_bulkcopy_arrow.py Adds unit + live-DB integration coverage for Arrow bulk copy, auth context building, and Arrow-source detection.
mssql_python/mssql_python.pyi Updates public type stubs to include bulkcopy and new bulkcopy_arrow API.
mssql_python/cursor.py Implements _build_pycore_context, Arrow source detection/steering, and the new bulkcopy_arrow method.
CHANGELOG.md Documents the new Arrow bulk copy feature and related requirements/behavior changes.
benchmarks/bench_bulkcopy_arrow.py Adds a benchmark script comparing tuple-based vs Arrow-based bulk copy performance.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread mssql_python/cursor.py
Comment on lines +3014 to +3018
raise TypeError(
"bulkcopy() expects an iterable of row tuples/lists. "
"For pyarrow.Table / RecordBatch / RecordBatchReader / objects "
"implementing __arrow_c_stream__, call cursor.bulkcopy_arrow() instead."
)
Comment thread mssql_python/cursor.py
Comment on lines +3293 to +3300
except Exception as e:
logger.debug(
"bulkcopy_arrow failed for table '%s': %s: %s",
table_name,
type(e).__name__,
str(e),
)
raise type(e)(str(e)) from None
@gargsaumya gargsaumya marked this pull request as draft July 8, 2026 07:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-size: large Substantial code update

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants