|
| 1 | +"""Tests that polars and pandas correctly infer schemas from cursor.description type codes.""" |
| 2 | + |
| 3 | +import datetime |
| 4 | +import inspect |
| 5 | +import pytest |
| 6 | + |
| 7 | +import mssql_python |
| 8 | + |
| 9 | +try: |
| 10 | + import polars as pl |
| 11 | + |
| 12 | + HAS_POLARS = True |
| 13 | +except ImportError: |
| 14 | + HAS_POLARS = False |
| 15 | + |
| 16 | +try: |
| 17 | + import pandas as pd |
| 18 | + |
| 19 | + HAS_PANDAS = True |
| 20 | +except ImportError: |
| 21 | + HAS_PANDAS = False |
| 22 | + |
| 23 | + |
| 24 | +# ── cursor.description type_code verification ───────────────────────────── |
| 25 | + |
| 26 | + |
| 27 | +class TestCursorDescriptionTypeCodes: |
| 28 | + """Verify cursor.description returns isclass-compatible Python types.""" |
| 29 | + |
| 30 | + def test_date_type_code_is_datetime_date(self, cursor): |
| 31 | + """DATE columns must report datetime.date, not str.""" |
| 32 | + cursor.execute("SELECT CAST('2024-01-15' AS DATE) AS d") |
| 33 | + type_code = cursor.description[0][1] |
| 34 | + assert type_code is datetime.date |
| 35 | + assert inspect.isclass(type_code) |
| 36 | + cursor.fetchall() |
| 37 | + |
| 38 | + def test_time_type_code_is_datetime_time(self, cursor): |
| 39 | + """TIME columns must report datetime.time.""" |
| 40 | + cursor.execute("SELECT CAST('13:45:30' AS TIME) AS t") |
| 41 | + type_code = cursor.description[0][1] |
| 42 | + assert type_code is datetime.time |
| 43 | + assert inspect.isclass(type_code) |
| 44 | + cursor.fetchall() |
| 45 | + |
| 46 | + def test_datetime_type_code_is_datetime_datetime(self, cursor): |
| 47 | + """DATETIME columns must report datetime.datetime.""" |
| 48 | + cursor.execute("SELECT CAST('2024-01-15 13:45:30' AS DATETIME) AS dt") |
| 49 | + type_code = cursor.description[0][1] |
| 50 | + assert type_code is datetime.datetime |
| 51 | + assert inspect.isclass(type_code) |
| 52 | + cursor.fetchall() |
| 53 | + |
| 54 | + def test_datetime2_type_code_is_datetime_datetime(self, cursor): |
| 55 | + """DATETIME2 columns must report datetime.datetime.""" |
| 56 | + cursor.execute("SELECT CAST('2024-01-15 13:45:30.1234567' AS DATETIME2) AS dt2") |
| 57 | + type_code = cursor.description[0][1] |
| 58 | + assert type_code is datetime.datetime |
| 59 | + assert inspect.isclass(type_code) |
| 60 | + cursor.fetchall() |
| 61 | + |
| 62 | + def test_smalldatetime_type_code_is_datetime_datetime(self, cursor): |
| 63 | + """SMALLDATETIME columns must report datetime.datetime.""" |
| 64 | + cursor.execute("SELECT CAST('2024-01-15 13:45:00' AS SMALLDATETIME) AS sdt") |
| 65 | + type_code = cursor.description[0][1] |
| 66 | + assert type_code is datetime.datetime |
| 67 | + assert inspect.isclass(type_code) |
| 68 | + cursor.fetchall() |
| 69 | + |
| 70 | + def test_datetimeoffset_type_code_is_datetime_datetime(self, cursor): |
| 71 | + """DATETIMEOFFSET columns must report datetime.datetime.""" |
| 72 | + cursor.execute("SELECT CAST('2024-01-15 13:45:30.123 +05:30' AS DATETIMEOFFSET) AS dto") |
| 73 | + type_code = cursor.description[0][1] |
| 74 | + assert type_code is datetime.datetime |
| 75 | + assert inspect.isclass(type_code) |
| 76 | + cursor.fetchall() |
| 77 | + |
| 78 | + def test_all_types_are_isclass(self, cursor): |
| 79 | + """Every type_code in cursor.description must pass inspect.isclass().""" |
| 80 | + cursor.execute(""" |
| 81 | + SELECT |
| 82 | + CAST(1 AS INT) AS i, |
| 83 | + CAST('x' AS NVARCHAR(10)) AS s, |
| 84 | + CAST('2024-01-15' AS DATE) AS d, |
| 85 | + CAST('13:45:30' AS TIME) AS t, |
| 86 | + CAST('2024-01-15 13:45:30' AS DATETIME2) AS dt2, |
| 87 | + CAST(1.5 AS DECIMAL(10,2)) AS dec, |
| 88 | + CAST(1 AS BIT) AS b, |
| 89 | + CAST(0x01 AS VARBINARY(10)) AS bin |
| 90 | + """) |
| 91 | + for desc in cursor.description: |
| 92 | + col_name = desc[0] |
| 93 | + type_code = desc[1] |
| 94 | + assert inspect.isclass( |
| 95 | + type_code |
| 96 | + ), f"Column '{col_name}': type_code={type_code!r} fails isclass()" |
| 97 | + cursor.fetchall() |
| 98 | + |
| 99 | + |
| 100 | +# ── Polars integration ──────────────────────────────────────────────────── |
| 101 | + |
| 102 | + |
| 103 | +@pytest.mark.skipif(not HAS_POLARS, reason="polars not installed") |
| 104 | +class TestPolarsIntegration: |
| 105 | + """Polars read_database must infer correct dtypes from cursor.description.""" |
| 106 | + |
| 107 | + def test_polars_date_column(self, db_connection): |
| 108 | + """Issue #352: DATE columns caused ComputeError in polars.""" |
| 109 | + df = pl.read_database( |
| 110 | + query="SELECT CAST('2024-01-15' AS DATE) AS d", |
| 111 | + connection=db_connection, |
| 112 | + ) |
| 113 | + assert df.schema["d"] == pl.Date |
| 114 | + assert df["d"][0] == datetime.date(2024, 1, 15) |
| 115 | + |
| 116 | + def test_polars_all_datetime_types(self, db_connection): |
| 117 | + """All date/time types must produce correct polars dtypes.""" |
| 118 | + df = pl.read_database( |
| 119 | + query=""" |
| 120 | + SELECT |
| 121 | + CAST('2024-01-15' AS DATE) AS d, |
| 122 | + CAST('2024-01-15 13:45:30' AS DATETIME) AS dt, |
| 123 | + CAST('2024-01-15 13:45:30.123' AS DATETIME2) AS dt2, |
| 124 | + CAST('2024-01-15 13:45:00' AS SMALLDATETIME) AS sdt |
| 125 | + """, |
| 126 | + connection=db_connection, |
| 127 | + ) |
| 128 | + assert df.schema["d"] == pl.Date |
| 129 | + assert df.schema["dt"] == pl.Datetime |
| 130 | + assert df.schema["dt2"] == pl.Datetime |
| 131 | + assert df.schema["sdt"] == pl.Datetime |
| 132 | + |
| 133 | + def test_polars_mixed_types(self, db_connection): |
| 134 | + """Mixed column types with DATE must not cause schema mismatch.""" |
| 135 | + df = pl.read_database( |
| 136 | + query=""" |
| 137 | + SELECT |
| 138 | + CAST(42 AS INT) AS i, |
| 139 | + CAST('hello' AS NVARCHAR(50)) AS s, |
| 140 | + CAST('2024-06-15' AS DATE) AS d, |
| 141 | + CAST(99.95 AS DECIMAL(10,2)) AS amount |
| 142 | + """, |
| 143 | + connection=db_connection, |
| 144 | + ) |
| 145 | + assert df["i"][0] == 42 |
| 146 | + assert df["s"][0] == "hello" |
| 147 | + assert df["d"][0] == datetime.date(2024, 6, 15) |
| 148 | + assert df.schema["d"] == pl.Date |
| 149 | + |
| 150 | + def test_polars_date_with_nulls(self, db_connection): |
| 151 | + """DATE columns with NULLs must still infer Date dtype.""" |
| 152 | + cursor = db_connection.cursor() |
| 153 | + try: |
| 154 | + cursor.execute(""" |
| 155 | + CREATE TABLE #polars_null_test ( |
| 156 | + id INT, |
| 157 | + d DATE |
| 158 | + ) |
| 159 | + """) |
| 160 | + cursor.execute(""" |
| 161 | + INSERT INTO #polars_null_test VALUES |
| 162 | + (1, '2024-01-15'), |
| 163 | + (2, NULL), |
| 164 | + (3, '2024-03-20') |
| 165 | + """) |
| 166 | + db_connection.commit() |
| 167 | + |
| 168 | + df = pl.read_database( |
| 169 | + query="SELECT * FROM #polars_null_test ORDER BY id", |
| 170 | + connection=db_connection, |
| 171 | + ) |
| 172 | + assert df.schema["d"] == pl.Date |
| 173 | + assert df["d"][0] == datetime.date(2024, 1, 15) |
| 174 | + assert df["d"][1] is None |
| 175 | + assert df["d"][2] == datetime.date(2024, 3, 20) |
| 176 | + finally: |
| 177 | + try: |
| 178 | + cursor.execute("DROP TABLE IF EXISTS #polars_null_test") |
| 179 | + db_connection.commit() |
| 180 | + except Exception: |
| 181 | + pass |
| 182 | + cursor.close() |
| 183 | + |
| 184 | + |
| 185 | +# ── Pandas integration ──────────────────────────────────────────────────── |
| 186 | + |
| 187 | + |
| 188 | +@pytest.mark.skipif(not HAS_PANDAS, reason="pandas not installed") |
| 189 | +@pytest.mark.filterwarnings("ignore::UserWarning") |
| 190 | +class TestPandasIntegration: |
| 191 | + """Pandas read_sql must handle date/time columns correctly.""" |
| 192 | + |
| 193 | + def test_pandas_date_column(self, db_connection): |
| 194 | + """DATE columns must be readable by pandas without error.""" |
| 195 | + df = pd.read_sql( |
| 196 | + "SELECT CAST('2024-01-15' AS DATE) AS d", |
| 197 | + db_connection, |
| 198 | + ) |
| 199 | + assert len(df) == 1 |
| 200 | + val = df["d"].iloc[0] |
| 201 | + # pandas may return datetime or date depending on version |
| 202 | + if isinstance(val, datetime.datetime): |
| 203 | + assert val.date() == datetime.date(2024, 1, 15) |
| 204 | + else: |
| 205 | + assert val == datetime.date(2024, 1, 15) |
| 206 | + |
| 207 | + def test_pandas_all_datetime_types(self, db_connection): |
| 208 | + """All date/time types must be readable by pandas.""" |
| 209 | + df = pd.read_sql( |
| 210 | + """ |
| 211 | + SELECT |
| 212 | + CAST('2024-01-15' AS DATE) AS d, |
| 213 | + CAST('2024-01-15 13:45:30' AS DATETIME) AS dt, |
| 214 | + CAST('2024-01-15 13:45:30.123' AS DATETIME2) AS dt2, |
| 215 | + CAST('2024-01-15 13:45:00' AS SMALLDATETIME) AS sdt |
| 216 | + """, |
| 217 | + db_connection, |
| 218 | + ) |
| 219 | + assert len(df) == 1 |
| 220 | + assert len(df.columns) == 4 |
| 221 | + |
| 222 | + def test_pandas_mixed_types_with_date(self, db_connection): |
| 223 | + """Mixed column types including DATE must work correctly.""" |
| 224 | + df = pd.read_sql( |
| 225 | + """ |
| 226 | + SELECT |
| 227 | + CAST(42 AS INT) AS i, |
| 228 | + CAST('hello' AS NVARCHAR(50)) AS s, |
| 229 | + CAST('2024-06-15' AS DATE) AS d, |
| 230 | + CAST(99.95 AS DECIMAL(10,2)) AS amount |
| 231 | + """, |
| 232 | + db_connection, |
| 233 | + ) |
| 234 | + assert df["i"].iloc[0] == 42 |
| 235 | + assert df["s"].iloc[0] == "hello" |
| 236 | + val = df["d"].iloc[0] |
| 237 | + if isinstance(val, datetime.datetime): |
| 238 | + assert val.date() == datetime.date(2024, 6, 15) |
| 239 | + else: |
| 240 | + assert val == datetime.date(2024, 6, 15) |
0 commit comments