sqlalchemy-mssql-bulkcopy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,302 @@
1
+ """SQLAlchemy integration for mssql-python's ``cursor.bulkcopy()``.
2
+
3
+ Uses SQL Server's native TDS bulk load protocol for 10-50x faster writes.
4
+ All ``cursor.bulkcopy()`` kwargs pass through to the driver unchanged.
5
+
6
+ Primary API::
7
+
8
+ from sqlalchemy_mssql_bulkcopy import bulkcopy
9
+
10
+ with engine.begin() as conn:
11
+ result = bulkcopy(conn, df, "dbo.users", batch_size=50_000)
12
+
13
+ Event hook for SA Core/ORM::
14
+
15
+ from sqlalchemy_mssql_bulkcopy import register_bulkcopy
16
+
17
+ engine = create_engine("...", use_insertmanyvalues=False)
18
+ register_bulkcopy(engine)
19
+ conn.execute(
20
+ users.insert().execution_options(use_bulkcopy=True), rows
21
+ )
22
+
23
+ See https://github.com/sqlalchemy/sqlalchemy/issues/13218
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import logging
29
+ from collections.abc import Callable, Iterable
30
+ from importlib.metadata import version as _pkg_version
31
+ from typing import Any
32
+
33
+ from sqlalchemy import event
34
+ from sqlalchemy.engine import Connection, Engine
35
+
36
+ __version__ = _pkg_version(__name__)
37
+ __all__ = [
38
+ "bulkcopy",
39
+ "bulkcopy_insert_method",
40
+ "register_bulkcopy",
41
+ ]
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # Primary API: direct bulkcopy
48
+ # ---------------------------------------------------------------------------
49
+
50
+
51
+ def bulkcopy(
52
+ conn: Connection,
53
+ data: Any,
54
+ table_name: str,
55
+ *,
56
+ columns: list[str] | None = None,
57
+ **kwargs: Any,
58
+ ) -> dict[str, Any]:
59
+ """Bulk-load data into SQL Server via the TDS bulk copy protocol.
60
+
61
+ Accesses the raw DBAPI cursor from *conn* and calls
62
+ ``cursor.bulkcopy()`` directly. No engine configuration required.
63
+ All keyword arguments pass through to the driver unchanged.
64
+
65
+ Parameters
66
+ ----------
67
+ conn : sqlalchemy.engine.Connection
68
+ An active SA connection (from ``engine.connect()`` or
69
+ ``engine.begin()``).
70
+ data : DataFrame | Iterable[tuple | list]
71
+ Rows to load. DataFrames are auto-converted; column names
72
+ are extracted unless *columns* is provided explicitly.
73
+ table_name : str
74
+ Target table, optionally schema-qualified (``"dbo.users"``).
75
+ columns : list[str] | None
76
+ Column names passed as ``column_mappings`` to the driver.
77
+ Auto-detected from DataFrames.
78
+ **kwargs
79
+ Forwarded to ``cursor.bulkcopy()``. See mssql-python docs
80
+ for the full list: ``batch_size``, ``table_lock``,
81
+ ``keep_identity``, ``check_constraints``, ``fire_triggers``,
82
+ ``keep_nulls``, ``timeout``, ``use_internal_transaction``.
83
+
84
+ Returns
85
+ -------
86
+ dict[str, Any]
87
+ Driver result: ``rows_copied``, ``batch_count``,
88
+ ``elapsed_time``.
89
+
90
+ Raises
91
+ ------
92
+ AttributeError
93
+ If the cursor does not have a ``bulkcopy`` method (wrong
94
+ driver or driver version < 1.4).
95
+ """
96
+ dbapi_conn = conn.connection.dbapi_connection
97
+ rows, columns = _normalize_data(data, columns)
98
+
99
+ if not rows:
100
+ return {"rows_copied": 0, "batch_count": 0, "elapsed_time": 0.0}
101
+
102
+ if columns is not None:
103
+ kwargs["column_mappings"] = columns
104
+
105
+ cursor = dbapi_conn.cursor()
106
+ try:
107
+ result: dict[str, Any] = cursor.bulkcopy(table_name, rows, **kwargs)
108
+ finally:
109
+ cursor.close()
110
+
111
+ logger.info(
112
+ "bulkcopy: %d rows -> %s (%.3fs)",
113
+ result.get("rows_copied", len(rows)),
114
+ table_name,
115
+ result.get("elapsed_time", 0),
116
+ )
117
+ return result
118
+
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # Event hook for SA Core / ORM
122
+ # ---------------------------------------------------------------------------
123
+
124
+
125
+ def register_bulkcopy(
126
+ engine: Engine,
127
+ *,
128
+ on_complete: Callable[[str, dict[str, Any]], Any] | None = None,
129
+ **defaults: Any,
130
+ ) -> None:
131
+ """Register a ``do_executemany`` event hook that routes INSERT
132
+ batches through ``cursor.bulkcopy()`` when
133
+ ``execution_options(use_bulkcopy=True)`` is set.
134
+
135
+ Parameters
136
+ ----------
137
+ engine : Engine
138
+ **Must** be created with ``use_insertmanyvalues=False``.
139
+ SA 2.x defaults to multi-row ``INSERT … VALUES`` batching
140
+ which bypasses ``executemany()`` entirely; without this flag
141
+ the event hook will never fire.
142
+ on_complete : callable | None
143
+ ``on_complete(table_name, result_dict)`` is called after each
144
+ successful bulkcopy. Errors in the callback propagate to the
145
+ caller (they do **not** trigger the executemany fallback).
146
+ **defaults
147
+ Default kwargs forwarded to ``cursor.bulkcopy()``.
148
+ Overridable per-statement via
149
+ ``execution_options(bulkcopy_<key>=value)``.
150
+
151
+ Raises
152
+ ------
153
+ ValueError
154
+ If the engine's dialect has ``use_insertmanyvalues`` enabled.
155
+ """
156
+ if getattr(engine.dialect, "use_insertmanyvalues", False):
157
+ raise ValueError(
158
+ "register_bulkcopy() requires use_insertmanyvalues=False. "
159
+ "SA 2.x defaults to multi-row INSERT batching which "
160
+ "bypasses executemany() — the event hook will never fire. "
161
+ "Create the engine with: "
162
+ "create_engine(..., use_insertmanyvalues=False) "
163
+ "This does not affect bulkcopy(); only register_bulkcopy() "
164
+ "has this requirement."
165
+ )
166
+
167
+ @event.listens_for(engine, "do_executemany", retval=True)
168
+ def _do_bulkcopy(
169
+ cursor: Any,
170
+ statement: str,
171
+ parameters: Any,
172
+ context: Any,
173
+ ) -> bool:
174
+ opts = context.execution_options
175
+ if not opts.get("use_bulkcopy", False):
176
+ return False
177
+
178
+ if not hasattr(cursor, "bulkcopy"):
179
+ logger.debug(
180
+ "use_bulkcopy set but cursor has no bulkcopy method; falling back to executemany"
181
+ )
182
+ return False
183
+
184
+ try:
185
+ table = context.compiled.statement.table
186
+ except AttributeError:
187
+ logger.debug(
188
+ "use_bulkcopy set but no table metadata on compiled "
189
+ "statement; falling back to executemany"
190
+ )
191
+ return False
192
+
193
+ # Schema-qualified table name
194
+ schema = table.schema or context.dialect.default_schema_name
195
+ table_name = f"{schema}.{table.name}" if schema else table.name
196
+
197
+ # Map SA column keys → DB column names (key != name when
198
+ # Column("db_name", key="python_name") is used)
199
+ col_names = [table.c[key].name for key in context.compiled.column_keys]
200
+
201
+ # SA sends tuples for qmark paramstyle (mssql-python) and
202
+ # dicts for named paramstyle. Handle both.
203
+ if parameters and isinstance(parameters[0], dict):
204
+ rows = [tuple(row[key] for key in context.compiled.column_keys) for row in parameters]
205
+ else:
206
+ rows = [tuple(row) for row in parameters]
207
+
208
+ # Engine defaults ← per-statement overrides (bulkcopy_ prefix)
209
+ bcp_kwargs: dict[str, Any] = {**defaults}
210
+ bcp_kwargs["column_mappings"] = col_names
211
+ for key, value in opts.items():
212
+ if key.startswith("bulkcopy_"):
213
+ bcp_kwargs[key.removeprefix("bulkcopy_")] = value
214
+
215
+ try:
216
+ result = cursor.bulkcopy(table_name, rows, **bcp_kwargs)
217
+ except Exception:
218
+ logger.warning(
219
+ "bulkcopy failed for %s; falling back to executemany",
220
+ table_name,
221
+ exc_info=True,
222
+ )
223
+ return False
224
+
225
+ logger.info(
226
+ "bulkcopy: %d rows -> %s (%d cols)",
227
+ len(rows),
228
+ table_name,
229
+ len(col_names),
230
+ )
231
+
232
+ # Callback runs outside try/except so errors propagate
233
+ # to the caller instead of silently triggering fallback.
234
+ if on_complete is not None:
235
+ on_complete(table_name, result)
236
+
237
+ return True
238
+
239
+
240
+ # ---------------------------------------------------------------------------
241
+ # Pandas helper
242
+ # ---------------------------------------------------------------------------
243
+
244
+
245
+ def bulkcopy_insert_method(
246
+ table: Any,
247
+ conn: Any,
248
+ keys: list[str],
249
+ data_iter: Iterable[tuple[Any, ...]],
250
+ ) -> None:
251
+ """``method`` callable for :meth:`~pandas.DataFrame.to_sql`.
252
+
253
+ Requires :func:`register_bulkcopy` on the engine::
254
+
255
+ df.to_sql("users", engine, method=bulkcopy_insert_method,
256
+ if_exists="append", index=False)
257
+ """
258
+ from sqlalchemy import insert as sa_insert
259
+
260
+ data = [dict(zip(keys, row, strict=True)) for row in data_iter]
261
+ if not data:
262
+ return
263
+
264
+ sa_table = getattr(table, "table", table)
265
+ stmt = sa_insert(sa_table).execution_options(use_bulkcopy=True)
266
+ conn.execute(stmt, data)
267
+
268
+
269
+ # ---------------------------------------------------------------------------
270
+ # Internal helpers
271
+ # ---------------------------------------------------------------------------
272
+
273
+
274
+ def _normalize_data(
275
+ data: Any,
276
+ columns: list[str] | None,
277
+ ) -> tuple[list[tuple[Any, ...]], list[str] | None]:
278
+ """Convert input to ``(list_of_tuples, columns)``.
279
+
280
+ Handles DataFrames, generators, lists-of-lists, and plain tuples.
281
+ Extracts column names from DataFrames when *columns* is ``None``.
282
+ """
283
+ try:
284
+ import pandas as pd
285
+
286
+ if isinstance(data, pd.DataFrame):
287
+ if columns is None:
288
+ columns = list(data.columns)
289
+ return list(data.itertuples(index=False, name=None)), columns
290
+ except ImportError:
291
+ pass
292
+
293
+ if not isinstance(data, list):
294
+ data = list(data)
295
+
296
+ if not data:
297
+ return data, columns
298
+
299
+ if not isinstance(data[0], tuple):
300
+ return [tuple(row) for row in data], columns
301
+
302
+ return data, columns
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
File without changes
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqlalchemy-mssql-bulkcopy
3
+ Version: 0.1.0
4
+ Summary: Bulk copy for SQLAlchemy + mssql-python — 10-50x faster writes via SQL Server's native TDS protocol
5
+ Author: Daniel Caspi
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/dxdc/sqlalchemy-mssql-bulkcopy
8
+ Project-URL: Issues, https://github.com/dxdc/sqlalchemy-mssql-bulkcopy/issues
9
+ Project-URL: Changelog, https://github.com/dxdc/sqlalchemy-mssql-bulkcopy/releases
10
+ Keywords: sqlalchemy,mssql,sql-server,bulk-copy,pandas,mssql-python,bulkcopy,tds,etl
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Database
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: sqlalchemy>=2.1.0b1
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8.0; extra == "dev"
27
+ Requires-Dist: pytest-cov>=6.0; extra == "dev"
28
+ Requires-Dist: pandas>=2.0; extra == "dev"
29
+ Requires-Dist: mssql-python>=1.4.0; extra == "dev"
30
+ Requires-Dist: ruff>=0.9; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # sqlalchemy-mssql-bulkcopy
34
+
35
+ [![CI](https://github.com/dxdc/sqlalchemy-mssql-bulkcopy/actions/workflows/ci.yml/badge.svg)](https://github.com/dxdc/sqlalchemy-mssql-bulkcopy/actions/workflows/ci.yml)
36
+ [![PyPI](https://img.shields.io/pypi/v/sqlalchemy-mssql-bulkcopy)](https://pypi.org/project/sqlalchemy-mssql-bulkcopy/)
37
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
38
+
39
+ Bulk copy for SQLAlchemy + mssql-python — 10–50× faster writes via
40
+ SQL Server's native TDS bulk load protocol.
41
+
42
+ All `cursor.bulkcopy()` kwargs pass through to the driver. When
43
+ mssql-python adds new options, this package supports them automatically.
44
+
45
+ Based on the [event hook approach recommended by SQLAlchemy's maintainer](https://github.com/sqlalchemy/sqlalchemy/issues/13218).
46
+
47
+ ## Install
48
+
49
+ The `mssql+mssqlpython` dialect requires SQLAlchemy ≥ 2.1.0b2,
50
+ which is not yet on PyPI. Install SA from git until then:
51
+
52
+ ```bash
53
+ pip install "sqlalchemy @ git+https://github.com/sqlalchemy/sqlalchemy.git@main"
54
+ pip install sqlalchemy-mssql-bulkcopy
55
+ ```
56
+
57
+ Once SA 2.1 is stable:
58
+
59
+ ```bash
60
+ pip install sqlalchemy-mssql-bulkcopy
61
+ ```
62
+
63
+ Requires Python ≥ 3.10, SQLAlchemy ≥ 2.1, mssql-python ≥ 1.4.
64
+
65
+ ## Usage
66
+
67
+ ### Direct (recommended)
68
+
69
+ No engine configuration needed. Returns the driver result dict.
70
+
71
+ ```python
72
+ from sqlalchemy import create_engine
73
+ from sqlalchemy_mssql_bulkcopy import bulkcopy
74
+
75
+ engine = create_engine("mssql+mssqlpython://user:pass@host/db")
76
+
77
+ with engine.begin() as conn:
78
+ result = bulkcopy(conn, df, "dbo.users", batch_size=50_000)
79
+ print(f"{result['rows_copied']} rows in {result['elapsed_time']:.2f}s")
80
+ ```
81
+
82
+ Accepts DataFrames (columns auto-detected), lists of tuples, generators,
83
+ or any iterable:
84
+
85
+ ```python
86
+ # All driver options pass through as kwargs
87
+ result = bulkcopy(
88
+ conn, df, "staging.events",
89
+ batch_size=100_000,
90
+ table_lock=True,
91
+ keep_identity=True,
92
+ check_constraints=True,
93
+ fire_triggers=True,
94
+ keep_nulls=True,
95
+ timeout=300,
96
+ use_internal_transaction=True,
97
+ )
98
+ ```
99
+
100
+ ### Event hook (SA Core / ORM)
101
+
102
+ Hooks into SQLAlchemy's INSERT workflow. Per-statement opt-in via
103
+ execution options:
104
+
105
+ ```python
106
+ from sqlalchemy_mssql_bulkcopy import register_bulkcopy
107
+
108
+ engine = create_engine(
109
+ "mssql+mssqlpython://user:pass@host/db",
110
+ use_insertmanyvalues=False, # required — see note below
111
+ )
112
+ register_bulkcopy(engine, batch_size=10_000, table_lock=True)
113
+
114
+ with engine.begin() as conn:
115
+ conn.execute(
116
+ users.insert().execution_options(use_bulkcopy=True),
117
+ rows,
118
+ )
119
+ ```
120
+
121
+ Per-statement overrides use the `bulkcopy_` prefix:
122
+
123
+ ```python
124
+ stmt = users.insert().execution_options(
125
+ use_bulkcopy=True,
126
+ bulkcopy_batch_size=100_000,
127
+ bulkcopy_fire_triggers=True,
128
+ )
129
+ ```
130
+
131
+ > **Note:** `register_bulkcopy()` raises `ValueError` if
132
+ > `use_insertmanyvalues` is not disabled. SA 2.x defaults to multi-row
133
+ > `INSERT … VALUES` batching which bypasses `executemany()` entirely —
134
+ > the event hook never fires without this flag. This is a global engine
135
+ > setting: non-bulkcopy inserts will use `executemany()` instead, which
136
+ > is slightly slower for medium-sized batches. If that matters, use
137
+ > `bulkcopy()` directly instead.
138
+
139
+ ### Pandas
140
+
141
+ ```python
142
+ from sqlalchemy_mssql_bulkcopy import bulkcopy_insert_method
143
+
144
+ df.to_sql("users", engine, method=bulkcopy_insert_method,
145
+ if_exists="append", index=False)
146
+ ```
147
+
148
+ ## Confirming bulkcopy was used
149
+
150
+ ```python
151
+ # Direct — return value
152
+ result = bulkcopy(conn, df, "dbo.users")
153
+ assert result["rows_copied"] == len(df)
154
+
155
+ # Event hook — on_complete callback
156
+ results = []
157
+ register_bulkcopy(engine, on_complete=lambda t, r: results.append(r))
158
+ ```
159
+
160
+ Both approaches log at INFO level:
161
+ `bulkcopy: 1000 rows -> dbo.users (0.050s)`
162
+
163
+ ## License
164
+
165
+ MIT
@@ -0,0 +1,8 @@
1
+ sqlalchemy_mssql_bulkcopy/__init__.py,sha256=xyv-uAB7SiU8999QGds56ZDasS0llGaPq7NN83ZSPkE,9723
2
+ sqlalchemy_mssql_bulkcopy/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
3
+ sqlalchemy_mssql_bulkcopy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ sqlalchemy_mssql_bulkcopy-0.1.0.dist-info/licenses/LICENSE,sha256=b_V-8rBn8J8Kv6QmpyrZgFijN99-FtuK_JuGEL9Bf9s,1069
5
+ sqlalchemy_mssql_bulkcopy-0.1.0.dist-info/METADATA,sha256=dFKt-_-wYkgE3vuCTdZzw8pV59BYYgt3S8ZzadWZaV0,5125
6
+ sqlalchemy_mssql_bulkcopy-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
7
+ sqlalchemy_mssql_bulkcopy-0.1.0.dist-info/top_level.txt,sha256=hNYCeNLYd0056hxaQNC2B40n5rwPt8va-izV9KpYH-s,26
8
+ sqlalchemy_mssql_bulkcopy-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daniel Caspi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ sqlalchemy_mssql_bulkcopy