Skip to content

BUG: Fix Dataframe constructor missing sql column names (#40682) #41005

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
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
1 change: 1 addition & 0 deletions pandas/compat/_optional.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"s3fs": "0.4.0",
"scipy": "1.2.0",
"sqlalchemy": "1.2.8",
"sql_metadata": None,
"tables": "3.5.1",
"tabulate": "0.8.7",
"xarray": "0.12.3",
Expand Down
12 changes: 11 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,7 @@
3 bar 8
"""

# DataFrame helper functions

# -----------------------------------------------------------------------
# DataFrame class
Expand Down Expand Up @@ -566,7 +567,6 @@ def __init__(
dtype: Dtype | None = None,
copy: bool | None = None,
):

if copy is None:
if isinstance(data, dict) or data is None:
# retain pre-GH#38939 default behavior
Expand Down Expand Up @@ -669,6 +669,16 @@ def __init__(
# For data is list-like, or Iterable (will consume into list)
elif is_list_like(data):
if not isinstance(data, (abc.Sequence, ExtensionArray)):
# For data is a sqlalchemy query, extract column names
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

umm what exactly are you trying to do here?

if str(type(data)) == "<class 'sqlalchemy.orm.query.Query'>":
sql_mt = import_optional_dependency("sql_metadata")
# Extract column names using sql_metadata
columns = list(sql_mt.get_query_columns(str(data)))
# Sanitize column names and remove everything before . character
for i in range(len(columns)):
if columns[i].find(".") != -1:
columns[i] = columns[i][columns[i].find(".") + 1 :]

data = list(data)
if len(data) > 0:
if is_dataclass(data[0]):
Expand Down