blob: dbda652fff522df234527c189682d8e442f11b76 [file] [log] [blame]
:py:mod:`airflow.operators.sql`
===============================
.. py:module:: airflow.operators.sql
Module Contents
---------------
Classes
~~~~~~~
.. autoapisummary::
airflow.operators.sql.BaseSQLOperator
airflow.operators.sql.SQLCheckOperator
airflow.operators.sql.SQLValueCheckOperator
airflow.operators.sql.SQLIntervalCheckOperator
airflow.operators.sql.SQLThresholdCheckOperator
airflow.operators.sql.BranchSQLOperator
.. py:class:: BaseSQLOperator(*, conn_id: Optional[str] = None, database: Optional[str] = None, **kwargs)
Bases: :py:obj:`airflow.models.BaseOperator`
This is a base class for generic SQL Operator to get a DB Hook
The provided method is .get_db_hook(). The default behavior will try to
retrieve the DB hook based on connection type.
You can custom the behavior by overriding the .get_db_hook() method.
.. py:method:: get_db_hook(self) -> airflow.hooks.dbapi.DbApiHook
Get the database hook for the connection.
:return: the database hook object.
:rtype: DbApiHook
.. py:class:: SQLCheckOperator(*, sql: str, conn_id: Optional[str] = None, database: Optional[str] = None, **kwargs)
Bases: :py:obj:`BaseSQLOperator`
Performs checks against a db. The ``SQLCheckOperator`` expects
a sql query that will return a single row. Each value on that
first row is evaluated using python ``bool`` casting. If any of the
values return ``False`` the check is failed and errors out.
Note that Python bool casting evals the following as ``False``:
* ``False``
* ``0``
* Empty string (``""``)
* Empty list (``[]``)
* Empty dictionary or set (``{}``)
Given a query like ``SELECT COUNT(*) FROM foo``, it will fail only if
the count ``== 0``. You can craft much more complex query that could,
for instance, check that the table has the same number of rows as
the source table upstream, or that the count of today's partition is
greater than yesterday's partition, or that a set of metrics are less
than 3 standard deviation for the 7 day average.
This operator can be used as a data quality check in your pipeline, and
depending on where you put it in your DAG, you have the choice to
stop the critical path, preventing from
publishing dubious data, or on the side and receive email alerts
without stopping the progress of the DAG.
:param sql: the sql to be executed. (templated)
:type sql: str
:param conn_id: the connection ID used to connect to the database.
:type conn_id: str
:param database: name of database which overwrite the defined one in connection
:type database: str
.. py:attribute:: template_fields
:annotation: :Iterable[str] = ['sql']
.. py:attribute:: template_ext
:annotation: :Iterable[str] = ['.hql', '.sql']
.. py:attribute:: ui_color
:annotation: = #fff7e6
.. py:method:: execute(self, context=None)
This is the main method to derive when creating an operator.
Context is the same dictionary used as when rendering jinja templates.
Refer to get_template_context for more context.
.. py:class:: SQLValueCheckOperator(*, sql: str, pass_value: Any, tolerance: Any = None, conn_id: Optional[str] = None, database: Optional[str] = None, **kwargs)
Bases: :py:obj:`BaseSQLOperator`
Performs a simple value check using sql code.
:param sql: the sql to be executed. (templated)
:type sql: str
:param conn_id: the connection ID used to connect to the database.
:type conn_id: str
:param database: name of database which overwrite the defined one in connection
:type database: str
.. py:attribute:: __mapper_args__
.. py:attribute:: template_fields
:annotation: :Iterable[str] = ['sql', 'pass_value']
.. py:attribute:: template_ext
:annotation: :Iterable[str] = ['.hql', '.sql']
.. py:attribute:: ui_color
:annotation: = #fff7e6
.. py:method:: execute(self, context=None)
This is the main method to derive when creating an operator.
Context is the same dictionary used as when rendering jinja templates.
Refer to get_template_context for more context.
.. py:class:: SQLIntervalCheckOperator(*, table: str, metrics_thresholds: Dict[str, int], date_filter_column: Optional[str] = 'ds', days_back: SupportsAbs[int] = -7, ratio_formula: Optional[str] = 'max_over_min', ignore_zero: bool = True, conn_id: Optional[str] = None, database: Optional[str] = None, **kwargs)
Bases: :py:obj:`BaseSQLOperator`
Checks that the values of metrics given as SQL expressions are within
a certain tolerance of the ones from days_back before.
:param table: the table name
:type table: str
:param conn_id: the connection ID used to connect to the database.
:type conn_id: str
:param database: name of database which will overwrite the defined one in connection
:type database: Optional[str]
:param days_back: number of days between ds and the ds we want to check
against. Defaults to 7 days
:type days_back: Optional[int]
:param date_filter_column: The column name for the dates to filter on. Defaults to 'ds'
:type date_filter_column: Optional[str]
:param ratio_formula: which formula to use to compute the ratio between
the two metrics. Assuming cur is the metric of today and ref is
the metric to today - days_back.
max_over_min: computes max(cur, ref) / min(cur, ref)
relative_diff: computes abs(cur-ref) / ref
Default: 'max_over_min'
:type ratio_formula: str
:param ignore_zero: whether we should ignore zero metrics
:type ignore_zero: bool
:param metrics_thresholds: a dictionary of ratios indexed by metrics
:type metrics_thresholds: dict
.. py:attribute:: __mapper_args__
.. py:attribute:: template_fields
:annotation: :Iterable[str] = ['sql1', 'sql2']
.. py:attribute:: template_ext
:annotation: :Iterable[str] = ['.hql', '.sql']
.. py:attribute:: template_fields_renderers
.. py:attribute:: ui_color
:annotation: = #fff7e6
.. py:attribute:: ratio_formulas
.. py:method:: execute(self, context=None)
This is the main method to derive when creating an operator.
Context is the same dictionary used as when rendering jinja templates.
Refer to get_template_context for more context.
.. py:class:: SQLThresholdCheckOperator(*, sql: str, min_threshold: Any, max_threshold: Any, conn_id: Optional[str] = None, database: Optional[str] = None, **kwargs)
Bases: :py:obj:`BaseSQLOperator`
Performs a value check using sql code against a minimum threshold
and a maximum threshold. Thresholds can be in the form of a numeric
value OR a sql statement that results a numeric.
:param sql: the sql to be executed. (templated)
:type sql: str
:param conn_id: the connection ID used to connect to the database.
:type conn_id: str
:param database: name of database which overwrite the defined one in connection
:type database: str
:param min_threshold: numerical value or min threshold sql to be executed (templated)
:type min_threshold: numeric or str
:param max_threshold: numerical value or max threshold sql to be executed (templated)
:type max_threshold: numeric or str
.. py:attribute:: template_fields
:annotation: = ['sql', 'min_threshold', 'max_threshold']
.. py:attribute:: template_ext
:annotation: :Iterable[str] = ['.hql', '.sql']
.. py:method:: execute(self, context=None)
This is the main method to derive when creating an operator.
Context is the same dictionary used as when rendering jinja templates.
Refer to get_template_context for more context.
.. py:method:: push(self, meta_data)
Optional: Send data check info and metadata to an external database.
Default functionality will log metadata.
.. py:class:: BranchSQLOperator(*, sql: str, follow_task_ids_if_true: List[str], follow_task_ids_if_false: List[str], conn_id: str = 'default_conn_id', database: Optional[str] = None, parameters: Optional[Union[Mapping, Iterable]] = None, **kwargs)
Bases: :py:obj:`BaseSQLOperator`, :py:obj:`airflow.models.SkipMixin`
Allows a DAG to "branch" or follow a specified path based on the results of a SQL query.
:param sql: The SQL code to be executed, should return true or false (templated)
:type sql: Can receive a str representing a sql statement or reference to a template file.
Template reference are recognized by str ending in '.sql'.
Expected SQL query to return Boolean (True/False), integer (0 = False, Otherwise = 1)
or string (true/y/yes/1/on/false/n/no/0/off).
:param follow_task_ids_if_true: task id or task ids to follow if query returns true
:type follow_task_ids_if_true: str or list
:param follow_task_ids_if_false: task id or task ids to follow if query returns false
:type follow_task_ids_if_false: str or list
:param conn_id: the connection ID used to connect to the database.
:type conn_id: str
:param database: name of database which overwrite the defined one in connection
:type database: str
:param parameters: (optional) the parameters to render the SQL query with.
:type parameters: mapping or iterable
.. py:attribute:: template_fields
:annotation: = ['sql']
.. py:attribute:: template_ext
:annotation: = ['.sql']
.. py:attribute:: ui_color
:annotation: = #a22034
.. py:attribute:: ui_fgcolor
:annotation: = #F7F7F7
.. py:method:: execute(self, context: Dict)
This is the main method to derive when creating an operator.
Context is the same dictionary used as when rendering jinja templates.
Refer to get_template_context for more context.