Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/transforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
25 changes: 21 additions & 4 deletions mycli/packages/dataframes/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down
102 changes: 101 additions & 1 deletion mycli_test/pytests/test_polars_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -628,13 +628,113 @@ 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, '<test>', '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, '<test>', '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', '<test>', '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')
rows = [(None,)] * 100 + [(Decimal('12345678901234567890.1234'),), (Decimal('-0.0001'),)]
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(
Expand Down
Loading