|
12 | 12 | import pyarrow as pa |
13 | 13 | import pytest |
14 | 14 | import sqlalchemy |
15 | | -from sqlalchemy import Integer, MetaData, Table, create_engine, func, select |
| 15 | +from sqlalchemy import Integer, MetaData, Table, create_engine, func, select, text |
16 | 16 | from sqlalchemy.orm import sessionmaker |
17 | 17 | from sqlalchemy.sql.expression import cast as alchemy_cast |
18 | 18 |
|
@@ -383,6 +383,39 @@ def test_read_database_alchemy_selectable(tmp_sqlite_db: Path) -> None: |
383 | 383 | assert_frame_equal(batches[0], expected) |
384 | 384 |
|
385 | 385 |
|
| 386 | +def test_read_database_alchemy_textclause(tmp_sqlite_db: Path) -> None: |
| 387 | + # various flavours of alchemy connection |
| 388 | + alchemy_engine = create_engine(f"sqlite:///{tmp_sqlite_db}") |
| 389 | + alchemy_session: ConnectionOrCursor = sessionmaker(bind=alchemy_engine)() |
| 390 | + alchemy_conn: ConnectionOrCursor = alchemy_engine.connect() |
| 391 | + |
| 392 | + # establish sqlalchemy "textclause" and validate usage |
| 393 | + textclause_query = text(""" |
| 394 | + SELECT CAST(STRFTIME('%Y',"date") AS INT) as "year", name, value |
| 395 | + FROM test_data |
| 396 | + WHERE value < 0 |
| 397 | + """) |
| 398 | + |
| 399 | + expected = pl.DataFrame({"year": [2021], "name": ["other"], "value": [-99.5]}) |
| 400 | + |
| 401 | + for conn in (alchemy_session, alchemy_engine, alchemy_conn): |
| 402 | + assert_frame_equal( |
| 403 | + pl.read_database(textclause_query, connection=conn), |
| 404 | + expected, |
| 405 | + ) |
| 406 | + |
| 407 | + batches = list( |
| 408 | + pl.read_database( |
| 409 | + textclause_query, |
| 410 | + connection=conn, |
| 411 | + iter_batches=True, |
| 412 | + batch_size=1, |
| 413 | + ) |
| 414 | + ) |
| 415 | + assert len(batches) == 1 |
| 416 | + assert_frame_equal(batches[0], expected) |
| 417 | + |
| 418 | + |
386 | 419 | def test_read_database_parameterised(tmp_sqlite_db: Path) -> None: |
387 | 420 | # raw cursor "execute" only takes positional params, alchemy cursor takes kwargs |
388 | 421 | alchemy_engine = create_engine(f"sqlite:///{tmp_sqlite_db}") |
|
0 commit comments