-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
[dagster-snowflake-pandas] pandas timestamp conversion fix #12190
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,15 @@ | ||
from typing import Mapping, Union, cast | ||
|
||
import pandas as pd | ||
import pandas.core.dtypes.common as pd_core_dtypes_common | ||
from dagster import ( | ||
InputContext, | ||
MetadataValue, | ||
OutputContext, | ||
TableColumn, | ||
TableSchema, | ||
) | ||
from dagster import InputContext, MetadataValue, OutputContext, TableColumn, TableSchema | ||
from dagster._core.definitions.metadata import RawMetadataValue | ||
from dagster._core.errors import DagsterInvalidInvocationError | ||
from dagster._core.storage.db_io_manager import DbTypeHandler, TableSlice | ||
from dagster_snowflake import build_snowflake_io_manager | ||
from dagster_snowflake.resources import SnowflakeConnection | ||
from dagster_snowflake.snowflake_io_manager import SnowflakeDbClient | ||
from snowflake.connector.pandas_tools import pd_writer | ||
from sqlalchemy.exc import InterfaceError | ||
|
||
|
||
def _connect_snowflake(context: Union[InputContext, OutputContext], table_slice: TableSlice): | ||
|
@@ -33,34 +28,6 @@ def _connect_snowflake(context: Union[InputContext, OutputContext], table_slice: | |
).get_connection(raw_conn=False) | ||
|
||
|
||
def _convert_timestamp_to_string(s: pd.Series) -> pd.Series: | ||
""" | ||
Converts columns of data of type pd.Timestamp to string so that it can be stored in | ||
snowflake. | ||
""" | ||
if pd_core_dtypes_common.is_datetime_or_timedelta_dtype(s): # type: ignore # (bad stubs) | ||
return s.dt.strftime("%Y-%m-%d %H:%M:%S.%f %z") | ||
else: | ||
return s | ||
|
||
|
||
def _convert_string_to_timestamp(s: pd.Series) -> pd.Series: | ||
""" | ||
Converts columns of strings in Timestamp format to pd.Timestamp to undo the conversion in | ||
_convert_timestamp_to_string. | ||
|
||
This will not convert non-timestamp strings into timestamps (pd.to_datetime will raise an | ||
exception if the string cannot be converted) | ||
""" | ||
if isinstance(s[0], str): | ||
try: | ||
return pd.to_datetime(s.values) # type: ignore # (bad stubs) | ||
except ValueError: | ||
return s | ||
else: | ||
return s | ||
|
||
|
||
class SnowflakePandasTypeHandler(DbTypeHandler[pd.DataFrame]): | ||
""" | ||
Plugin for the Snowflake I/O Manager that can store and load Pandas DataFrames as Snowflake tables. | ||
|
@@ -86,16 +53,23 @@ def handle_output( | |
connector.paramstyle = "pyformat" | ||
with _connect_snowflake(context, table_slice) as con: | ||
with_uppercase_cols = obj.rename(str.upper, copy=False, axis="columns") | ||
with_uppercase_cols = with_uppercase_cols.apply( | ||
_convert_timestamp_to_string, axis="index" | ||
) | ||
with_uppercase_cols.to_sql( | ||
table_slice.table, | ||
con=con.engine, | ||
if_exists="append", | ||
index=False, | ||
method=pd_writer, | ||
) | ||
|
||
try: | ||
with_uppercase_cols.to_sql( | ||
table_slice.table, | ||
con=con.engine, | ||
if_exists="append", | ||
index=False, | ||
method=pd_writer, | ||
) | ||
except InterfaceError as e: | ||
if "out of range" in e.orig.msg: | ||
raise DagsterInvalidInvocationError( | ||
f"Could not store output {context.name} of step {context.step_key}. If the" | ||
" DataFrame includes pandas Timestamp values, ensure that they have" | ||
" timezones." | ||
) from e | ||
raise e | ||
|
||
return { | ||
"row_count": obj.shape[0], | ||
|
@@ -111,8 +85,18 @@ def handle_output( | |
|
||
def load_input(self, context: InputContext, table_slice: TableSlice) -> pd.DataFrame: | ||
with _connect_snowflake(context, table_slice) as con: | ||
result = pd.read_sql(sql=SnowflakeDbClient.get_select_statement(table_slice), con=con) | ||
result = result.apply(_convert_string_to_timestamp, axis="index") | ||
try: | ||
result = pd.read_sql( | ||
sql=SnowflakeDbClient.get_select_statement(table_slice), con=con | ||
) | ||
except InterfaceError as e: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if we go down the route of https://github.com/dagster-io/dagster/pull/12190/files#r1100731596 this error check would get removed |
||
if "out of range" in e.orig.msg: | ||
raise DagsterInvalidInvocationError( | ||
f"Could not load input {context.name} of {context.op_def.name}. If the" | ||
" DataFrame includes pandas Timestamp values, ensure that they have" | ||
" timezones." | ||
) from e | ||
raise e | ||
result.columns = map(str.lower, result.columns) # type: ignore # (bad stubs) | ||
return result | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
another option instead of reacting to a failed write would be to pre-emptively check if the dataframe as Timestamp data. if so we check if there is timezone information, and raise an error if it doesn't have that info