response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Add is_orphaned to DatasetModel | def upgrade():
"""Add is_orphaned to DatasetModel"""
with op.batch_alter_table("dataset") as batch_op:
batch_op.add_column(
sa.Column(
"is_orphaned",
sa.Boolean,
default=False,
nullable=False,
server_default="0",... |
Remove is_orphaned from DatasetModel | def downgrade():
"""Remove is_orphaned from DatasetModel"""
with op.batch_alter_table("dataset") as batch_op:
batch_op.drop_column("is_orphaned", mssql_drop_default=True) |
Apply add dttm index on log table | def upgrade():
"""Apply add dttm index on log table"""
op.create_index("idx_log_dttm", "log", ["dttm"], unique=False) |
Unapply add dttm index on log table | def downgrade():
"""Unapply add dttm index on log table"""
op.drop_index("idx_log_dttm", table_name="log") |
Increase length of user identifier columns in ab_user and ab_register_user tables | def upgrade():
"""Increase length of user identifier columns in ab_user and ab_register_user tables"""
with op.batch_alter_table("ab_user") as batch_op:
batch_op.alter_column("first_name", type_=sa.String(256), existing_nullable=False)
batch_op.alter_column("last_name", type_=sa.String(256), exi... |
Revert length of user identifier columns in ab_user and ab_register_user tables | def downgrade():
"""Revert length of user identifier columns in ab_user and ab_register_user tables"""
conn = op.get_bind()
if conn.dialect.name != "mssql":
with op.batch_alter_table("ab_user") as batch_op:
batch_op.alter_column("first_name", type_=sa.String(64), existing_nullable=False)... |
Apply Add onupdate cascade to taskmap | def upgrade():
"""Apply Add onupdate cascade to taskmap"""
with op.batch_alter_table("task_map") as batch_op:
batch_op.drop_constraint("task_map_task_instance_fkey", type_="foreignkey")
batch_op.create_foreign_key(
"task_map_task_instance_fkey",
"task_instance",
... |
Unapply Add onupdate cascade to taskmap | def downgrade():
"""Unapply Add onupdate cascade to taskmap"""
with op.batch_alter_table("task_map") as batch_op:
batch_op.drop_constraint("task_map_task_instance_fkey", type_="foreignkey")
batch_op.create_foreign_key(
"task_map_task_instance_fkey",
"task_instance",
... |
Apply Add index to task_instance table | def upgrade():
"""Apply Add index to task_instance table"""
# We don't add this index anymore because it's not useful.
pass |
Unapply Add index to task_instance table | def downgrade():
"""Unapply Add index to task_instance table"""
# At 2.8.1 we removed this index as it is not used, and changed this migration not to add it
# So we use drop if exists (cus it might not be there)
import sqlalchemy
from contextlib import suppress
with suppress(sqlalchemy.exc.Data... |
Apply Add custom_operator_name column | def upgrade():
"""Apply Add custom_operator_name column"""
with op.batch_alter_table(TABLE_NAME) as batch_op:
batch_op.add_column(sa.Column("custom_operator_name", sa.VARCHAR(length=1000), nullable=True)) |
Unapply Add custom_operator_name column | def downgrade():
"""Unapply Add custom_operator_name column"""
with op.batch_alter_table(TABLE_NAME) as batch_op:
batch_op.drop_column("custom_operator_name") |
Apply add include_deferred column to pool | def upgrade():
"""Apply add include_deferred column to pool"""
with op.batch_alter_table("slot_pool") as batch_op:
batch_op.add_column(sa.Column("include_deferred", sa.Boolean))
# Different databases support different literal for FALSE. This is fine.
op.execute(sa.text(f"UPDATE slot_pool SET inc... |
Unapply add include_deferred column to pool | def downgrade():
"""Unapply add include_deferred column to pool"""
with op.batch_alter_table("slot_pool") as batch_op:
batch_op.drop_column("include_deferred") |
Apply add cleared column to dagrun | def upgrade():
"""Apply add cleared column to dagrun"""
conn = op.get_bind()
if conn.dialect.name == "mssql":
with op.batch_alter_table("dag_run") as batch_op:
batch_op.add_column(sa.Column("clear_number", sa.Integer, default=0))
batch_op.alter_column("clear_number", existing... |
Unapply add cleared column to pool | def downgrade():
"""Unapply add cleared column to pool"""
with op.batch_alter_table("dag_run") as batch_op:
batch_op.drop_column("clear_number") |
Adds owner_display_name column to log | def upgrade():
"""Adds owner_display_name column to log"""
with op.batch_alter_table(TABLE_NAME) as batch_op:
batch_op.add_column(sa.Column("owner_display_name", sa.String(500))) |
Removes owner_display_name column from log | def downgrade():
"""Removes owner_display_name column from log"""
with op.batch_alter_table(TABLE_NAME) as batch_op:
batch_op.drop_column("owner_display_name") |
Apply Make connection login/password TEXT | def upgrade():
"""Apply Make connection login/password TEXT"""
with op.batch_alter_table("connection", schema=None) as batch_op:
batch_op.alter_column(
"login", existing_type=sa.VARCHAR(length=500), type_=sa.Text(), existing_nullable=True
)
batch_op.alter_column(
... |
Unapply Make connection login/password TEXT | def downgrade():
"""Unapply Make connection login/password TEXT"""
with op.batch_alter_table("connection", schema=None) as batch_op:
batch_op.alter_column(
"password", existing_type=sa.Text(), type_=sa.VARCHAR(length=5000), existing_nullable=True
)
batch_op.alter_column(
... |
Apply Add processor_subdir to ImportError. | def upgrade():
"""Apply Add processor_subdir to ImportError."""
conn = op.get_bind()
with op.batch_alter_table("import_error") as batch_op:
if conn.dialect.name == "mysql":
batch_op.add_column(sa.Column("processor_subdir", sa.Text(length=2000), nullable=True))
else:
... |
Unapply Add processor_subdir to ImportError. | def downgrade():
"""Unapply Add processor_subdir to ImportError."""
conn = op.get_bind()
with op.batch_alter_table("import_error", schema=None) as batch_op:
batch_op.drop_column("processor_subdir") |
Apply refactor dag run indexes | def upgrade():
"""Apply refactor dag run indexes"""
# This index may have been created in 2.7 but we've since removed it from migrations
import sqlalchemy
from contextlib import suppress
with suppress(sqlalchemy.exc.DatabaseError): # mysql does not support drop if exists index
op.drop_inde... |
Unapply refactor dag run indexes | def downgrade():
"""Unapply refactor dag run indexes""" |
Apply Add rendered_map_index to TaskInstance. | def upgrade():
"""Apply Add rendered_map_index to TaskInstance."""
conn = op.get_bind()
with op.batch_alter_table("task_instance") as batch_op:
batch_op.add_column(sa.Column("rendered_map_index", sa.String(length=250), nullable=True)) |
Unapply Add rendered_map_index to TaskInstance. | def downgrade():
"""Unapply Add rendered_map_index to TaskInstance."""
conn = op.get_bind()
with op.batch_alter_table("task_instance", schema=None) as batch_op:
batch_op.drop_column("rendered_map_index") |
Apply Add run_id to Log and increase Log event name length. | def upgrade():
"""Apply Add run_id to Log and increase Log event name length."""
# Note: we could repopulate the run_id of old runs via a join with DagRun on date + dag_id,
# But this would incur a potentially heavy migration for non-essential changes.
# Instead, we've chosen to only populate this colu... |
Unapply Add run_id to Log and increase Log event name length. | def downgrade():
"""Unapply Add run_id to Log and increase Log event name length."""
with op.batch_alter_table("log") as batch_op:
batch_op.drop_column("run_id")
conn = op.get_bind()
if conn.dialect.name == "mssql":
with op.batch_alter_table("log") as batch_op:
batch_op.drop... |
Apply Add dataset_expression to DagModel. | def upgrade():
"""Apply Add dataset_expression to DagModel."""
with op.batch_alter_table("dag") as batch_op:
batch_op.add_column(sa.Column('dataset_expression', sqlalchemy_jsonfield.JSONField(json=json), nullable=True)) |
Unapply Add dataset_expression to DagModel. | def downgrade():
"""Unapply Add dataset_expression to DagModel."""
with op.batch_alter_table("dag") as batch_op:
batch_op.drop_column('dataset_expression') |
Apply Adding max_consecutive_failed_dag_runs column to dag_model table | def upgrade():
"""Apply Adding max_consecutive_failed_dag_runs column to dag_model table"""
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('dag', schema=None) as batch_op:
batch_op.add_column(sa.Column('max_consecutive_failed_dag_runs', sa.Integer())) |
Unapply Adding max_consecutive_failed_dag_runs column to dag_model table | def downgrade():
"""Unapply Adding max_consecutive_failed_dag_runs column to dag_model table"""
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('dag', schema=None) as batch_op:
batch_op.drop_column('max_consecutive_failed_dag_runs') |
Apply Change value column type to longblob in xcom table for mysql | def upgrade():
"""Apply Change value column type to longblob in xcom table for mysql"""
conn = op.get_bind()
if conn.dialect.name == "mysql":
with op.batch_alter_table("xcom", schema=None) as batch_op:
batch_op.alter_column("value", type_=sa.LargeBinary().with_variant(LONGBLOB, "mysql")) |
Unapply Change value column type to longblob in xcom table for mysql | def downgrade():
"""Unapply Change value column type to longblob in xcom table for mysql"""
conn = op.get_bind()
if conn.dialect.name == "mysql":
with op.batch_alter_table("xcom", schema=None) as batch_op:
batch_op.alter_column("value", type_=sa.LargeBinary) |
Apply add display name for dag and task instance | def upgrade():
"""Apply add display name for dag and task instance"""
op.add_column("dag", sa.Column("dag_display_name", sa.String(2000), nullable=True))
op.add_column("task_instance", sa.Column("task_display_name", sa.String(2000), nullable=True)) |
Unapply add display name for dag and task instance | def downgrade():
"""Unapply add display name for dag and task instance"""
op.drop_column("dag", "dag_display_name")
op.drop_column("task_instance", "task_display_name") |
Update trigger kwargs type to string and encrypt | def upgrade():
"""Update trigger kwargs type to string and encrypt"""
with op.batch_alter_table("trigger") as batch_op:
batch_op.alter_column("kwargs", type_=sa.Text(), )
if not context.is_offline_mode():
session = get_session()
try:
for trigger in session.query(Trigger... |
Unapply update trigger kwargs type to string and encrypt | def downgrade():
"""Unapply update trigger kwargs type to string and encrypt"""
if context.is_offline_mode():
print(dedent("""
------------
-- WARNING: Unable to decrypt trigger kwargs automatically in offline mode!
-- If any trigger rows exist when you do an offline downgrade,... |
Apply add executor field to task instance | def upgrade():
"""Apply add executor field to task instance"""
op.add_column('task_instance', sa.Column('executor', sa.String(length=1000), default=None)) |
Unapply add executor field to task instance | def downgrade():
"""Unapply add executor field to task instance"""
op.drop_column('task_instance', 'executor') |
Get SQLAlchemy args to use for COLLATION. | def get_id_collation_args():
"""Get SQLAlchemy args to use for COLLATION."""
collation = conf.get("database", "sql_engine_collation_for_ids", fallback=None)
if collation:
return {"collation": collation}
else:
# Automatically use utf8mb3_bin collation for mysql
# This is backwards... |
Given a number of tasks, builds a dependency chain.
This function accepts values of BaseOperator (aka tasks), EdgeModifiers (aka Labels), XComArg, TaskGroups,
or lists containing any mix of these types (or a mix in the same list). If you want to chain between two
lists you must ensure they have the same length.
Using... | def chain(*tasks: DependencyMixin | Sequence[DependencyMixin]) -> None:
r"""
Given a number of tasks, builds a dependency chain.
This function accepts values of BaseOperator (aka tasks), EdgeModifiers (aka Labels), XComArg, TaskGroups,
or lists containing any mix of these types (or a mix in the same li... |
Set downstream dependencies for all tasks in from_tasks to all tasks in to_tasks.
Using classic operators/sensors:
.. code-block:: python
cross_downstream(from_tasks=[t1, t2, t3], to_tasks=[t4, t5, t6])
is equivalent to::
t1 ---> t4
\ /
t2 -X -> t5
/ \
t3 ---> t6
.. code-block:: pyth... | def cross_downstream(
from_tasks: Sequence[DependencyMixin],
to_tasks: DependencyMixin | Sequence[DependencyMixin],
):
r"""
Set downstream dependencies for all tasks in from_tasks to all tasks in to_tasks.
Using classic operators/sensors:
.. code-block:: python
cross_downstream(from_t... |
Simplify task dependency definition.
E.g.: suppose you want precedence like so::
╭─op2─╮ ╭─op4─╮
op1─┤ ├─├─op5─┤─op7
╰-op3─╯ ╰-op6─╯
Then you can accomplish like so::
chain_linear(op1, [op2, op3], [op4, op5, op6], op7)
:param elements: a list of operators / lists of operators | def chain_linear(*elements: DependencyMixin | Sequence[DependencyMixin]):
"""
Simplify task dependency definition.
E.g.: suppose you want precedence like so::
╭─op2─╮ ╭─op4─╮
op1─┤ ├─├─op5─┤─op7
╰-op3─╯ ╰-op6─╯
Then you can accomplish like so::
chain_linea... |
PEP-562: Lazy loaded attributes on python modules.
:meta private: | def __getattr__(name):
"""
PEP-562: Lazy loaded attributes on python modules.
:meta private:
"""
path = __deprecated_imports.get(name)
if not path:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
from airflow.utils.module_loading import import_string
war... |
Do not use, this method is deprecated. | def parse_netloc_to_hostname(*args, **kwargs):
"""Do not use, this method is deprecated."""
warnings.warn("This method is deprecated.", RemovedInAirflow3Warning, stacklevel=2)
return _parse_netloc_to_hostname(*args, **kwargs) |
Sanitizes the connection id and allows only specific characters to be within.
Namely, it allows alphanumeric characters plus the symbols #,!,-,_,.,:,\,/ and () from 1 and up to
250 consecutive matches. If desired, the max length can be adjusted by setting `max_length`.
You can try to play with the regex here: https:/... | def sanitize_conn_id(conn_id: str | None, max_length=CONN_ID_MAX_LEN) -> str | None:
r"""Sanitizes the connection id and allows only specific characters to be within.
Namely, it allows alphanumeric characters plus the symbols #,!,-,_,.,:,\,/ and () from 1 and up to
250 consecutive matches. If desired, the ... |
Parse a URI string to get the correct Hostname.
``urlparse(...).hostname`` or ``urlsplit(...).hostname`` returns value into the lowercase in most cases,
there are some exclusion exists for specific cases such as https://bugs.python.org/issue32323
In case if expected to get a path as part of hostname path,
then default... | def _parse_netloc_to_hostname(uri_parts):
"""
Parse a URI string to get the correct Hostname.
``urlparse(...).hostname`` or ``urlsplit(...).hostname`` returns value into the lowercase in most cases,
there are some exclusion exists for specific cases such as https://bugs.python.org/issue32323
In cas... |
Deferred load of Fernet key.
This function could fail either because Cryptography is not installed
or because the Fernet key is invalid.
:return: Fernet object
:raises: airflow.exceptions.AirflowException if there's a problem trying to load Fernet | def get_fernet():
"""
Deferred load of Fernet key.
This function could fail either because Cryptography is not installed
or because the Fernet key is invalid.
:return: Fernet object
:raises: airflow.exceptions.AirflowException if there's a problem trying to load Fernet
"""
from cryptog... |
Create a Timetable instance from a ``schedule_interval`` argument. | def create_timetable(interval: ScheduleIntervalArg, timezone: Timezone | FixedTimezone) -> Timetable:
"""Create a Timetable instance from a ``schedule_interval`` argument."""
if interval is NOTSET:
return DeltaDataIntervalTimetable(DEFAULT_SCHEDULE_INTERVAL)
if interval is None:
return NullT... |
Return the last dag run for a dag, None if there was none.
Last dag run can be any type of run e.g. scheduled or backfilled.
Overridden DagRuns are ignored. | def get_last_dagrun(dag_id, session, include_externally_triggered=False):
"""
Return the last dag run for a dag, None if there was none.
Last dag run can be any type of run e.g. scheduled or backfilled.
Overridden DagRuns are ignored.
"""
DR = DagRun
query = select(DR).where(DR.dag_id == da... |
Get next run info for a list of dag_ids.
Given a list of dag_ids, get string representing how close any that are dataset triggered are
their next run, e.g. "1 of 2 datasets updated". | def get_dataset_triggered_next_run_info(
dag_ids: list[str], *, session: Session
) -> dict[str, dict[str, int | str]]:
"""
Get next run info for a list of dag_ids.
Given a list of dag_ids, get string representing how close any that are dataset triggered are
their next run, e.g. "1 of 2 datasets upd... |
Python dag decorator which wraps a function into an Airflow DAG.
Accepts kwargs for operator kwarg. Can be used to parameterize DAGs.
:param dag_args: Arguments for DAG object
:param dag_kwargs: Kwargs for DAG object. | def dag(
dag_id: str = "",
description: str | None = None,
schedule: ScheduleArg = NOTSET,
schedule_interval: ScheduleIntervalArg = NOTSET,
timetable: Timetable | None = None,
start_date: datetime | None = None,
end_date: datetime | None = None,
full_filepath: str | None = None,
temp... |
Run a single task instance, and push result to Xcom for downstream tasks.
Bypasses a lot of extra steps used in `task.run` to keep our local running as fast as
possible. This function is only meant for the `dag.test` function as a helper function.
Args:
ti: TaskInstance to run | def _run_task(*, ti: TaskInstance, inline_trigger: bool = False, session: Session):
"""
Run a single task instance, and push result to Xcom for downstream tasks.
Bypasses a lot of extra steps used in `task.run` to keep our local running as fast as
possible. This function is only meant for the `dag.tes... |
Create a DAG run, replacing an existing instance if needed to prevent collisions.
This function is only meant to be used by :meth:`DAG.test` as a helper function.
:param dag: DAG to be used to find run.
:param conf: Configuration to pass to newly created run.
:param start_date: Start date of new run.
:param execution... | def _get_or_create_dagrun(
dag: DAG,
conf: dict[Any, Any] | None,
start_date: datetime,
execution_date: datetime,
run_id: str,
session: Session,
data_interval: tuple[datetime, datetime] | None = None,
) -> DagRun:
"""Create a DAG run, replacing an existing instance if needed to prevent c... |
Creator the ``note`` association proxy. | def _creator_note(val):
"""Creator the ``note`` association proxy."""
if isinstance(val, str):
return DagRunNote(content=val)
elif isinstance(val, dict):
return DagRunNote(**val)
else:
return DagRunNote(*val) |
Whether a task needs expansion at runtime.
A task needs expansion if it either
* Is a mapped operator, or
* Is in a mapped task group.
This is implemented as a free function (instead of a property) so we can
make it a type guard. | def needs_expansion(task: AbstractOperator) -> TypeGuard[Operator]:
"""Whether a task needs expansion at runtime.
A task needs expansion if it either
* Is a mapped operator, or
* Is in a mapped task group.
This is implemented as a free function (instead of a property) so we can
make it a type... |
Merge, validate params, and convert them into a simple dict. | def process_params(
dag: DAG,
task: Operator,
dag_run: DagRun | DagRunPydantic | None,
*,
suppress_exception: bool,
) -> dict[str, Any]:
"""Merge, validate params, and convert them into a simple dict."""
from airflow.configuration import conf
params = ParamsDict(suppress_exception=suppr... |
Get and serialize the template fields for a task.
Used in preparing to store them in RTIF table.
:param task: Operator instance with rendered template fields
:meta private: | def get_serialized_template_fields(task: Operator):
"""
Get and serialize the template fields for a task.
Used in preparing to store them in RTIF table.
:param task: Operator instance with rendered template fields
:meta private:
"""
return {field: serialize_template_field(getattr(task, fi... |
Set the current execution context to the provided context object.
This method should be called once per Task execution, before calling operator.execute. | def set_current_context(context: Context) -> Generator[Context, None, None]:
"""
Set the current execution context to the provided context object.
This method should be called once per Task execution, before calling operator.execute.
"""
_CURRENT_CONTEXT.append(context)
try:
yield conte... |
Stop non-teardown tasks in dag.
:meta private: | def _stop_remaining_tasks(*, task_instance: TaskInstance | TaskInstancePydantic, session: Session):
"""
Stop non-teardown tasks in dag.
:meta private:
"""
if not task_instance.dag_run:
raise ValueError("``task_instance`` must have ``dag_run`` set")
tis = task_instance.dag_run.get_task_i... |
Clear a set of task instances, but make sure the running ones get killed.
Also sets Dagrun's `state` to QUEUED and `start_date` to the time of execution.
But only for finished DRs (SUCCESS and FAILED).
Doesn't clear DR's `state` and `start_date`for running
DRs (QUEUED and RUNNING) because clearing the state for alread... | def clear_task_instances(
tis: list[TaskInstance],
session: Session,
activate_dag_runs: None = None,
dag: DAG | None = None,
dag_run_state: DagRunState | Literal[False] = DagRunState.QUEUED,
) -> None:
"""
Clear a set of task instances, but make sure the running ones get killed.
Also se... |
Whether a value can be used for task mapping.
We only allow collections with guaranteed ordering, but exclude character
sequences since that's usually not what users would expect to be mappable. | def _is_mappable_value(value: Any) -> TypeGuard[Collection]:
"""Whether a value can be used for task mapping.
We only allow collections with guaranteed ordering, but exclude character
sequences since that's usually not what users would expect to be mappable.
"""
if not isinstance(value, (collection... |
Creator the ``note`` association proxy. | def _creator_note(val):
"""Creator the ``note`` association proxy."""
if isinstance(val, str):
return TaskInstanceNote(content=val)
elif isinstance(val, dict):
return TaskInstanceNote(**val)
else:
return TaskInstanceNote(*val) |
Execute Task (optionally with a Timeout) and push Xcom results.
:param task_instance: the task instance
:param context: Jinja2 context
:param task_orig: origin task
:meta private: | def _execute_task(task_instance: TaskInstance | TaskInstancePydantic, context: Context, task_orig: Operator):
"""
Execute Task (optionally with a Timeout) and push Xcom results.
:param task_instance: the task instance
:param context: Jinja2 context
:param task_orig: origin task
:meta private:
... |
Refresh the task instance from the database based on the primary key.
:param task_instance: the task instance
:param session: SQLAlchemy ORM Session
:param lock_for_update: if True, indicates that the database should
lock the TaskInstance (issuing a FOR UPDATE clause) until the
session is committed.
:meta pri... | def _refresh_from_db(
*,
task_instance: TaskInstance | TaskInstancePydantic,
session: Session | None = None,
lock_for_update: bool = False,
) -> None:
"""
Refresh the task instance from the database based on the primary key.
:param task_instance: the task instance
:param session: SQLAlc... |
Set task instance duration.
:param task_instance: the task instance
:meta private: | def _set_duration(*, task_instance: TaskInstance | TaskInstancePydantic) -> None:
"""
Set task instance duration.
:param task_instance: the task instance
:meta private:
"""
if task_instance.end_date and task_instance.start_date:
task_instance.duration = (task_instance.end_date - task_i... |
Return task instance tags.
:param task_instance: the task instance
:meta private: | def _stats_tags(*, task_instance: TaskInstance | TaskInstancePydantic) -> dict[str, str]:
"""
Return task instance tags.
:param task_instance: the task instance
:meta private:
"""
return prune_dict({"dag_id": task_instance.dag_id, "task_id": task_instance.task_id}) |
Ensure we unset next_method and next_kwargs to ensure that any retries don't reuse them.
:param task_instance: the task instance
:meta private: | def _clear_next_method_args(*, task_instance: TaskInstance | TaskInstancePydantic) -> None:
"""
Ensure we unset next_method and next_kwargs to ensure that any retries don't reuse them.
:param task_instance: the task instance
:meta private:
"""
log.debug("Clearing next_method and next_kwargs.")... |
Return TI Context.
:param task_instance: the task instance
:param session: SQLAlchemy ORM Session
:param ignore_param_exceptions: flag to suppress value exceptions while initializing the ParamsDict
:meta private: | def _get_template_context(
*,
task_instance: TaskInstance | TaskInstancePydantic,
session: Session | None = None,
ignore_param_exceptions: bool = True,
) -> Context:
"""
Return TI Context.
:param task_instance: the task instance
:param session: SQLAlchemy ORM Session
:param ignore_p... |
Is task instance is eligible for retry.
:param task_instance: the task instance
:meta private: | def _is_eligible_to_retry(*, task_instance: TaskInstance | TaskInstancePydantic):
"""
Is task instance is eligible for retry.
:param task_instance: the task instance
:meta private:
"""
if task_instance.state == TaskInstanceState.RESTARTING:
# If a task is cleared when running, it goes ... |
Handle Failure for a task instance.
:param task_instance: the task instance
:param error: if specified, log the specific exception if thrown
:param session: SQLAlchemy ORM Session
:param test_mode: doesn't record success or failure in the DB if True
:param context: Jinja2 context
:param force_fail: if True, task does ... | def _handle_failure(
*,
task_instance: TaskInstance | TaskInstancePydantic,
error: None | str | BaseException,
session: Session,
test_mode: bool | None = None,
context: Context | None = None,
force_fail: bool = False,
) -> None:
"""
Handle Failure for a task instance.
:param tas... |
Return the try number that a task number will be when it is actually run.
If the TaskInstance is currently running, this will match the column in the
database, in all other cases this will be incremented.
This is designed so that task logs end up in the right file.
:param task_instance: the task instance
:meta priv... | def _get_try_number(*, task_instance: TaskInstance):
"""
Return the try number that a task number will be when it is actually run.
If the TaskInstance is currently running, this will match the column in the
database, in all other cases this will be incremented.
This is designed so that task logs e... |
Opposite of _get_try_number.
Given the value returned by try_number, return the value of _try_number that
should produce the same result.
This is needed for setting _try_number on TaskInstance from the value on PydanticTaskInstance, which has no private attrs.
:param task_instance: the task instance
:meta private: | def _get_private_try_number(*, task_instance: TaskInstance | TaskInstancePydantic):
"""
Opposite of _get_try_number.
Given the value returned by try_number, return the value of _try_number that
should produce the same result.
This is needed for setting _try_number on TaskInstance from the value on ... |
Set a task try number.
:param task_instance: the task instance
:param value: the try number
:meta private: | def _set_try_number(*, task_instance: TaskInstance | TaskInstancePydantic, value: int) -> None:
"""
Set a task try number.
:param task_instance: the task instance
:param value: the try number
:meta private:
"""
task_instance._try_number = value |
Copy common attributes from the given task.
:param task_instance: the task instance
:param task: The task object to copy from
:param pool_override: Use the pool_override instead of task's pool
:meta private: | def _refresh_from_task(
*, task_instance: TaskInstance | TaskInstancePydantic, task: Operator, pool_override: str | None = None
) -> None:
"""
Copy common attributes from the given task.
:param task_instance: the task instance
:param task: The task object to copy from
:param pool_override: Use ... |
Record the task map for downstream tasks.
:param task_instance: the task instance
:param task: The task object
:param value: The value
:param session: SQLAlchemy ORM Session
:meta private: | def _record_task_map_for_downstreams(
*, task_instance: TaskInstance | TaskInstancePydantic, task: Operator, value: Any, session: Session
) -> None:
"""
Record the task map for downstream tasks.
:param task_instance: the task instance
:param task: The task object
:param value: The value
:pa... |
Return the DagRun that ran prior to this task instance's DagRun.
:param task_instance: the task instance
:param state: If passed, it only take into account instances of a specific state.
:param session: SQLAlchemy ORM Session.
:meta private: | def _get_previous_dagrun(
*,
task_instance: TaskInstance | TaskInstancePydantic,
state: DagRunState | None = None,
session: Session | None = None,
) -> DagRun | None:
"""
Return the DagRun that ran prior to this task instance's DagRun.
:param task_instance: the task instance
:param stat... |
Get execution date from property previous_ti_success.
:param task_instance: the task instance
:param session: SQLAlchemy ORM Session
:param state: If passed, it only take into account instances of a specific state.
:meta private: | def _get_previous_execution_date(
*,
task_instance: TaskInstance | TaskInstancePydantic,
state: DagRunState | None,
session: Session,
) -> pendulum.DateTime | None:
"""
Get execution date from property previous_ti_success.
:param task_instance: the task instance
:param session: SQLAlche... |
Send alert email with exception information.
:param task_instance: the task instance
:param exception: the exception
:param task: task related to the exception
:meta private: | def _email_alert(
*, task_instance: TaskInstance | TaskInstancePydantic, exception, task: BaseOperator
) -> None:
"""
Send alert email with exception information.
:param task_instance: the task instance
:param exception: the exception
:param task: task related to the exception
:meta privat... |
Get the email subject content for exceptions.
:param task_instance: the task instance
:param exception: the exception sent in the email
:param task:
:meta private: | def _get_email_subject_content(
*,
task_instance: TaskInstance | TaskInstancePydantic,
exception: BaseException,
task: BaseOperator | None = None,
) -> tuple[str, str, str]:
"""
Get the email subject content for exceptions.
:param task_instance: the task instance
:param exception: the e... |
Run callback after task finishes.
:param callbacks: callbacks to run
:param context: callbacks context
:meta private: | def _run_finished_callback(
*,
callbacks: None | TaskStateChangeCallback | list[TaskStateChangeCallback],
context: Context,
) -> None:
"""
Run callback after task finishes.
:param callbacks: callbacks to run
:param context: callbacks context
:meta private:
"""
if callbacks:
... |
Log task state.
:param task_instance: the task instance
:param lead_msg: lead message
:meta private: | def _log_state(*, task_instance: TaskInstance | TaskInstancePydantic, lead_msg: str = "") -> None:
"""
Log task state.
:param task_instance: the task instance
:param lead_msg: lead message
:meta private:
"""
params = [
lead_msg,
str(task_instance.state).upper(),
tas... |
Fetch a date attribute or None of it does not exist.
:param task_instance: the task instance
:param attr: the attribute name
:meta private: | def _date_or_empty(*, task_instance: TaskInstance | TaskInstancePydantic, attr: str) -> str:
"""
Fetch a date attribute or None of it does not exist.
:param task_instance: the task instance
:param attr: the attribute name
:meta private:
"""
result: datetime | None = getattr(task_instance, ... |
Get task instance for the task that ran before this task instance.
:param task_instance: the task instance
:param state: If passed, it only take into account instances of a specific state.
:param session: SQLAlchemy ORM Session
:meta private: | def _get_previous_ti(
*,
task_instance: TaskInstance | TaskInstancePydantic,
session: Session,
state: DagRunState | None = None,
) -> TaskInstance | TaskInstancePydantic | None:
"""
Get task instance for the task that ran before this task instance.
:param task_instance: the task instance
... |
Given two operators, find their innermost common mapped task group. | def _find_common_ancestor_mapped_group(node1: Operator, node2: Operator) -> MappedTaskGroup | None:
"""Given two operators, find their innermost common mapped task group."""
if node1.dag is None or node2.dag is None or node1.dag_id != node2.dag_id:
return None
parent_group_ids = {g.group_id for g in... |
Whether given operator is *further* mapped inside a task group. | def _is_further_mapped_inside(operator: Operator, container: TaskGroup) -> bool:
"""Whether given operator is *further* mapped inside a task group."""
if isinstance(operator, MappedOperator):
return True
task_group = operator.task_group
while task_group is not None and task_group.group_id != con... |
Patch a custom ``serialize_value`` to accept the modern signature.
To give custom XCom backends more flexibility with how they store values, we
now forward all params passed to ``XCom.set`` to ``XCom.serialize_value``.
In order to maintain compatibility with custom XCom backends written with
the old signature, we chec... | def _patch_outdated_serializer(clazz: type[BaseXCom], params: Iterable[str]) -> None:
"""Patch a custom ``serialize_value`` to accept the modern signature.
To give custom XCom backends more flexibility with how they store values, we
now forward all params passed to ``XCom.set`` to ``XCom.serialize_value``.... |
Return the list of variables names of a function.
:param function: The function to inspect | def _get_function_params(function) -> list[str]:
"""
Return the list of variables names of a function.
:param function: The function to inspect
"""
parameters = inspect.signature(function).parameters
bound_arguments = [
name for name, p in parameters.items() if p.kind not in (p.VAR_POSI... |
Resolve custom XCom class.
Confirm that custom XCom class extends the BaseXCom.
Compare the function signature of the custom XCom serialize_value to the base XCom serialize_value. | def resolve_xcom_backend() -> type[BaseXCom]:
"""Resolve custom XCom class.
Confirm that custom XCom class extends the BaseXCom.
Compare the function signature of the custom XCom serialize_value to the base XCom serialize_value.
"""
clazz = conf.getimport("core", "xcom_backend", fallback=f"airflow.... |
Try to "describe" a callable by getting its name. | def _get_callable_name(f: Callable | str) -> str:
"""Try to "describe" a callable by getting its name."""
if callable(f):
return f.__name__
# Parse the source to find whatever is behind "def". For safety, we don't
# want to evaluate the code in any meaningful way!
with contextlib.suppress(Ex... |
DAG serialization interface. | def serialize_xcom_arg(value: XComArg) -> dict[str, Any]:
"""DAG serialization interface."""
key = next(k for k, v in _XCOM_ARG_TYPES.items() if v == type(value))
if key:
return {"type": key, **value._serialize()}
return value._serialize() |
DAG serialization interface. | def deserialize_xcom_arg(data: dict[str, Any], dag: DAG) -> XComArg:
"""DAG serialization interface."""
klass = _XCOM_ARG_TYPES[data.get("type", "")]
return klass._deserialize(data, dag) |
Ensure upper and lower time targets are datetimes by combining them with base_date. | def target_times_as_dates(
base_date: datetime.datetime,
lower: datetime.datetime | datetime.time | None,
upper: datetime.datetime | datetime.time | None,
):
"""Ensure upper and lower time targets are datetimes by combining them with base_date."""
if isinstance(lower, datetime.datetime) and isinstan... |
Check if the virtualenv package is installed via checking if it is on the path or installed as package.
:return: True if it is. Whichever way of checking it works, is fine. | def is_venv_installed() -> bool:
"""
Check if the virtualenv package is installed via checking if it is on the path or installed as package.
:return: True if it is. Whichever way of checking it works, is fine.
"""
if shutil.which("virtualenv") or importlib.util.find_spec("virtualenv"):
retu... |
Use :func:`airflow.decorators.task` instead, this is deprecated.
Calls ``@task.python`` and allows users to turn a Python function into
an Airflow task.
: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 (te... | def task(python_callable: Callable | None = None, multiple_outputs: bool | None = None, **kwargs):
"""Use :func:`airflow.decorators.task` instead, this is deprecated.
Calls ``@task.python`` and allows users to turn a Python function into
an Airflow task.
:param python_callable: A reference to an objec... |
Parse python version info from a text. | def _parse_version_info(text: str) -> tuple[int, int, int, str, int]:
"""Parse python version info from a text."""
parts = text.strip().split(".")
if len(parts) != 5:
msg = f"Invalid Python version info, expected 5 components separated by '.', but got {text!r}."
raise ValueError(msg)
try... |
Retrieve the execution context dictionary without altering user method's signature.
This is the simplest method of retrieving the execution context dictionary.
**Old style:**
.. code:: python
def my_task(**context):
ti = context["ti"]
**New style:**
.. code:: python
from airflow.operators.python ... | def get_current_context() -> Context:
"""
Retrieve the execution context dictionary without altering user method's signature.
This is the simplest method of retrieving the execution context dictionary.
**Old style:**
.. code:: python
def my_task(**context):
ti = context["ti"]... |
Unify bucket name and key if a key is provided but not a bucket name. | def provide_bucket_name(func: T) -> T:
"""Unify bucket name and key if a key is provided but not a bucket name."""
function_signature = signature(func)
@wraps(func)
def wrapper(*args, **kwargs) -> T:
bound_args = function_signature.bind(*args, **kwargs)
self = args[0]
if bound_a... |
Unify bucket name and key if a key is provided but not a bucket name. | def unify_bucket_name_and_key(func: T) -> T:
"""Unify bucket name and key if a key is provided but not a bucket name."""
function_signature = signature(func)
@wraps(func)
def wrapper(*args, **kwargs) -> T:
bound_args = function_signature.bind(*args, **kwargs)
def get_key() -> str:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.