uranusjr commented on code in PR #24652: URL: https://github.com/apache/airflow/pull/24652#discussion_r954588592
########## airflow/providers/snowflake/decorators/snowpark.py: ########## @@ -0,0 +1,143 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence + +from airflow.decorators.base import DecoratedOperator, task_decorator_factory +from airflow.operators.python import PythonOperator +from airflow.providers.snowflake.operators.snowflake import get_db_hook + +if TYPE_CHECKING: + import snowflake + + from airflow.decorators.base import TaskDecorator + +try: + import snowflake.snowpark # noqa +except ImportError as e: + # Snowpark is an optional feature and if imports are missing, it should be silently ignored + # As of Airflow 2.3 and above the operator can throw OptionalProviderFeatureException + try: + from airflow.exceptions import AirflowOptionalProviderFeatureException + except ImportError: + # However, in order to keep backwards-compatibility with Airflow 2.1 and 2.2, if the + # 2.3 exception cannot be imported, the original ImportError should be raised. + # This try/except can be removed when the provider depends on Airflow >= 2.3.0 + raise e from None + raise AirflowOptionalProviderFeatureException(e) + + +class _SnowparkDecoratedOperator(DecoratedOperator, PythonOperator): + """ + Wraps a Python callable and captures args/kwargs when called for execution. + + :param snowflake_conn_id: Reference to + :ref:`Snowflake connection id<howto/connection:snowflake>` + :param parameters: (optional) the parameters to render the SQL query with. + :param warehouse: name of warehouse (will overwrite any warehouse defined in the connection's extra JSON) + :param database: name of database (will overwrite database defined in connection) + :param schema: name of schema (will overwrite schema defined in connection) + :param role: name of role (will overwrite any role defined in connection's extra JSON) + :param authenticator: authenticator for Snowflake. + 'snowflake' (default) to use the internal Snowflake authenticator + 'externalbrowser' to authenticate using your web browser and + Okta, ADFS or any other SAML 2.0-compliant identify provider + (IdP) that has been defined for your account + 'https://<your_okta_account_name>.okta.com' to authenticate + through native Okta. + :param session_parameters: You can set session-level parameters at the time you connect to Snowflake + :param python_callable: A reference to an object that is callable + :param op_kwargs: a dictionary of keyword arguments that will get unpacked in your function (templated) + :param op_args: a list of positional arguments that will get unpacked when + calling your callable (templated) + :param multiple_outputs: if set, function return value will be + unrolled to multiple XCom values. Dict will unroll to xcom values with keys as keys. + Defaults to False. + """ + + template_fields: Sequence[str] = ('op_args', 'op_kwargs') + template_fields_renderers = {"op_args": "py", "op_kwargs": "py"} + + # since we won't mutate the arguments, we should just do the shallow copy + # there are some cases we can't deepcopy the objects (e.g protobuf). + shallow_copy_attrs: Sequence[str] = ('python_callable',) + + def __init__( + self, + *, + snowflake_conn_id: str = 'snowflake_default', + parameters: Optional[dict] = None, + warehouse: Optional[str] = None, + database: Optional[str] = None, + role: Optional[str] = None, + schema: Optional[str] = None, + authenticator: Optional[str] = None, + session_parameters: Optional[dict] = None, + python_callable, + op_args, + op_kwargs: Dict, + **kwargs, + ) -> None: + self.snowflake_conn_id = snowflake_conn_id + self.parameters = parameters + self.warehouse = warehouse + self.database = database + self.role = role + self.schema = schema + self.authenticator = authenticator + self.session_parameters = session_parameters + + kwargs_to_upstream = { + "python_callable": python_callable, + "op_args": op_args, + "op_kwargs": op_kwargs, + } + super().__init__( + kwargs_to_upstream=kwargs_to_upstream, + python_callable=python_callable, + op_args=op_args, + # airflow.decorators.base.DecoratedOperator checks if the functions are bindable, so we have to + # add an artificial value to pass the validations. The real value is determined at runtime. + op_kwargs={**op_kwargs, 'snowpark_session': None}, + **kwargs, + ) + + def execute_callable(self): + hook = get_db_hook(self) + snowpark_session = hook.get_snowpark_session() + return self.python_callable(*self.op_args, **{**self.op_kwargs, 'snowpark_session': snowpark_session}) Review Comment: ```suggestion return self.python_callable(*self.op_args, **self.op_kwargs, snowpark_session snowpark_session) ``` ########## airflow/providers/snowflake/decorators/snowpark.py: ########## @@ -0,0 +1,143 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from typing import TYPE_CHECKING, Callable, Dict, Optional, Sequence + +from airflow.decorators.base import DecoratedOperator, task_decorator_factory +from airflow.operators.python import PythonOperator +from airflow.providers.snowflake.operators.snowflake import get_db_hook + +if TYPE_CHECKING: + import snowflake + + from airflow.decorators.base import TaskDecorator + +try: + import snowflake.snowpark # noqa +except ImportError as e: + # Snowpark is an optional feature and if imports are missing, it should be silently ignored + # As of Airflow 2.3 and above the operator can throw OptionalProviderFeatureException + try: + from airflow.exceptions import AirflowOptionalProviderFeatureException + except ImportError: + # However, in order to keep backwards-compatibility with Airflow 2.1 and 2.2, if the + # 2.3 exception cannot be imported, the original ImportError should be raised. + # This try/except can be removed when the provider depends on Airflow >= 2.3.0 + raise e from None + raise AirflowOptionalProviderFeatureException(e) + + +class _SnowparkDecoratedOperator(DecoratedOperator, PythonOperator): + """ + Wraps a Python callable and captures args/kwargs when called for execution. + + :param snowflake_conn_id: Reference to + :ref:`Snowflake connection id<howto/connection:snowflake>` + :param parameters: (optional) the parameters to render the SQL query with. + :param warehouse: name of warehouse (will overwrite any warehouse defined in the connection's extra JSON) + :param database: name of database (will overwrite database defined in connection) + :param schema: name of schema (will overwrite schema defined in connection) + :param role: name of role (will overwrite any role defined in connection's extra JSON) + :param authenticator: authenticator for Snowflake. + 'snowflake' (default) to use the internal Snowflake authenticator + 'externalbrowser' to authenticate using your web browser and + Okta, ADFS or any other SAML 2.0-compliant identify provider + (IdP) that has been defined for your account + 'https://<your_okta_account_name>.okta.com' to authenticate + through native Okta. + :param session_parameters: You can set session-level parameters at the time you connect to Snowflake + :param python_callable: A reference to an object that is callable + :param op_kwargs: a dictionary of keyword arguments that will get unpacked in your function (templated) + :param op_args: a list of positional arguments that will get unpacked when + calling your callable (templated) + :param multiple_outputs: if set, function return value will be + unrolled to multiple XCom values. Dict will unroll to xcom values with keys as keys. + Defaults to False. + """ + + template_fields: Sequence[str] = ('op_args', 'op_kwargs') + template_fields_renderers = {"op_args": "py", "op_kwargs": "py"} + + # since we won't mutate the arguments, we should just do the shallow copy + # there are some cases we can't deepcopy the objects (e.g protobuf). + shallow_copy_attrs: Sequence[str] = ('python_callable',) + + def __init__( + self, + *, + snowflake_conn_id: str = 'snowflake_default', + parameters: Optional[dict] = None, + warehouse: Optional[str] = None, + database: Optional[str] = None, + role: Optional[str] = None, + schema: Optional[str] = None, + authenticator: Optional[str] = None, + session_parameters: Optional[dict] = None, + python_callable, + op_args, + op_kwargs: Dict, + **kwargs, + ) -> None: + self.snowflake_conn_id = snowflake_conn_id + self.parameters = parameters + self.warehouse = warehouse + self.database = database + self.role = role + self.schema = schema + self.authenticator = authenticator + self.session_parameters = session_parameters + + kwargs_to_upstream = { + "python_callable": python_callable, + "op_args": op_args, + "op_kwargs": op_kwargs, + } + super().__init__( + kwargs_to_upstream=kwargs_to_upstream, + python_callable=python_callable, + op_args=op_args, + # airflow.decorators.base.DecoratedOperator checks if the functions are bindable, so we have to + # add an artificial value to pass the validations. The real value is determined at runtime. + op_kwargs={**op_kwargs, 'snowpark_session': None}, + **kwargs, + ) + + def execute_callable(self): + hook = get_db_hook(self) + snowpark_session = hook.get_snowpark_session() + return self.python_callable(*self.op_args, **{**self.op_kwargs, 'snowpark_session': snowpark_session}) Review Comment: ```suggestion return self.python_callable(*self.op_args, **self.op_kwargs, snowpark_session=snowpark_session) ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
