Skip to content

Convert DECIMAL values when use_unicode=False - #1293

Open
PDGGK wants to merge 1 commit into
PyMySQL:mainfrom
PDGGK:fix-decimal-without-unicode
Open

PDGGK wants to merge 1 commit into
PyMySQL:mainfrom
PDGGK:fix-decimal-without-unicode

Conversation

@PDGGK

@PDGGK PDGGK commented Nov 10, 2026 •

Copy link
Copy Markdown

With use_unicode=False, any query that returns a DECIMAL column raises TypeError: conversion from bytes to Decimal is not supported. That includes SUM() and AVG() over plain INT columns, since MySQL returns those as DECIMAL. The exception is raised in the middle of reading the result, so the remaining packets stay on the socket, and the next query on the same connection fails with InternalError: Packet sequence number wrong - got 5 expected 1.

With use_unicode=False the values reach the decoders as bytes. convert_datetime(), convert_timedelta() and convert_date() decode bytes first (#456), and int and float accept bytes, but DECIMAL and NEWDECIMAL are mapped to Decimal itself, which does not.

I added convert_decimal(), which decodes bytes the same way and returns a Decimal, and mapped both DECIMAL field types to it. With the default use_unicode=True the value is still a str and the result is the same Decimal. mysqlclient 2.3.0 returns Decimal('9.99'), Decimal('5') and Decimal('5.245000') for the three queries below with use_unicode=False, so this also matches it.

Reproduced on MySQL 8.4.9 with Python 3.13, before the change:

con = pymysql.connect(..., use_unicode=False)
cur = con.cursor()
cur.execute("CREATE TABLE prices (id INT, qty INT, price DECIMAL(10, 2))")
cur.execute("INSERT INTO prices VALUES (1, 2, 9.99), (2, 3, 0.50)")
cur.execute("SELECT SUM(qty) FROM prices")  # TypeError
cur.execute("SELECT 1")                     # InternalError: Packet sequence number wrong

After the change the queries return Decimal('9.99'), Decimal('5') and Decimal('5.245000').

Tests: TestConversion.test_decimal_without_unicode selects a DECIMAL and a SUM() on a use_unicode=False connection. With the old converters.py it fails with the same TypeError. The docstring of convert_decimal() has doctests for str and bytes. The full suite (pytest pymysql: 188 passed, 12 skipped, 1 xfailed), the converters doctests, ruff format --diff and ruff check --diff pass. I ran the suite against MySQL 8.4 only, without the unix socket entry from ci/docker.json, and not against MariaDB or MySQL 5.7.

Summary by CodeRabbit

  • Bug Fixes
    • Decimal values are now returned consistently as decimal numbers when Unicode conversion is disabled, including results from decimal aggregates. This avoids exposing byte-based values in these cases and makes decimal results easier to use in applications.

With `use_unicode=False`, column values reach the decoders as bytes.
The date and time converters decode bytes first, but DECIMAL and
NEWDECIMAL were mapped to `Decimal` itself, which rejects bytes. Any
result with a DECIMAL column, including `SUM()` and `AVG()` of integer
columns, raised `TypeError: conversion from bytes to Decimal is not
supported`, and the rows left unread made the next query on the same
connection fail with "Packet sequence number wrong".

Add `convert_decimal()`, which decodes bytes like the other converters
and returns a `Decimal`, and use it for both DECIMAL field types. This
matches mysqlclient, which returns `Decimal` for these columns with
`use_unicode=False`.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T09:13:38.668971Z ed36879 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The decimal converter now decodes byte inputs as ASCII before constructing Decimal values. The DECIMAL and NEWDECIMAL decoders use this converter. A test checks decimal query results with use_unicode=False.

Changes: Decimal conversion

Layer / File(s) Summary
Decimal decoding and validation
pymysql/converters.py, pymysql/tests/test_basic.py
Added convert_decimal for byte and bytearray inputs and registered it for DECIMAL and NEWDECIMAL. Added a test that checks a decimal cast and aggregate result when use_unicode=False.

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix

Suggested reviewers: methane

Merge Risk: Minimal · up to ed368

The change addresses decimal results with Unicode disabled; no merge-blocking issue was found.

Pre-merge checks: Passed 5

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: converting DECIMAL values when use_unicode=False.
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 2 files.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fc60b2c9-bd3a-43bf-8d84-ff96c2b0ca7c
Commits

Reviewing files that changed from the base of the PR and between 7b9584f and ed36879.

Files selected for processing: 2

  • pymysql/converters.py
  • pymysql/tests/test_basic.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant