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
13 changes: 13 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
Upcoming (TBD)
==============

Features
--------
* Create explicit schemas for Polars dataframes, handling stringified invalid dates.


Documentation
--------
* Note transform limitations when the result contains invalid dates.


v2.32.3 (2026/12/02)
==============

Expand Down
4 changes: 4 additions & 0 deletions doc/transforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ or install these libraries separately:
* results from `UNION`s may not be able to be transformed
* the post-processing model means that the entire SQL result must be transferred
from the server and loaded into local memory
* if a result column contains a date/datetime/timestamp such as `0000-00-00`,
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

## Transforming

Expand Down
88 changes: 87 additions & 1 deletion mycli/packages/dataframes/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
from types import CodeType
from typing import Any, Iterable, Sequence

from pymysql.constants import FIELD_TYPE, FLAG
from pymysql.cursors import Cursor
import sqlglot

from mycli.packages.redirection.hybrid_redirection import (
Expand All @@ -24,6 +26,45 @@
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.TINY: int,
FIELD_TYPE.SHORT: int,
FIELD_TYPE.LONG: int,
FIELD_TYPE.FLOAT: float,
FIELD_TYPE.DOUBLE: float,
FIELD_TYPE.NULL: type(None),
FIELD_TYPE.TIMESTAMP: datetime.datetime,
FIELD_TYPE.LONGLONG: int, # or Polars UInt64 as determined on-the-fly
FIELD_TYPE.INT24: int,
FIELD_TYPE.DATE: datetime.date,
FIELD_TYPE.TIME: datetime.time,
FIELD_TYPE.DATETIME: datetime.datetime,
FIELD_TYPE.YEAR: int,
FIELD_TYPE.NEWDATE: str,
FIELD_TYPE.VARCHAR: bytes,
FIELD_TYPE.BIT: bytes,
FIELD_TYPE.JSON: str,
FIELD_TYPE.NEWDECIMAL: None, # todo: don't infer decimals
FIELD_TYPE.ENUM: str,
FIELD_TYPE.SET: None,
FIELD_TYPE.TINY_BLOB: bytes,
FIELD_TYPE.MEDIUM_BLOB: bytes,
FIELD_TYPE.LONG_BLOB: bytes,
FIELD_TYPE.BLOB: bytes,
FIELD_TYPE.VAR_STRING: str,
FIELD_TYPE.STRING: str,
FIELD_TYPE.GEOMETRY: None,
}
TEXT_BINARY_TYPES = {
FIELD_TYPE.VARCHAR,
FIELD_TYPE.VAR_STRING,
FIELD_TYPE.STRING,
FIELD_TYPE.TINY_BLOB,
FIELD_TYPE.MEDIUM_BLOB,
FIELD_TYPE.LONG_BLOB,
FIELD_TYPE.BLOB,
}


class PolarsTransformError(RuntimeError):
Expand Down Expand Up @@ -283,7 +324,52 @@ def run_polars_transform(
if not isinstance(result.header, list) or result.rows is None:
raise PolarsTransformError('Polars transforms require a tabular SQL result.')

dataframe = transform.polars.DataFrame(list(result.rows), schema=result.header, orient='row', infer_schema_length=None)
if isinstance(result.rows, Cursor):
# should be faster than inferring

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:
if mysql_type == FIELD_TYPE.LONGLONG:
if field_index >= len(fields):
return None
return transform.polars.UInt64 if fields[field_index].flags & FLAG.UNSIGNED else int
if mysql_type in TEXT_BINARY_TYPES:
if field_index >= len(converters):
return None
# PyMySQL resolves charset and use_unicode into a per-column encoding.
encoding, _converter = converters[field_index]
return str if encoding is not None else bytes
polars_type = POLARS_TYPES.get(mysql_type, None)
return polars_type if type(polars_type) is type else None

polars_types = [get_polars_dtype(field_index, tup[1]) for field_index, tup in enumerate(result.rows.description)]
rows = list(result.rows)
# MySQL zero/invalid dates are decoded as strings rather than temporal values.
string_dates = {
index
for index, dtype in enumerate(polars_types)
if dtype
in (
datetime.date,
datetime.datetime,
datetime.time,
)
and any(isinstance(row[index], str) for row in rows)
}
if string_dates:
for index in string_dates:
polars_types[index] = str
rows = [
tuple(str(value) if index in string_dates and value is not None else value for index, value in enumerate(row))
for row in rows
]
schema = list(zip(result.header, polars_types, strict=True))
dataframe = transform.polars.DataFrame(rows, schema=schema, orient='row', infer_schema_length=None)
else:
dataframe = transform.polars.DataFrame(list(result.rows), schema=result.header, orient='row', infer_schema_length=None)

try:
value = eval(
transform.code,
Expand Down
168 changes: 168 additions & 0 deletions mycli_test/pytests/test_polars_transform.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
from __future__ import annotations

import datetime
from decimal import Decimal
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Iterator, Sequence
from unittest.mock import MagicMock

from pymysql.constants import FIELD_TYPE, FLAG
from pymysql.cursors import Cursor
import pytest

from mycli.packages.dataframes import transform as polars_transform
Expand Down Expand Up @@ -482,6 +488,168 @@ def test_run_polars_transform_materializes_and_renders_returned_dataframe() -> N
assert result == SQLResult(header=['id'], rows=[(1,), (2,)])


def test_run_polars_transform_preserves_declared_types_for_null_cursor_values() -> None:
pl = pytest.importorskip('polars')
cursor = MagicMock(spec=Cursor)
cursor.description = [
('id', FIELD_TYPE.LONG, None, None, None, None, True),
('name', FIELD_TYPE.VAR_STRING, None, None, None, None, True),
]
cursor.rowcount = 1
cursor._result = SimpleNamespace(converters=[('ascii', None), ('utf8', None)])
cursor.__iter__.return_value = iter([(None, None)])
expression = "df.select(pl.lit(str(df.schema['id'])).alias('id_type'), pl.lit(str(df.schema['name'])).alias('name_type'))"
transform = PolarsTransform(
sql='SELECT id, name FROM records',
expression=expression,
code=compile(expression, '<test>', 'eval'),
polars=pl,
altair=None,
)

result = run_polars_transform(transform, [SQLResult(header=['id', 'name'], rows=cursor)])

assert result == SQLResult(header=['id_type', 'name_type'], rows=[('Int64', 'String')])


@pytest.mark.parametrize(
'mysql_type',
[
FIELD_TYPE.VARCHAR,
FIELD_TYPE.VAR_STRING,
FIELD_TYPE.STRING,
FIELD_TYPE.TINY_BLOB,
FIELD_TYPE.MEDIUM_BLOB,
FIELD_TYPE.LONG_BLOB,
FIELD_TYPE.BLOB,
],
)
@pytest.mark.parametrize(('encoding', 'value'), [('utf8', 'caf\u00e9'), (None, b'\xff\x00')])
def test_run_polars_transform_respects_text_binary_decoding(mysql_type: int, encoding: str | None, value: str | bytes) -> None:
pl = pytest.importorskip('polars')
cursor = MagicMock(spec=Cursor)
cursor.description = [('value', mysql_type, None, None, None, None, True)]
cursor._result = SimpleNamespace(converters=[(encoding, None)])
cursor.__iter__.return_value = iter([(value,), (None,)])
transform = PolarsTransform('SELECT value FROM records', 'df', compile('df', '<test>', 'eval'), pl, None)

result = run_polars_transform(transform, [SQLResult(header=['value'], rows=cursor)])

assert result == SQLResult(header=['value'], rows=[(value,), (None,)])


@pytest.mark.parametrize('value', ['text', b'\xff'])
def test_run_polars_transform_infers_text_binary_type_without_decoder_metadata(value: str | bytes) -> None:
pl = pytest.importorskip('polars')
cursor = MagicMock(spec=Cursor)
cursor.description = [('value', FIELD_TYPE.BLOB, None, None, None, None, True)]
cursor._result = None
cursor.__iter__.return_value = iter([(value,)])
transform = PolarsTransform('SELECT value FROM records', 'df', compile('df', '<test>', 'eval'), pl, None)

result = run_polars_transform(transform, [SQLResult(header=['value'], rows=cursor)])

assert result == SQLResult(header=['value'], rows=[(value,)])


@pytest.mark.parametrize(
('flags', 'value', 'dtype'),
[
(FLAG.UNSIGNED, 2**63, 'UInt64'),
(FLAG.UNSIGNED | FLAG.NOT_NULL, 2**64 - 1, 'UInt64'),
(FLAG.UNSIGNED, 0, 'UInt64'),
(FLAG.UNSIGNED, None, 'UInt64'),
(0, -(2**63), 'Int64'),
(FLAG.NOT_NULL, 2**63 - 1, 'Int64'),
],
)
def test_run_polars_transform_respects_bigint_unsigned_flag(flags: int, value: int | None, dtype: str) -> None:
pl = pytest.importorskip('polars')
cursor = MagicMock(spec=Cursor)
cursor.description = [('value', FIELD_TYPE.LONGLONG, None, None, None, None, True)]
cursor._result = SimpleNamespace(fields=[SimpleNamespace(flags=flags)])
cursor.__iter__.return_value = iter([(value,)])
expression = "df.with_columns(pl.lit(str(df.schema['value'])).alias('dtype'))"
transform = PolarsTransform('SELECT value FROM records', expression, compile(expression, '<test>', 'eval'), pl, None)

result = run_polars_transform(transform, [SQLResult(header=['value'], rows=cursor)])

assert result == SQLResult(header=['value', 'dtype'], rows=[(value, dtype)])


@pytest.mark.parametrize(
('mysql_type', 'valid', 'invalid', 'dtype'),
[
(FIELD_TYPE.DATE, datetime.date(2026, 1, 2), '0000-00-00', 'Date'),
(FIELD_TYPE.DATE, datetime.date(2026, 1, 2), '2026-02-31', 'Date'),
(FIELD_TYPE.DATETIME, datetime.datetime(2026, 1, 2, 3, 4, 5), '0000-00-00 00:00:00', "Datetime(time_unit='us', time_zone=None)"),
(FIELD_TYPE.TIMESTAMP, datetime.datetime(2026, 1, 2, 3, 4, 5), '0000-00-00 00:00:00', "Datetime(time_unit='us', time_zone=None)"),
(FIELD_TYPE.TIME, datetime.time(12, 30), '-01:00:00', 'Time'),
(FIELD_TYPE.TIME, datetime.time(0, 0), '25:00:00', 'Time'),
(FIELD_TYPE.TIME, datetime.time(23, 59, 59, 123456), '-838:59:59.123456', 'Time'),
(FIELD_TYPE.TIME, datetime.time(12, 30, 0, 123456), '838:59:59.123456', 'Time'),
],
)
@pytest.mark.parametrize('values', ['invalid', 'mixed', 'valid', 'null', 'empty'])
def test_run_polars_transform_preserves_cursor_temporal_values(
mysql_type: int, valid: datetime.date | datetime.time, invalid: str, dtype: str, values: str
) -> None:
pl = pytest.importorskip('polars')
cases: dict[str, list[tuple[datetime.date | datetime.time | str | None]]] = {
'invalid': [(invalid,), (None,)],
'mixed': [(valid,)] * 101 + [(invalid,), (None,)],
'valid': [(valid,), (None,)],
'null': [(None,)],
'empty': [],
}
rows = cases[values]
cursor = MagicMock(spec=Cursor)
cursor.description = [('value', mysql_type, None, None, None, None, True)]
cursor.__iter__.return_value = iter(rows)
expression = "df.with_columns(pl.lit(str(df.schema['value'])).alias('dtype'))"
transform = PolarsTransform('SELECT value FROM records', expression, compile(expression, '<test>', 'eval'), pl, None)
result = run_polars_transform(transform, [SQLResult(header=['value'], rows=cursor)])

fallback = values in ('invalid', 'mixed')
expected = [(str(value) if fallback and value is not None else value, 'String' if fallback else dtype) for (value,) in rows]
assert result == SQLResult(header=['value', 'dtype'], rows=expected)


def test_run_polars_transform_infers_bigint_without_field_metadata() -> None:
pl = pytest.importorskip('polars')
cursor = MagicMock(spec=Cursor)
cursor.description = [('value', FIELD_TYPE.LONGLONG, None, None, None, None, True)]
cursor._result = None
cursor.__iter__.return_value = iter([(2**64 - 1,)])
transform = PolarsTransform('SELECT value FROM records', 'df', compile('df', '<test>', 'eval'), pl, None)

result = run_polars_transform(transform, [SQLResult(header=['value'], rows=cursor)])

assert result == SQLResult(header=['value'], rows=[(2**64 - 1,)])


@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.__iter__.return_value = iter(rows)
expression = "df.with_columns((pl.col('amount') * 2).alias('amount'))"
transform = PolarsTransform(
sql='SELECT amount FROM records',
expression=expression,
code=compile(expression, '<test>', 'eval'),
polars=pl,
altair=None,
)

result = run_polars_transform(transform, [SQLResult(header=['amount'], rows=cursor)])

assert result == SQLResult(header=['amount'], rows=[(None,)] * 100 + [(Decimal('24691357802469135780.2468'),), (Decimal('-0.0002'),)])


@pytest.mark.parametrize('later_value', [1, 'value'])
def test_run_polars_transform_infers_types_from_all_rows(later_value: Any) -> None:
pl = pytest.importorskip('polars')
Expand Down
Loading