Skip to content

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

Draft
gargsaumya wants to merge 13 commits into
mainfrom
saumya/gh-570
Draft

FEAT: Support for Apache Arrow in Bulk Copy API#665
gargsaumya wants to merge 13 commits 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 bulkcopy_arrow method to the Cursor class for bulk loading data directly from Apache Arrow sources, along with several related improvements and refactorings. It also updates type stubs and documentation to reflect the new API, and improves bulk copy authentication handling by refactoring shared logic.

New feature: Arrow-based bulk copy

  • Added Cursor.bulkcopy_arrow(table_name, source) for efficient bulk loading from Arrow sources (e.g., pyarrow.Table, RecordBatch, objects exposing the Arrow C Data Interface). This avoids unnecessary Python row materialization and is significantly faster for Arrow-native data. [1] [2]
  • The classic bulkcopy() method now raises a TypeError if given Arrow-shaped data, steering users to the new method.

Codebase refactoring and improvements

  • Refactored connection context and Azure AD authentication logic into a shared _build_pycore_context() helper, used by both bulkcopy and bulkcopy_arrow. This ensures consistent authentication handling and reduces code duplication. [1] [2]
  • Updated type stubs (mssql_python.pyi) to include the new bulkcopy_arrow method and improved the typing for bulkcopy. [1] [2]

Documentation

  • Updated the CHANGELOG.md to document the new Arrow bulk copy feature and its requirements.

Minor improvements

  • Minor code formatting improvement in a test file (test_bulkcopy_udt_geometry).

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
Comment thread tests/test_024_bulkcopy_arrow.py Fixed
Comment thread tests/test_024_bulkcopy_arrow.py Fixed
Comment thread tests/test_024_bulkcopy_arrow.py Fixed
Comment thread tests/test_024_bulkcopy_arrow.py Fixed
Comment thread tests/test_024_bulkcopy_arrow.py Fixed
Comment thread tests/test_024_bulkcopy_arrow.py Fixed

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 thread mssql_python/cursor.py Outdated
@gargsaumya
gargsaumya marked this pull request as draft July 8, 2026 07:47
…sign D13)

Remove the keyword-only '*' from Cursor.bulkcopy_arrow (cursor.py + stub) so batch_size/timeout match bulkcopy's signature per the finalized design (D13/section 2). Also set cursor._timeout in the test mock-cursor helper (main's #650 added self._timeout to the shared _build_pycore_context) and add a positional-args regression test.
Comment thread tests/test_024_bulkcopy_arrow.py Fixed
@github-actions

github-actions Bot commented Jul 29, 2026

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

100%


🎯 Overall Coverage

81%


📈 Total Lines Covered: 7145 out of 8757
📁 Project: mssql-python


Diff Coverage

Diff: main...HEAD, staged and unstaged changes

  • mssql_python/cursor.py (100%)

Summary

  • Total: 80 lines
  • Missing: 0 lines
  • Coverage: 100%

📋 Files Needing Attention

📉 Files with overall lowest coverage (click to expand)
mssql_python.pybind.logger_bridge.cpp: 59.2%
mssql_python.pybind.ddbc_bindings.h: 59.9%
mssql_python.pybind.logger_bridge.hpp: 70.8%
mssql_python.pybind.ddbc_bindings.cpp: 76.3%
mssql_python.__init__.py: 77.3%
mssql_python.row.py: 77.6%
mssql_python.ddbc_bindings.py: 79.6%
mssql_python.pybind.connection.connection_pool.cpp: 81.4%
mssql_python.pybind.connection.connection.cpp: 83.7%
mssql_python.connection.py: 84.7%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

@bewithgaurav bewithgaurav left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

no major problems or blockers found - just some improvements to code structure and a nit miss on error message, will approve once done

Comment thread mssql_python/cursor.py
"""
is_logging_enabled = logger.is_debug_enabled

try:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this preamble is byte-identical to bulkcopy(), as are three other chunks:
the table_name check, the batch_size and timeout validation below it, and the whole finally block with the credential scrub and cleanup. a few lines duplicated across the two methods.

two static helpers cover all four, _bulkcopy_core_and_validate(table_name, batch_size, timeout) returning the module and _bulkcopy_teardown(pycore_context, pycore_cursor, pycore_connection).

I made changes locally, net 43 lines lighter, no flags and no dynamic dispatch

why I pointed:
the except block a few lines down got changed to a bare raise, bulkcopy still does raise type(e)(str(e)) from None - identical code, fixed in one copy, missed in the other

Comment thread mssql_python/cursor.py
Comment on lines +3270 to +3275
if source is None:
raise TypeError(
"source must be a pyarrow Table/RecordBatch/RecordBatchReader, "
"an iterable of RecordBatch, or an object implementing "
"__arrow_c_stream__/__arrow_c_array__, got None"
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: str and bytes slip past this block and fail later with a message that doesn't name the cause:

cursor.bulkcopy_arrow("dbo.T", "data.parquet")
TypeError: iterable must yield pyarrow.RecordBatch instances

both are iterable, so they get treated as an iterable of batches and die on the first character. bulkcopy guards for exactly this a couple hundred lines up and says

  • "got str. Strings and bytes are not valid row collections."

folding it into the existing None check keeps it to one branch:

Suggested change
if source is None:
raise TypeError(
"source must be a pyarrow Table/RecordBatch/RecordBatchReader, "
"an iterable of RecordBatch, or an object implementing "
"__arrow_c_stream__/__arrow_c_array__, got None"
)
if source is None or isinstance(source, (str, bytes)):
got = "None" if source is None else type(source).__name__
raise TypeError(
"source must be a pyarrow Table/RecordBatch/RecordBatchReader, "
"an iterable of RecordBatch, or an object implementing "
f"__arrow_c_stream__/__arrow_c_array__, got {got}"
)

everything else reads fine here. a list of tuples gets the RecordBatch message and that's the correct thing to say. it's only these two types which are missed.

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.

5 participants