Repository navigation
PERF: single-pass pyformat to qmark conversion, cached per statement - #888
Conversation
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
PR Performance Report✅ No regression detectedNo consistent slowdowns detected across all 2 environments. 0 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS Coverage: 2 of 2 environments completed. Advisory result; does not block merging. Performance diagnosticsPhase times are inclusive diagnostics and must not be added together. They identify where measured time changed, not why it changed. No affected phases or call-count changes were recorded. All database tasks and timingsUnix / SQL Server 2022
Unix / SQL Server 2025
Build and measurement detailsPR head:
A consistent change requires more than 20% median paired movement, at least 1 ms between the median runtimes, and at least 80% of pairs exceeding the relative threshold in the same direction. A slowdown without enough pair agreement is reported as inconsistent. The displayed change is the median of paired before-and-after ratios. It is not recalculated from the two displayed median runtimes. Both revisions use profiling-enabled builds on the same agent and database, with alternating order and discarded warmups. Results are diagnostic and do not represent production-wheel latency. Raw samples and logs are attached to the ADO run as |
|
@microsoft-github-policy-service agree |
There was a problem hiding this comment.
🔵 Needs a closer look
Unavailable native-built, live SQL Server validation and matched base/PR benchmarks leave SQLAlchemy execute(), dict-based executemany(), and claimed throughput gains unverified.
No open issues 🎉
What changed in this PR
This follow-up to #500 optimizes pyformat parameter conversion in the Python driver, targeting repeated, parameter-heavy SQLAlchemy statements.
Changes:
- Replaces per-parameter SQL replacements with a position-based rewrite and a 32-entry statement cache.
- Preserves placeholder-like text in quoted SQL and comments, and fixes escaped-percent and sentinel-collision handling.
- Adds regression tests for large inserts, cache reuse, missing parameters, and parameter-style validation.
| File | Description |
|---|---|
tests/test_015_pyformat_parameters.py |
Adds conversion, escaping, validation, and cache-reuse regression tests. |
mssql_python/parameter_helper.py |
Implements cached, position-based conversion and reduces unnecessary scanning and debug-log preparation. |
Review effort: Balanced
fc0083c to
8c04f82
Compare
|
/azp run |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
There was a problem hiding this comment.
🔵 Needs a closer look
The reported SQLAlchemy throughput gains and execute/executemany behavior require validation with a built driver and live SQL Server, which was unavailable in this source-only review environment.
No open issues 🎉
Review effort: Balanced
|
Thanks for kicking off the pipeline. A note on the performance report, since it shows "no signal" for everything: The only workload in the suite that goes through the pyformat conversion is "Repeated named-parameter queries" ( The case this PR is really aimed at is a large statement with many named parameters, like the multi-row INSERT that SQLAlchemy emits (about 30 KB of SQL and 2,000 parameters per 1,000 rows). There the conversion goes from roughly 68 ms to about 1 ms on first execution and 0.17 ms on repeat. None of the 25 tasks cover that right now, since the insert workloads use If it would help, I'm happy to add a workload for it to |
Jahnvi Thakkar (jahnvi480)
left a comment
There was a problem hiding this comment.
I compared its head against its base using live SQL Server, with two runs of 24 balanced before/after pairs:
| Workload | Measured result |
|---|---|
| 2,000 named parameters, cached statement | 12.2–12.3× faster |
| 2,000 named parameters, empty conversion cache | 8.3–8.5× faster |
The mechanism is sound: it removes repeated whole-SQL scans, caches the SQL rewrite—not parameter values—and avoids unnecessary logging work.
Jahnvi Thakkar (jahnvi480)
left a comment
There was a problem hiding this comment.
LGTM! Thank you so much for your valuable contribution to make our driver faster.
[AB#50320](https://sqlclientdrivers.visualstudio.com/c6d89619-62de-46a0-8b46-70b92a84d85e/_workitems/edit/50320) ### Summary Prepare mssql-python 1.18.0 using the approved customer-facing change inventory since v1.17.0. #### Enhancements - Accept APP/Application Name across synchronous, async and bulk-copy paths; note the async/bulk-copy default application-name change to MSSQL-Python (#884). - Reduce row-to-dictionary, single-row fetch, output-converter batch and fetchmany(1) text-processing overhead (#847, #858, #852, #891). - Cache single-pass pyformat conversion and retain compatible parameter bindings for prepared-statement reuse (#888, #886). - Include mssql-python-rs 0.5.0 improvements: Rust-backed execution, macOS Strict TLS and table-valued parameters in the opt-in Rust ODBC provider (#896). #### Bug Fixes - Avoid unsupported isolation reset when closing pooled Azure Synapse connections (#889). - Respect explicit positive connection timeouts during pooled checkout (#897). - Coordinate Arrow reader cross-thread shutdown/cancellation (#892). - Preserve SQL literal, identifier, comment and escaped-percent behavior during pyformat conversion (#888). - Include Rust-backed timeout, prepared-statement lifetime/cancellation, isolation-change, small-stack connection, streaming-order and SQL_VARIANT decoding fixes (#896). #### Version - Bump mssql_python.__version__ and setup.py from 1.17.0 to 1.18.0. - Replace the previous PyPI highlights with the approved 1.18.0 inventory. - Change exactly three release files; no runtime implementation or dependency-pin changes in this PR. ### Validation - Passed: pinned full-directory Black check, staged Python formatting hook, release-version/highlights/approved-PR inventory checks, and git diff --check. - Not run locally: native rebuild and full integration suite. The isolated project environment lacks runtime/test dependencies and DB_CONNECTION_STRING is unset. No integration-test success is claimed; release qualification remains required. ### Release gates - Keep this PR unmerged until the required PyPI and Conda release/verification gates complete. - Rust dependency verified: mssql-python-rs==0.5.0 was built successfully by ADO build 191702 from stable commit 2f6ab0fa…. Release run 191738 successfully verified/staged and published the wheels through ESRP. All nine wheels are non-yanked on PyPI, and their advertised SHA256 digests match the staging log. There is no wheel-build or publication blocker. The overall release run failed on Guardian findings and dependency-update automation; any required Guardian disposition remains separate and unresolved. - Rust release-source comparison: 0.4.0 at 0c3e3c1436b1234d4e838087ff11140ba68b43a5 to 0.5.0 at 2f6ab0faf2a3a4dbad7dc8f0c4cfe2980eabf41d, verified against version declarations and ADO release sources. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jahnvi Thakkar <61936179+jahnvi480@users.noreply.github.com>
Work Item / Issue Reference
Summary
Follow-up to #500. SQLAlchemy inserts on mssql-python were still topping out around 20-25K rows/s, and most of that time turned out to be in
convert_pyformat_to_qmark(). It did astr.count()+str.replace()over the whole SQL for every parameter, which for a typical SQLAlchemy batch (~2,000 params, ~30 KB of SQL) is ~50 ms perexecute().This rewrites the conversion as a single pass over the placeholder positions the existing scanner already finds, and caches the result per SQL string (small LRU), since the same statement gets executed batch after batch.
It also fixes a few edge cases in the same code:
SELECT '%(id)s', %(id)sbecameSELECT '?', ?)%%(name)swas treated as a placeholder byparse_pyformat_params()but not by the conversion, soexecutemany()with dict rows could end up with the wrong number of values%%handling no longer relies on a sentinel string, so SQL containing that text isn't changedConversion for a 2,000-param statement goes from ~50 ms to ~3 ms (~0.1 ms when cached). SQLAlchemy's default insert into SQL Server went from ~27K to ~189K rows/s in my testing. Added tests for the cases above.