alexkruc commented on code in PR #24663:
URL: https://github.com/apache/airflow/pull/24663#discussion_r908891277


##########
airflow/providers/slack/transfers/sql_to_slack.py:
##########
@@ -0,0 +1,197 @@
+# 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.
+import warnings
+from typing import TYPE_CHECKING, Iterable, Mapping, Optional, Sequence, Union
+
+from pandas import DataFrame
+from tabulate import tabulate
+
+from airflow.exceptions import AirflowException
+from airflow.hooks.base import BaseHook
+from airflow.hooks.dbapi import DbApiHook
+from airflow.models import BaseOperator
+from airflow.providers.slack.hooks.slack_webhook import SlackWebhookHook
+from airflow.providers_manager import ProvidersManager
+from airflow.utils.module_loading import import_string
+from airflow.version import version
+
+if TYPE_CHECKING:
+    from airflow.utils.context import Context
+
+
+def _backported_get_hook(connection, *, hook_params=None):
+    """Return hook based on conn_type
+     For supporting Airflow versions < 2.3, we backport "get_hook()" method. 
This should be removed
+     when "apache-airflow-providers-slack" will depend on Airflow >= 2.3. Git 
reference:
+     
https://github.com/apache/airflow/blob/main/airflow/providers/slack/provider.yaml#L38
+    """
+    hook = ProvidersManager().hooks.get(connection.conn_type, None)
+
+    if hook is None:
+        raise AirflowException(f'Unknown hook type "{connection.conn_type}"')
+    try:
+        hook_class = import_string(hook.hook_class_name)
+    except ImportError:
+        warnings.warn(
+            "Could not import %s when discovering %s %s",
+            hook.hook_class_name,
+            hook.hook_name,
+            hook.package_name,
+        )
+        raise
+    if hook_params is None:
+        hook_params = {}
+    return hook_class(**{hook.connection_id_attribute_name: 
connection.conn_id}, **hook_params)
+
+
+class SqlToSlackOperator(BaseOperator):
+    """
+    Executes an SQL statement in a given SQL connection and sends the results 
to Slack. The results of the
+    query are rendered into the 'slack_message' parameter as a Pandas 
dataframe using a JINJA variable called
+    '{{ results_df }}'. The 'results_df' variable name can be changed by 
specifying a different
+    'results_df_name' parameter. The Tabulate library is added to the JINJA 
environment as a filter to
+    allow the dataframe to be rendered nicely. For example, set 
'slack_message' to {{ results_df |
+    tabulate(tablefmt="pretty", headers="keys") }} to send the results to 
Slack as an ascii rendered table.
+
+    .. seealso::
+        For more information on how to use this operator, take a look at the 
guide:
+        :ref:`howto/operator:SqlToSlackOperator`
+
+    :param sql: The SQL statement to execute on Snowflake (templated)
+    :param slack_message: The templated Slack message to send with the data 
returned from Snowflake.
+        You can use the default JINJA variable {{ results_df }} to access the 
pandas dataframe containing the
+        SQL results
+    :param sql_conn_id: Reference to
+        :ref:`Snowflake connection id<howto/connection:snowflake>`
+    :param sql_hook_params: Extra config params to be passed to the underlying 
hook.
+           Should match the desired hook constructor params.
+    :param slack_conn_id: The connection id for Slack.
+    :param slack_webhook_token: The token to use to authenticate to Slack. If 
this is not provided, the
+        'slack_conn_id' attribute needs to be specified in the 'password' 
field.
+    :param slack_channel: The channel to send message. Override default from 
Slack connection.
+    :param results_df_name: The name of the JINJA template's dataframe 
variable, default is 'results_df'
+    :param parameters: The parameters to pass to the SQL query
+    """
+
+    template_fields: Sequence[str] = ('sql', 'slack_message')
+    template_ext: Sequence[str] = ('.sql', '.jinja', '.j2')
+    template_fields_renderers = {"sql": "sql", "slack_message": "jinja"}
+    times_rendered = 0
+
+    def __init__(
+        self,
+        *,
+        sql: str,
+        sql_conn_id: str,
+        sql_hook_params: Optional[dict] = None,
+        slack_conn_id: Optional[str] = None,
+        slack_webhook_token: Optional[str] = None,
+        slack_channel: Optional[str] = None,
+        slack_message: str,
+        results_df_name: str = 'results_df',
+        parameters: Optional[Union[Iterable, Mapping]] = None,
+        **kwargs,
+    ) -> None:
+
+        super().__init__(**kwargs)
+
+        self.sql_conn_id = sql_conn_id
+        self.sql_hook_params = sql_hook_params
+        self.sql = sql
+        self.parameters = parameters
+        self.slack_conn_id = slack_conn_id
+        self.slack_webhook_token = slack_webhook_token
+        self.slack_channel = slack_channel
+        self.slack_message = slack_message
+        self.results_df_name = results_df_name
+        self.kwargs = kwargs
+
+        if not self.slack_conn_id and not self.slack_webhook_token:
+            raise AirflowException(
+                "SqlToSlackOperator requires either a `slack_conn_id` or a 
`slack_webhook_token` argument"
+            )
+
+    def _get_hook(self) -> DbApiHook:
+        self.log.debug("Get connection for %s", self.sql_conn_id)
+        conn = BaseHook.get_connection(self.sql_conn_id)
+        if version >= '2.3':
+            # "hook_params" were introduced to into "get_hook()" only in 
Airflow 2.3.
+            hook = conn.get_hook(hook_params=self.sql_hook_params)
+        else:
+            # For supporting Airflow versions < 2.3, we backport "get_hook()" 
method. This should be removed
+            # when "apache-airflow-providers-slack" will depend on Airflow >= 
2.3. Git reference:
+            # 
https://github.com/apache/airflow/blob/main/airflow/providers/slack/provider.yaml#L38
+            hook = _backported_get_hook(conn)

Review Comment:
   your'e right :) fixed it :) 



-- 
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: commits-unsubscr...@airflow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to