Skip to content
Open
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
11 changes: 11 additions & 0 deletions pandas/io/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@
# -- Helper functions


def _sa_text_if_string(stmt):
"""Wrap plain SQL strings in sqlalchemy.text()."""
try:
import sqlalchemy as sa
except Exception:
return stmt
return sa.text(stmt) if isinstance(stmt, str) else stmt


def _process_parse_dates_argument(parse_dates):
"""Process parse_dates argument for read_sql functions"""
# handle non-list entries for parse_dates gracefully
Expand Down Expand Up @@ -1848,7 +1857,9 @@ def read_query(
read_sql_table : Read SQL database table into a DataFrame.
read_sql


"""
sql = _sa_text_if_string(sql)
result = self.execute(sql, params)
columns = result.keys()

Expand Down
45 changes: 45 additions & 0 deletions pandas/tests/io/sql/test_percent_patterns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# pandas/tests/io/sql/test_percent_patterns.py
import os

import pytest

sa = pytest.importorskip("sqlalchemy")

PG = os.environ.get("PANDAS_TEST_POSTGRES_URI")
URL = PG or "sqlite+pysqlite:///:memory:"


def _eng():
return sa.create_engine(URL)


def test_text_modulo():
import pandas as pd

with _eng().connect() as c:
df = pd.read_sql(sa.text("SELECT 5 % 2 AS r"), c)
assert df.iloc[0, 0] == 1


def test_like_single_percent():
import pandas as pd

with _eng().connect() as c:
df = pd.read_sql(
sa.text("SELECT 'John' AS fullname WHERE 'John' LIKE 'John%'"),
c,
)
assert len(df) == 1


def test_sqlalchemy_expr_percent_operator():
from sqlalchemy import (
literal,
select,
)

import pandas as pd

with _eng().connect() as c:
df = pd.read_sql(select((literal(7) % literal(3)).label("r")), c)
assert df.iloc[0, 0] == 1
Loading