From 5d2c53d30c183c1e3ec5641ce9ecc22e7efcceb1 Mon Sep 17 00:00:00 2001 From: Roland Walker Date: Wed, 2 Dec 2026 09:35:55 -0500 Subject: [PATCH] compose transform schema for Decimal values rather than infer. Read Decimal field metadata from MySQL, setting a Polars DataType for the field before a transform, saving an inference step for Decimal results. MySQL's Decimals can be larger than Polars allows. In this case, we fall back to inference, which leads to an error being sent to the REPL: BindingsError: "Decimal is too large to fit in Decimal128" --- doc/transforms.md | 2 + mycli/packages/dataframes/transform.py | 25 ++++- mycli_test/pytests/test_polars_transform.py | 102 +++++++++++++++++++- 3 files changed, 124 insertions(+), 5 deletions(-) diff --git a/doc/transforms.md b/doc/transforms.md index d771b1ea..fcf09e48 100644 --- a/doc/transforms.md +++ b/doc/transforms.md @@ -31,6 +31,8 @@ or install these libraries separately: which is representable in MySQL but not in Python, then every field in that result column will be cast to string, making the values opaque to many dataframe operations + * if a result field contains a MySQL Decimal value which is too large for Polars, + an error will be thrown ## Transforming diff --git a/mycli/packages/dataframes/transform.py b/mycli/packages/dataframes/transform.py index 77cb7da7..e36e6770 100644 --- a/mycli/packages/dataframes/transform.py +++ b/mycli/packages/dataframes/transform.py @@ -7,7 +7,7 @@ import fractions from io import BytesIO from types import CodeType -from typing import Any, Iterable, Sequence +from typing import TYPE_CHECKING, Any, Iterable, Sequence from pymysql.constants import FIELD_TYPE, FLAG from pymysql.cursors import Cursor @@ -23,11 +23,14 @@ from mycli.packages.sql_result.sql_result import SQLResult from mycli.types import ImageProtocol, OutputMode +if TYPE_CHECKING: + from polars.datatypes import DataType + delimiter_command = DelimiterCommand() PLOT_FORMATS = ('png', 'pdf', 'svg', 'html') PARQUET_QUERY_METADATA_KEY = 'mycli_query' POLARS_TYPES = { - FIELD_TYPE.DECIMAL: None, # todo: don't infer decimals + FIELD_TYPE.DECIMAL: None, # resolved from field metadata on-the-fly when possible FIELD_TYPE.TINY: int, FIELD_TYPE.SHORT: int, FIELD_TYPE.LONG: int, @@ -45,7 +48,7 @@ FIELD_TYPE.VARCHAR: bytes, FIELD_TYPE.BIT: bytes, FIELD_TYPE.JSON: str, - FIELD_TYPE.NEWDECIMAL: None, # todo: don't infer decimals + FIELD_TYPE.NEWDECIMAL: None, # resolved from field metadata on-the-fly when possible FIELD_TYPE.ENUM: str, FIELD_TYPE.SET: None, FIELD_TYPE.TINY_BLOB: bytes, @@ -330,7 +333,21 @@ def run_polars_transform( converters = getattr(getattr(result.rows, '_result', None), 'converters', ()) fields = getattr(getattr(result.rows, '_result', None), 'fields', ()) - def get_polars_dtype(field_index: int, mysql_type: int) -> type | None: + def get_polars_dtype(field_index: int, mysql_type: int) -> type | DataType | None: + if mysql_type in (FIELD_TYPE.DECIMAL, FIELD_TYPE.NEWDECIMAL): + if field_index >= len(fields): + return None + field = fields[field_index] + length = getattr(field, 'length', None) + scale = getattr(field, 'scale', None) + flags = getattr(field, 'flags', None) + if type(length) is not int or type(scale) is not int or type(flags) is not int: + return None + # Protocol widths include the decimal point and, for signed fields, the sign. + precision = length - (1 if scale > 0 else 0) - (0 if flags & FLAG.UNSIGNED else 1) + if not 1 <= precision <= 38 or not 0 <= scale <= precision: + return None + return transform.polars.Decimal(precision=precision, scale=scale) if mysql_type == FIELD_TYPE.LONGLONG: if field_index >= len(fields): return None diff --git a/mycli_test/pytests/test_polars_transform.py b/mycli_test/pytests/test_polars_transform.py index 8c38c52e..91e2c0da 100644 --- a/mycli_test/pytests/test_polars_transform.py +++ b/mycli_test/pytests/test_polars_transform.py @@ -8,7 +8,7 @@ from unittest.mock import MagicMock from pymysql.constants import FIELD_TYPE, FLAG -from pymysql.cursors import Cursor +from pymysql.cursors import Cursor, SSCursor import pytest from mycli.packages.dataframes import transform as polars_transform @@ -628,6 +628,105 @@ def test_run_polars_transform_infers_bigint_without_field_metadata() -> None: assert result == SQLResult(header=['value'], rows=[(2**64 - 1,)]) +@pytest.mark.parametrize('mysql_type', [FIELD_TYPE.DECIMAL, FIELD_TYPE.NEWDECIMAL]) +@pytest.mark.parametrize('cursor_type', [Cursor, SSCursor]) +@pytest.mark.parametrize( + ('length', 'scale', 'flags', 'precision'), + [ + (12, 4, 0, 10), + (11, 4, FLAG.UNSIGNED | FLAG.NOT_NULL, 10), + (11, 0, 0, 10), + (10, 0, FLAG.UNSIGNED, 10), + (6, 4, 0, 4), + (40, 4, 0, 38), + (39, 4, FLAG.UNSIGNED, 38), + ], +) +@pytest.mark.parametrize('rows', [[], [(None,)], [(Decimal('0'),)]]) +def test_run_polars_transform_uses_decimal_metadata( + mysql_type: int, + cursor_type: type[Cursor], + length: int, + scale: int, + flags: int, + precision: int, + rows: list[tuple[Decimal | None]], +) -> None: + pl = pytest.importorskip('polars') + cursor = MagicMock(spec=cursor_type) + cursor.description = [('amount', mysql_type, None, length, length, scale, True)] + cursor._result = SimpleNamespace(fields=[SimpleNamespace(length=length, scale=scale, flags=flags)]) + cursor.__iter__.return_value = iter(rows) + expression = "pl.DataFrame({'dtype': [str(df.schema['amount'])]})" + transform = PolarsTransform('SELECT amount', expression, compile(expression, '', 'eval'), pl, None) + + result = run_polars_transform(transform, [SQLResult(header=['amount'], rows=cursor)]) + + assert result == SQLResult(header=['dtype'], rows=[(str(pl.Decimal(precision, scale)),)]) + + +@pytest.mark.parametrize('mysql_type', [FIELD_TYPE.DECIMAL, FIELD_TYPE.NEWDECIMAL]) +@pytest.mark.parametrize( + 'fields', + [ + [], + [SimpleNamespace()], + [SimpleNamespace(length=None, scale=4, flags=0)], + [SimpleNamespace(length=12, scale='4', flags=0)], + [SimpleNamespace(length=12, scale=4, flags=None)], + [SimpleNamespace(length=True, scale=0, flags=0)], + [SimpleNamespace(length=0, scale=0, flags=0)], + [SimpleNamespace(length=12, scale=-1, flags=0)], + [SimpleNamespace(length=4, scale=4, flags=0)], + [SimpleNamespace(length=67, scale=4, flags=0)], + [SimpleNamespace(length=66, scale=4, flags=FLAG.UNSIGNED)], + ], +) +def test_run_polars_transform_infers_decimal_with_unsupported_metadata(mysql_type: int, fields: list[Any]) -> None: + pl = pytest.importorskip('polars') + rows = [(Decimal('123.4500'),), (None,)] + cursor = MagicMock(spec=Cursor) + cursor.description = [('amount', mysql_type, None, None, None, None, True)] + cursor._result = SimpleNamespace(fields=fields) + cursor.__iter__.return_value = iter(rows) + expression = "pl.DataFrame({'dtype': [str(df.schema['amount'])]})" + transform = PolarsTransform('SELECT amount', expression, compile(expression, '', 'eval'), pl, None) + + result = run_polars_transform(transform, [SQLResult(header=['amount'], rows=cursor)]) + + inferred = pl.DataFrame(rows, schema=['amount'], orient='row', infer_schema_length=None) + assert result == SQLResult(header=['dtype'], rows=[(str(inferred.schema['amount']),)]) + + +@pytest.mark.parametrize('cursor_type', [Cursor, SSCursor]) +def test_run_polars_transform_writes_decimal_schema_to_parquet(tmp_path: Path, cursor_type: type[Cursor]) -> None: + pl = pytest.importorskip('polars') + rows = [(Decimal('-123.4500'), Decimal('42'), 1), (None, None, 2)] + cursor = MagicMock(spec=cursor_type) + cursor.description = [ + ('amount', FIELD_TYPE.NEWDECIMAL, None, 12, 12, 4, True), + ('count', FIELD_TYPE.DECIMAL, None, 5, 5, 0, True), + ('id', FIELD_TYPE.LONG, None, None, None, None, True), + ] + cursor._result = SimpleNamespace( + fields=[ + SimpleNamespace(length=12, scale=4, flags=0), + SimpleNamespace(length=5, scale=0, flags=FLAG.UNSIGNED), + SimpleNamespace(flags=0), + ] + ) + cursor.__iter__.return_value = iter(rows) + transform = PolarsTransform('SELECT amount, count, id', 'df', compile('df', '', 'eval'), pl, None) + path = tmp_path / 'decimals.parquet' + + run_polars_transform(transform, [SQLResult(header=['amount', 'count', 'id'], rows=cursor)], str(path)) + + dataframe = pl.read_parquet(path) + assert dataframe.schema == {'amount': pl.Decimal(10, 4), 'count': pl.Decimal(5, 0), 'id': pl.Int64} + assert dataframe.rows() == rows + assert dataframe['amount'][0].as_tuple().exponent == -4 + + @pytest.mark.parametrize('mysql_type', [FIELD_TYPE.DECIMAL, FIELD_TYPE.NEWDECIMAL]) def test_run_polars_transform_preserves_cursor_decimal_values(mysql_type: int) -> None: pl = pytest.importorskip('polars') @@ -635,6 +734,7 @@ def test_run_polars_transform_preserves_cursor_decimal_values(mysql_type: int) - cursor = MagicMock(spec=Cursor) cursor.description = [('amount', mysql_type, None, 27, 27, 4, True)] cursor.rowcount = len(rows) + cursor._result = SimpleNamespace(fields=[SimpleNamespace(length=27, scale=4, flags=0)]) cursor.__iter__.return_value = iter(rows) expression = "df.with_columns((pl.col('amount') * 2).alias('amount'))" transform = PolarsTransform(