Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Terminate PG query when task is killed via Airflow (#717)

rwidom3ab5e572b061
diff --git a/openverse_catalog/dags/common/loader/loader.py b/openverse_catalog/dags/common/loader/loader.py
index 63081f91b..a4095db84 100644
--- a/openverse_catalog/dags/common/loader/loader.py
+++ b/openverse_catalog/dags/common/loader/loader.py
@@ -1,3 +1,4 @@
+from airflow.models.abstractoperator import AbstractOperator
from common.loader import paths, s3, sql
from common.loader.paths import _extract_media_type
from common.loader.reporting import RecordMetrics
@@ -17,6 +18,7 @@ def load_s3_data(
postgres_conn_id,
identifier,
ti,
+ task,
):
media_type = ti.xcom_pull(task_ids="stage_oldest_tsv_file", key="media_type")
tsv_version = ti.xcom_pull(task_ids="stage_oldest_tsv_file", key="tsv_version")
@@ -27,10 +29,14 @@ def load_s3_data(
identifier, bucket, aws_conn_id, media_prefix=media_type
)
sql.load_s3_data_to_intermediate_table(
- postgres_conn_id, bucket, tsv_key, identifier, media_type
+ postgres_conn_id, bucket, tsv_key, identifier, media_type, task
)
sql.upsert_records_to_db_table(
- postgres_conn_id, identifier, media_type=media_type, tsv_version=tsv_version
+ postgres_conn_id,
+ identifier,
+ media_type=media_type,
+ tsv_version=tsv_version,
+ task=task,
)
@@ -41,6 +47,7 @@ def upsert_data(
identifier: str,
loaded_count: int,
duplicates_count: tuple[int, int],
+ task: AbstractOperator = None,
) -> RecordMetrics:
"""
Upsert data into the catalog DB from the loading table, and calculate
@@ -48,7 +55,11 @@ def upsert_data(
"""
missing_columns, foreign_id_dup = duplicates_count
upserted = sql.upsert_records_to_db_table(
- postgres_conn_id, identifier, media_type=media_type, tsv_version=tsv_version
+ postgres_conn_id,
+ identifier,
+ media_type=media_type,
+ tsv_version=tsv_version,
+ task=task,
)
url_dup = loaded_count - missing_columns - foreign_id_dup - upserted
diff --git a/openverse_catalog/dags/common/loader/sql.py b/openverse_catalog/dags/common/loader/sql.py
index 903b6ca1f..9cec55915 100644
--- a/openverse_catalog/dags/common/loader/sql.py
+++ b/openverse_catalog/dags/common/loader/sql.py
@@ -1,10 +1,11 @@
import logging
from textwrap import dedent
-from airflow.providers.postgres.hooks.postgres import PostgresHook
+from airflow.models.abstractoperator import AbstractOperator
from common.constants import AUDIO, IMAGE, MediaType
from common.loader import provider_details as prov
from common.loader.paths import _extract_media_type
+from common.sql import PostgresHook
from common.storage import columns as col
from common.storage.columns import NULL, Column, UpsertStrategy
from common.storage.db_columns import AUDIO_TABLE_COLUMNS, IMAGE_TABLE_COLUMNS
@@ -68,7 +69,10 @@ def create_loading_table(
):
"""Create intermediary table and indices if they do not exist."""
load_table = _get_load_table_name(identifier, media_type=media_type)
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=10.0,
+ )
loading_table_columns = TSV_COLUMNS[media_type]
columns_definition = f"{create_column_definitions(loading_table_columns)}"
table_creation_query = dedent(
@@ -102,13 +106,20 @@ def create_loading_table(
def load_local_data_to_intermediate_table(
- postgres_conn_id, tsv_file_name, identifier, max_rows_to_skip=10
+ postgres_conn_id,
+ tsv_file_name,
+ identifier,
+ max_rows_to_skip=10,
+ task: AbstractOperator = None,
):
media_type = _extract_media_type(tsv_file_name)
load_table = _get_load_table_name(identifier, media_type=media_type)
logger.info(f"Loading {tsv_file_name} into {load_table}")
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
load_successful = False
while not load_successful and max_rows_to_skip >= 0:
@@ -150,11 +161,15 @@ def load_s3_data_to_intermediate_table(
s3_key,
identifier,
media_type=IMAGE,
+ task: AbstractOperator = None,
) -> int:
load_table = _get_load_table_name(identifier, media_type=media_type)
logger.info(f"Loading {s3_key} from S3 Bucket {bucket} into {load_table}")
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
loaded = postgres.run(
dedent(
f"""
@@ -178,6 +193,7 @@ def clean_intermediate_table_data(
postgres_conn_id: str,
identifier: str,
media_type: MediaType = IMAGE,
+ task: AbstractOperator = None,
) -> tuple[int, int]:
"""
Clean the data in the intermediate table.
@@ -189,7 +205,10 @@ def clean_intermediate_table_data(
and `foreign_id`.
"""
load_table = _get_load_table_name(identifier, media_type=media_type)
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
missing_columns = 0
for column in required_columns:
@@ -247,6 +266,7 @@ def upsert_records_to_db_table(
db_table: str = None,
media_type: str = IMAGE,
tsv_version: str = CURRENT_TSV_VERSION,
+ task: AbstractOperator = None,
):
"""
Upsert newly ingested records from loading table into the main db table.
@@ -260,6 +280,7 @@ def upsert_records_to_db_table(
:param media_type
:param tsv_version: The version of TSV being processed. This
determines which columns are used in the upsert query.
+ :param task To be automagically passed by airflow.
:return:
"""
if db_table is None:
@@ -267,7 +288,10 @@ def upsert_records_to_db_table(
load_table = _get_load_table_name(identifier, media_type=media_type)
logger.info(f"Upserting new records into {db_table}.")
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
# Remove identifier column
db_columns: list[Column] = DB_COLUMNS[media_type][1:]
@@ -313,7 +337,9 @@ def drop_load_table(
media_type: str = IMAGE,
):
load_table = _get_load_table_name(identifier, media_type=media_type)
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id, default_statement_timeout=60
+ )
postgres.run(f"DROP TABLE IF EXISTS {load_table};")
@@ -345,8 +371,16 @@ def _delete_malformed_row_in_file(tsv_file_name, line_number):
write_obj.write(line)
-def expire_old_images(postgres_conn_id, provider, image_table=TABLE_NAMES[IMAGE]):
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+def expire_old_images(
+ postgres_conn_id,
+ provider,
+ image_table=TABLE_NAMES[IMAGE],
+ task: AbstractOperator = None,
+):
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
if provider not in OLDEST_PER_PROVIDER:
raise Exception(
diff --git a/openverse_catalog/dags/common/popularity/sql.py b/openverse_catalog/dags/common/popularity/sql.py
index 3b26322c5..2c3e04073 100644
--- a/openverse_catalog/dags/common/popularity/sql.py
+++ b/openverse_catalog/dags/common/popularity/sql.py
@@ -1,9 +1,11 @@
from collections import namedtuple
+from datetime import timedelta
from textwrap import dedent
-from airflow.providers.postgres.hooks.postgres import PostgresHook
+from airflow.models.abstractoperator import AbstractOperator
from common.constants import AUDIO, IMAGE
from common.loader.sql import TABLE_NAMES
+from common.sql import PostgresHook
from common.storage import columns as col
@@ -68,6 +70,7 @@ def drop_media_popularity_relations(
db_view=IMAGE_VIEW_NAME,
constants=IMAGE_POPULARITY_CONSTANTS_VIEW,
metrics=IMAGE_POPULARITY_METRICS_TABLE_NAME,
+ pg_timeout: float = timedelta(minutes=10).total_seconds(),
):
if media_type == AUDIO:
@@ -75,7 +78,9 @@ def drop_media_popularity_relations(
constants = AUDIO_POPULARITY_CONSTANTS_VIEW
metrics = AUDIO_POPULARITY_METRICS_TABLE_NAME
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id, default_statement_timeout=pg_timeout
+ )
drop_media_view = f"DROP MATERIALIZED VIEW IF EXISTS public.{db_view} CASCADE;"
drop_popularity_constants = (
f"DROP MATERIALIZED VIEW IF EXISTS public.{constants} CASCADE;"
@@ -95,7 +100,9 @@ def drop_media_popularity_functions(
if media_type == AUDIO:
popularity_percentile = AUDIO_POPULARITY_PERCENTILE_FUNCTION
standardized_popularity = STANDARDIZED_AUDIO_POPULARITY_FUNCTION
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id, default_statement_timeout=10.0
+ )
drop_standardized_popularity = (
f"DROP FUNCTION IF EXISTS public.{standardized_popularity} CASCADE;"
)
@@ -113,7 +120,9 @@ def create_media_popularity_metrics(
):
if media_type == AUDIO:
popularity_metrics_table = AUDIO_POPULARITY_METRICS_TABLE_NAME
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id, default_statement_timeout=10.0
+ )
popularity_metrics_columns_string = ",\n ".join(
f"{c.name} {c.definition}" for c in POPULARITY_METRICS_TABLE_COLUMNS
)
@@ -132,6 +141,7 @@ def update_media_popularity_metrics(
media_type=IMAGE,
popularity_metrics=None,
popularity_metrics_table=IMAGE_POPULARITY_METRICS_TABLE_NAME,
+ task: AbstractOperator = None,
):
if popularity_metrics is None:
if media_type == AUDIO:
@@ -140,7 +150,10 @@ def update_media_popularity_metrics(
popularity_metrics = IMAGE_POPULARITY_METRICS
if media_type == AUDIO:
popularity_metrics_table = AUDIO_POPULARITY_METRICS_TABLE_NAME
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
column_names = [c.name for c in POPULARITY_METRICS_TABLE_COLUMNS]
updates_string = ",\n ".join(
f"{c}=EXCLUDED.{c}" for c in column_names if c != PARTITION
@@ -192,7 +205,9 @@ def create_media_popularity_percentile_function(
popularity_percentile=IMAGE_POPULARITY_PERCENTILE_FUNCTION,
media_table=TABLE_NAMES[IMAGE],
):
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id, default_statement_timeout=10.0
+ )
if media_type == AUDIO:
popularity_percentile = AUDIO_POPULARITY_PERCENTILE_FUNCTION
media_table = TABLE_NAMES[AUDIO]
@@ -221,8 +236,11 @@ def create_media_popularity_constants_view(
popularity_constants_idx=IMAGE_POP_CONSTANTS_IDX,
popularity_metrics=IMAGE_POPULARITY_METRICS_TABLE_NAME,
popularity_percentile=IMAGE_POPULARITY_PERCENTILE_FUNCTION,
+ pg_timeout: float = timedelta(hours=6).total_seconds(),
):
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id, default_statement_timeout=pg_timeout
+ )
if media_type == AUDIO:
popularity_constants = AUDIO_POPULARITY_CONSTANTS_VIEW
popularity_constants_idx = AUDIO_POP_CONSTANTS_IDX
@@ -269,10 +287,14 @@ def update_media_popularity_constants(
postgres_conn_id,
media_type=IMAGE,
popularity_constants_view=IMAGE_POPULARITY_CONSTANTS_VIEW,
+ task: AbstractOperator = None,
):
if media_type == AUDIO:
popularity_constants_view = AUDIO_POPULARITY_CONSTANTS_VIEW
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
postgres.run(f"REFRESH MATERIALIZED VIEW CONCURRENTLY {popularity_constants_view};")
@@ -285,7 +307,9 @@ def create_standardized_media_popularity_function(
if media_type == AUDIO:
popularity_constants = AUDIO_POPULARITY_CONSTANTS_VIEW
function_name = STANDARDIZED_AUDIO_POPULARITY_FUNCTION
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id, default_statement_timeout=10.0
+ )
query = dedent(
f"""
CREATE OR REPLACE FUNCTION public.{function_name}(
@@ -343,6 +367,7 @@ def create_media_view(
db_view_name=IMAGE_VIEW_NAME,
db_view_id_idx=IMAGE_VIEW_ID_IDX,
db_view_provider_fid_idx=IMAGE_VIEW_PROVIDER_FID_IDX,
+ task: AbstractOperator = None,
):
if media_type == AUDIO:
table_name = TABLE_NAMES[AUDIO]
@@ -350,7 +375,10 @@ def create_media_view(
db_view_id_idx = AUDIO_VIEW_ID_IDX
db_view_provider_fid_idx = AUDIO_VIEW_PROVIDER_FID_IDX
standardized_popularity_func = STANDARDIZED_AUDIO_POPULARITY_FUNCTION
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
audio_set_id_str = (
"\naudio_set ->> 'foreign_identifier' AS audio_set_foreign_identifier,"
)
@@ -382,11 +410,12 @@ def create_media_view(
def update_db_view(
- postgres_conn_id,
- media_type=IMAGE,
- db_view_name=IMAGE_VIEW_NAME,
+ postgres_conn_id, media_type=IMAGE, db_view_name=IMAGE_VIEW_NAME, task=None
):
if media_type == AUDIO:
db_view_name = AUDIO_VIEW_NAME
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
postgres.run(f"REFRESH MATERIALIZED VIEW CONCURRENTLY {db_view_name};")
diff --git a/openverse_catalog/dags/common/sql.py b/openverse_catalog/dags/common/sql.py
new file mode 100644
index 000000000..cba305e8b
--- /dev/null
+++ b/openverse_catalog/dags/common/sql.py
@@ -0,0 +1,162 @@
+import logging
+from datetime import timedelta
+
+from airflow.models import BaseOperator
+from airflow.models.mappedoperator import MappedOperator
+from airflow.providers.common.sql.hooks.sql import fetch_one_handler
+from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator
+from airflow.providers.postgres.hooks.postgres import (
+ PostgresHook as UpstreamPostgresHook,
+)
+from common.constants import DAG_DEFAULT_ARGS, POSTGRES_CONN_ID
+
+
+# More on how Airflow timeouts work is in the docs here:
+# https://airflow.apache.org/docs/apache-airflow/2.5.1/core-concepts/tasks.html#timeouts
+# We set default task execution timeouts in common.constants.DAG_DEFAULT_ARGS
+# https://airflow.apache.org/docs/apache-airflow/2.5.1/core-concepts/dags.html#default-arguments
+# and for provider scripts, we set some timeouts in
+# dags.providers.provider_workflows.PROVIDER_WORKFLOWS
+
+logger = logging.getLogger(__name__)
+
+
+# Some functions, like inaturalist, use "copy_expert" to bulk load data to a table.
+# Right now, that is not using the timeout automagically.
+# https://airflow.apache.org/docs/apache-airflow-providers-postgres/stable/_api/airflow/providers/postgres/hooks/postgres/index.html#airflow.providers.postgres.hooks.postgres.PostgresHook.copy_expert # noqa
+
+
+class PostgresHook(UpstreamPostgresHook):
+ """
+ PostgresHook that sets the database timeout on any query to match the airflow task
+ execution timeout or a specific timeout for a particular run.
+
+ default_statement_timeout: number of seconds postgres should wait before canceling
+ the query (note: can override this by passing statement_timeout to the `run`
+ method, but other methods like `get_records` which rely on `run` are not set up
+ to pass an override timeout through to `run`. Not clear that it always works to
+ have a `statement_timeout` that is longer than the airflow task
+ `execution_timeout`.)
+ see airflow.providers.postgres.hooks.postgres.PostgresHook for more on other params
+ """
+
+ def __init__(
+ self,
+ postgres_conn_id: str = POSTGRES_CONN_ID,
+ default_statement_timeout: float = None,
+ *args,
+ **kwargs,
+ ) -> None:
+ self.default_statement_timeout = default_statement_timeout
+ if default_statement_timeout is None:
+ self.default_statement_timeout = DAG_DEFAULT_ARGS[
+ "execution_timeout"
+ ].total_seconds()
+ self.postgres_conn_id = postgres_conn_id
+ if postgres_conn_id is None:
+ self.postgres_conn_id = POSTGRES_CONN_ID
+ super().__init__(self.postgres_conn_id, *args, **kwargs)
+
+ def run(
+ self,
+ sql,
+ statement_timeout: float = None,
+ autocommit=False,
+ parameters=None,
+ handler: callable = fetch_one_handler,
+ *args,
+ **kwargs,
+ ):
+ statement_timeout = statement_timeout or self.default_statement_timeout
+
+ if statement_timeout:
+ timeout_sql = self.get_pg_timeout_sql(statement_timeout)
+ if isinstance(sql, list):
+ sql = [timeout_sql, *sql]
+ else:
+ sql = f"{timeout_sql} {sql}"
+ return super().run(sql, autocommit, parameters, handler)
+
+ @staticmethod
+ def get_execution_timeout(task: BaseOperator | MappedOperator = None) -> float:
+ """
+ Pull execution timeout from airflow task and format it for the hook, i.e.
+ number of seconds. Use the task execution timeout, if available. If not, take
+ the DAG execution timeout, if that's not available, return 0 for no timeout.
+
+ If the task falls through the cracks between functions and 'None' is passed
+ instead, return the common.constants dag default task timeout, and note the
+ decision in the log.
+ """
+ universal_default = DAG_DEFAULT_ARGS["execution_timeout"].total_seconds()
+ if task is None:
+ logger.warning(
+ f"No task supplied, using default timeout of {universal_default}s"
+ )
+ return universal_default
+
+ # DAG-level default task execution timeout, which may come from
+ # common.constants.DAG_DEFAULT_ARGS["execution_timeout"]
+ # or by over-ridden for a specific DAG as in image expiration.
+ # https://github.com/WordPress/openverse-catalog/blob/main/openverse_catalog/dags/database/image_expiration_workflow.py#L24
+ dag_default_timeout = getattr(task.dag, "default_args", {}).get(
+ "execution_timeout"
+ )
+
+ # explicitly specified with the task
+ if isinstance(task, BaseOperator):
+ task_timeout = task._BaseOperator__init_kwargs.get("execution_timeout")
+ elif isinstance(task, MappedOperator):
+ task_timeout = task.partial_kwargs.get("execution_timeout")
+ else:
+ task_timeout = None
+
+ # Prefer the most immediately specified. Here "None" means not specified and
+ # results in the universal default timeout, while timedelta(seconds=0) which is
+ # not None but also falsey means "Set no timeout at all."
+ if task_timeout is not None:
+ return task_timeout.total_seconds()
+ elif dag_default_timeout is not None:
+ return dag_default_timeout.total_seconds()
+ else:
+ return universal_default
+
+ @staticmethod
+ def get_pg_timeout_sql(statement_timeout: float) -> str:
+ return f"SET statement_timeout TO '{statement_timeout}s';"
+
+ def run_statement_timeout(self):
+ """
+ Pass an empty SQL statement to the regular run command so that only the
+ timeout setting gets run.
+ """
+ self.run("")
+
+
+class PGExecuteQueryOperator(SQLExecuteQueryOperator):
+ """
+ SQL Operator that sets the database statement timeout to match the airflow task
+ execution timeout. execution_timeout is a standard Airflow parameter that should be
+ in the form of `datetime.timedelta`. See SQLExecuteQueryOperator for more on other
+ params.
+ """
+
+ def __init__(
+ self,
+ *,
+ postgres_conn_id: str = None,
+ execution_timeout: timedelta = None,
+ **kwargs,
+ ) -> None:
+ self.statement_timeout = None
+ if execution_timeout:
+ self.statement_timeout = execution_timeout.total_seconds()
+ self.postgres_conn_id = postgres_conn_id or kwargs.get("conn_id")
+ super().__init__(**kwargs)
+
+ def get_db_hook(self):
+ return PostgresHook(
+ default_statement_timeout=self.statement_timeout,
+ postgres_conn_id=self.postgres_conn_id,
+ **self.hook_params,
+ )
diff --git a/openverse_catalog/dags/data_refresh/dag_factory.py b/openverse_catalog/dags/data_refresh/dag_factory.py
index 9a4479fed..836f0e9b6 100644
--- a/openverse_catalog/dags/data_refresh/dag_factory.py
+++ b/openverse_catalog/dags/data_refresh/dag_factory.py
@@ -37,7 +37,6 @@ from collections.abc import Sequence
from airflow import DAG
from airflow.models.dagrun import DagRun
from airflow.operators.python import BranchPythonOperator, PythonOperator
-from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator
from airflow.settings import SASession
from airflow.utils.session import provide_session
from airflow.utils.state import State
@@ -46,6 +45,7 @@ from common.constants import (
OPENLEDGER_API_CONN_ID,
XCOM_PULL_TEMPLATE,
)
+from common.sql import PGExecuteQueryOperator
from data_refresh.data_refresh_task_factory import create_data_refresh_task_group
from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefresh
from data_refresh.refresh_popularity_metrics_task_factory import (
@@ -210,7 +210,7 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc
)
# Get the current number of records in the target API table
- before_record_count = SQLExecuteQueryOperator(
+ before_record_count = PGExecuteQueryOperator(
task_id="get_before_record_count",
conn_id=OPENLEDGER_API_CONN_ID,
sql=count_sql,
@@ -236,7 +236,7 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc
)
# Get the final number of records in the API table after the refresh
- after_record_count = SQLExecuteQueryOperator(
+ after_record_count = PGExecuteQueryOperator(
task_id="get_after_record_count",
conn_id=OPENLEDGER_API_CONN_ID,
sql=count_sql,
diff --git a/openverse_catalog/dags/data_refresh/data_refresh_types.py b/openverse_catalog/dags/data_refresh/data_refresh_types.py
index e2755f45c..40876dd22 100644
--- a/openverse_catalog/dags/data_refresh/data_refresh_types.py
+++ b/openverse_catalog/dags/data_refresh/data_refresh_types.py
@@ -28,7 +28,9 @@ class DataRefresh:
should be run. Passed to the
airflow.dag.DAG __init__ method.
data_refresh_timeout: int giving the amount of time in seconds a
- given data pull may take.
+ given data pull may take. int rather than
+ than timedelta because it is used by HttpSensor
+ for scheduling, rather than PG for running tasks.
refresh_metrics_timeout: timedelta expressing amount of time the
refresh popularity metrics tasks may take.
refresh_matview_timeout: timedelta expressing amount of time the
diff --git a/openverse_catalog/dags/data_refresh/refresh_popularity_metrics_task_factory.py b/openverse_catalog/dags/data_refresh/refresh_popularity_metrics_task_factory.py
index 3b071da8a..7247f9bf4 100644
--- a/openverse_catalog/dags/data_refresh/refresh_popularity_metrics_task_factory.py
+++ b/openverse_catalog/dags/data_refresh/refresh_popularity_metrics_task_factory.py
@@ -41,7 +41,10 @@ def create_refresh_popularity_metrics_task_group(data_refresh: DataRefresh):
update_metrics = PythonOperator(
task_id=UPDATE_MEDIA_POPULARITY_METRICS_TASK_ID,
python_callable=sql.update_media_popularity_metrics,
- op_args=[POSTGRES_CONN_ID, media_type],
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
execution_timeout=execution_timeout,
doc=(
"Updates the popularity metrics table, adding any new "
@@ -63,7 +66,10 @@ def create_refresh_popularity_metrics_task_group(data_refresh: DataRefresh):
update_constants = PythonOperator(
task_id=UPDATE_MEDIA_POPULARITY_CONSTANTS_TASK_ID,
python_callable=sql.update_media_popularity_constants,
- op_args=[POSTGRES_CONN_ID, media_type],
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
execution_timeout=execution_timeout,
doc=(
"Updates the popularity constants view. This completely "
diff --git a/openverse_catalog/dags/data_refresh/refresh_view_data_task_factory.py b/openverse_catalog/dags/data_refresh/refresh_view_data_task_factory.py
index 49cf83a8b..4fe501ead 100644
--- a/openverse_catalog/dags/data_refresh/refresh_view_data_task_factory.py
+++ b/openverse_catalog/dags/data_refresh/refresh_view_data_task_factory.py
@@ -38,7 +38,10 @@ def create_refresh_view_data_task(data_refresh: DataRefresh):
refresh_matview = PythonOperator(
task_id=UPDATE_DB_VIEW_TASK_ID,
python_callable=sql.update_db_view,
- op_args=[POSTGRES_CONN_ID, data_refresh.media_type],
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": data_refresh.media_type,
+ },
execution_timeout=data_refresh.refresh_matview_timeout,
trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS,
doc_md=create_refresh_view_data_task.__doc__,
diff --git a/openverse_catalog/dags/database/image_expiration_workflow.py b/openverse_catalog/dags/database/image_expiration_workflow.py
index d9fde4de7..14f941c11 100644
--- a/openverse_catalog/dags/database/image_expiration_workflow.py
+++ b/openverse_catalog/dags/database/image_expiration_workflow.py
@@ -21,7 +21,9 @@ dag = DAG(
default_args={
**DAG_DEFAULT_ARGS,
"retry_delay": timedelta(seconds=15),
- "execution_timeout": None,
+ "execution_timeout": timedelta(
+ seconds=0
+ ), # Let these tasks run with no timeout
},
max_active_tasks=MAX_ACTIVE_TASKS,
max_active_runs=MAX_ACTIVE_TASKS,
diff --git a/openverse_catalog/dags/database/report_pending_reported_media.py b/openverse_catalog/dags/database/report_pending_reported_media.py
index 7a34332fb..e0534d95f 100644
--- a/openverse_catalog/dags/database/report_pending_reported_media.py
+++ b/openverse_catalog/dags/database/report_pending_reported_media.py
@@ -16,9 +16,8 @@ from urllib.parse import urljoin
from airflow import DAG
from airflow.exceptions import AirflowException
-from airflow.models import TaskInstance
+from airflow.models import BaseOperator, TaskInstance
from airflow.operators.python import PythonOperator
-from airflow.providers.postgres.hooks.postgres import PostgresHook
from common import slack
from common.constants import (
DAG_DEFAULT_ARGS,
@@ -26,6 +25,7 @@ from common.constants import (
OPENLEDGER_API_CONN_ID,
XCOM_PULL_TEMPLATE,
)
+from common.sql import PostgresHook
logger = logging.getLogger(__name__)
@@ -48,7 +48,7 @@ MediaTypeReportCounts = dict[str, ReportCountsByReason]
def get_pending_report_counts(
- db_conn_id: str, media_type: str, ti: TaskInstance
+ db_conn_id: str, media_type: str, ti: TaskInstance, task: BaseOperator
) -> ReportCountsByReason:
"""
Build a dict of pending report counts grouped by report reason for a media type.
@@ -59,7 +59,10 @@ def get_pending_report_counts(
media_type: Media type for which to look up reports
ti: Running task instance
"""
- postgres = PostgresHook(postgres_conn_id=db_conn_id)
+ postgres = PostgresHook(
+ postgres_conn_id=db_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
report_counts_by_reason = {}
if media_type not in REPORTS_TABLES:
diff --git a/openverse_catalog/dags/providers/provider_api_scripts/inaturalist.py b/openverse_catalog/dags/providers/provider_api_scripts/inaturalist.py
index 1cef8abc9..e94d282d9 100644
--- a/openverse_catalog/dags/providers/provider_api_scripts/inaturalist.py
+++ b/openverse_catalog/dags/providers/provider_api_scripts/inaturalist.py
@@ -27,14 +27,14 @@ import pendulum
import requests
from airflow import XComArg
from airflow.exceptions import AirflowNotFoundException, AirflowSkipException
+from airflow.models.abstractoperator import AbstractOperator
from airflow.operators.python import PythonOperator, ShortCircuitOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
-from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator
-from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.utils.task_group import TaskGroup
from airflow.utils.trigger_rule import TriggerRule
from common.constants import IMAGE, POSTGRES_CONN_ID, XCOM_PULL_TEMPLATE
from common.loader import provider_details, reporting, sql
+from common.sql import PGExecuteQueryOperator, PostgresHook
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
@@ -81,9 +81,12 @@ class INaturalistDataIngester(ProviderDataIngester):
@staticmethod
def get_batches(
batch_length: int, # must be a positive, non-zero integer
- postgres_conn_id=POSTGRES_CONN_ID,
+ task: AbstractOperator,
):
- pg = PostgresHook(postgres_conn_id)
+ pg = PostgresHook(
+ postgres_conn_id=POSTGRES_CONN_ID,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
max_id = pg.get_records("SELECT max(photo_id) FROM inaturalist.photos")[0][0]
if max_id is None:
# This would only happen if there were no data loaded to inaturalist.photos
@@ -100,7 +103,7 @@ class INaturalistDataIngester(ProviderDataIngester):
batch: tuple[int, int],
intermediate_table: str,
identifier: str,
- postgres_conn_id=POSTGRES_CONN_ID,
+ task: AbstractOperator,
sql_template_file_name="transformed_table.template.sql",
):
"""
@@ -110,7 +113,10 @@ class INaturalistDataIngester(ProviderDataIngester):
"""
start_time = time.perf_counter()
(batch_start, batch_end) = batch
- pg = PostgresHook(postgres_conn_id)
+ pg = PostgresHook(
+ postgres_conn_id=POSTGRES_CONN_ID,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
sql_template = (SCRIPT_DIR / sql_template_file_name).read_text()
batch_number = int(batch_start / (batch_end - batch_start + 1)) + 1
logger.info(f"Starting at photo_id {batch_start}, on batch {batch_number}.")
@@ -128,15 +134,13 @@ class INaturalistDataIngester(ProviderDataIngester):
)
# Run standard cleaning
(missing_columns, foreign_id_dup) = sql.clean_intermediate_table_data(
- identifier=identifier,
- postgres_conn_id=postgres_conn_id,
+ postgres_conn_id=POSTGRES_CONN_ID, identifier=identifier, task=task
)
# Add transformed records to the target catalog image table.
# TO DO: Would it be better to use loader.upsert_records here? Would need to
# trace back the parameters that need to be passed in for different stats.
upserted_records = sql.upsert_records_to_db_table(
- identifier=identifier,
- postgres_conn_id=postgres_conn_id,
+ postgres_conn_id=POSTGRES_CONN_ID, identifier=identifier, task=task
)
logger.info(f"Upserted {upserted_records} records, from batch {batch_number}.")
# Truncate the temp table
@@ -201,7 +205,7 @@ class INaturalistDataIngester(ProviderDataIngester):
raise AirflowSkipException("Nothing new to ingest")
@staticmethod
- def load_catalog_of_life_names(remove_api_files: bool):
+ def load_catalog_of_life_names(task: PythonOperator, remove_api_files: bool):
COL_URL = "https://api.checklistbank.org/dataset/9840/export.zip?format=ColDP"
local_zip_file = "COL_archive.zip"
name_usage_file = "NameUsage.tsv"
@@ -237,13 +241,16 @@ class INaturalistDataIngester(ProviderDataIngester):
f.write(z.read(vernacular_file))
logger.info(f"Extracted raw file: {OUTPUT_DIR}/{vernacular_file}")
# set up for loading data
- pg = PostgresHook(POSTGRES_CONN_ID)
+ pg = PostgresHook(
+ default_statement_timeout=PostgresHook.get_execution_timeout(task)
+ )
COPY_SQL = (
"COPY inaturalist.{} FROM STDIN "
"DELIMITER E'\t' CSV HEADER QUOTE E'\b' NULL AS ''"
)
COUNT_SQL = "SELECT count(*) FROM inaturalist.{};"
# upload vernacular names file to postgres
+ pg.run_statement_timeout()
pg.copy_expert(COPY_SQL.format("col_vernacular"), OUTPUT_DIR / vernacular_file)
vernacular_records = pg.get_records(COUNT_SQL.format("col_vernacular"))
if vernacular_records[0][0] == 0:
@@ -288,11 +295,11 @@ class INaturalistDataIngester(ProviderDataIngester):
doc_md="Check for iNaturalist files added to S3 since last load",
)
- create_inaturalist_schema = SQLExecuteQueryOperator(
+ create_inaturalist_schema = PGExecuteQueryOperator(
task_id="create_inaturalist_schema",
- conn_id=POSTGRES_CONN_ID,
sql=(SCRIPT_DIR / "create_schema.sql").read_text(),
doc_md="Create temporary schema and license table",
+ execution_timeout=timedelta(minutes=1),
)
load_catalog_of_life_names = PythonOperator(
@@ -302,6 +309,7 @@ class INaturalistDataIngester(ProviderDataIngester):
op_kwargs={
"remove_api_files": "{{params.sql_rm_source_data_after_ingesting}}"
},
+ execution_timeout=timedelta(minutes=15),
)
(
@@ -324,17 +332,18 @@ class INaturalistDataIngester(ProviderDataIngester):
# just skip the drop steps, not the final reporting step in the dag
ignore_downstream_trigger_rules=False,
)
- drop_inaturalist_schema = SQLExecuteQueryOperator(
+ drop_inaturalist_schema = PGExecuteQueryOperator(
task_id="drop_inaturalist_schema",
- conn_id=POSTGRES_CONN_ID,
sql="DROP SCHEMA IF EXISTS inaturalist CASCADE",
doc_md="Drop iNaturalist source tables and their schema",
+ execution_timeout=timedelta(minutes=10),
)
drop_loading_table = PythonOperator(
task_id="drop_loading_table",
python_callable=sql.drop_load_table,
op_kwargs=LOADER_ARGS,
doc_md="Drop the temporary (transformed) loading table",
+ execution_timeout=timedelta(minutes=10),
)
(check_drop_parameter >> [drop_inaturalist_schema, drop_loading_table])
return postingestion_tasks
@@ -348,11 +357,11 @@ class INaturalistDataIngester(ProviderDataIngester):
with TaskGroup(group_id="pull_image_data") as pull_data:
for source_name in SOURCE_FILE_NAMES:
- SQLExecuteQueryOperator(
+ PGExecuteQueryOperator(
task_id=f"load_{source_name}",
- conn_id=POSTGRES_CONN_ID,
sql=(SCRIPT_DIR / f"{source_name}.sql").read_text(),
doc_md=f"Load iNaturalist {source_name} from s3 to postgres",
+ execution_timeout=timedelta(minutes=10),
),
with TaskGroup(group_id="load_image_data") as loader_tasks:
@@ -367,6 +376,7 @@ class INaturalistDataIngester(ProviderDataIngester):
"Create a temp table for ingesting data from inaturalist "
"source tables."
),
+ execution_timeout=timedelta(minutes=1),
)
get_batches = PythonOperator(
@@ -374,17 +384,16 @@ class INaturalistDataIngester(ProviderDataIngester):
python_callable=INaturalistDataIngester.get_batches,
op_kwargs={
"batch_length": 2_000_000,
- "postgres_conn_id": LOADER_ARGS["postgres_conn_id"],
},
+ execution_timeout=timedelta(minutes=1),
)
+ # In testing this locally, the longest full iteration took 39 minutes,
+ # median was 18 minutes. We should probably adjust the timeouts with
+ # more info from production runs.
load_transformed_data = PythonOperator.partial(
task_id="load_transformed_data",
python_callable=INaturalistDataIngester.load_transformed_data,
- # In testing this locally, the longest iteration took 39 minutes,
- # median was 18 minutes. We should probably adjust the timeouts with
- # more info from production runs.
- execution_timeout=timedelta(hours=1),
retries=0,
max_active_tis_per_dag=1,
op_kwargs={
@@ -397,7 +406,7 @@ class INaturalistDataIngester(ProviderDataIngester):
"Load one batch of data from source tables to target table."
),
).expand(
- op_args=XComArg(get_batches),
+ op_args=XComArg(get_batches, "return_value"),
)
consolidate_load_statistics = PythonOperator(
diff --git a/pytest.ini b/pytest.ini
index 8b92f0abe..878bfa250 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -20,5 +20,16 @@ addopts =
# sqlalchemy
# Warning in dependency, nothing we can do
# https://docs.sqlalchemy.org/en/20/errors.html#error-b8d9
+# airflow
+# Warning within Airflow for an internal call, nothing we can do
+# flask
+# https://docs.sqlalchemy.org/en/20/errors.html#error-b8d9
+# Warning in dependency, nothing we can do
+# "removed"/"remoevd" is due to https://github.com/pallets/flask
+# distutils
+# Warning in dependency, nothing we can do
filterwarnings=
- ignore:.*Deprecated API features detected.*:sqlalchemy.exc.MovedIn20Warning
+ ignore::sqlalchemy.exc.MovedIn20Warning
+ ignore:Calling `DAG.create_dagrun\(\)` without an explicit data interval is deprecated:airflow.exceptions.RemovedInAirflow3Warning
+ ignore:.*is deprecated and will be (remoevd|removed) in Flask 2.3.:DeprecationWarning
+ ignore:distutils Version classes are deprecated. Use packaging.version instead:DeprecationWarning
diff --git a/tests/dags/common/conftest.py b/tests/dags/common/conftest.py
index a5ae2b732..1bbbf8775 100644
--- a/tests/dags/common/conftest.py
+++ b/tests/dags/common/conftest.py
@@ -1,8 +1,14 @@
import socket
+from datetime import datetime, timedelta
from urllib.parse import urlparse
import boto3
import pytest
+from airflow import DAG
+from airflow.models.abstractoperator import AbstractOperator
+from airflow.operators.python import PythonOperator
+from common.constants import POSTGRES_CONN_ID
+from common.sql import PGExecuteQueryOperator, PostgresHook
from tests.dags.common.loader.test_s3 import ACCESS_KEY, S3_LOCAL_ENDPOINT, SECRET_KEY
@@ -54,3 +60,77 @@ def identifier(request):
def image_table(identifier):
# Parallelized tests need to use distinct database tables
return f"image_{identifier}"
+
+
+TEST_SQL = "SELECT PG_SLEEP(1);"
+
+
+def timed_pg_hook_sleeper(
+ task,
+ statement_timeout: float = None,
+):
+ pg = PostgresHook(
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ conn_id=POSTGRES_CONN_ID,
+ )
+ pg.run(sql=TEST_SQL, statement_timeout=statement_timeout)
+
+
+def mapped_select_pg_hook(
+ select_val: int,
+ task: AbstractOperator,
+):
+ pg = PostgresHook(
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ conn_id=POSTGRES_CONN_ID,
+ )
+ return pg.run(f"select {select_val};")
+
+
+def create_pg_timeout_tester_dag():
+ with DAG(
+ dag_id="a_pg_timeout_tester",
+ schedule=None,
+ doc_md="DAG to test query timeouts in postgres",
+ start_date=datetime(2023, 1, 1),
+ ) as dag:
+ pg_operator_happy = PGExecuteQueryOperator(
+ task_id="pg_operator_happy",
+ retries=0,
+ conn_id=POSTGRES_CONN_ID,
+ sql=TEST_SQL,
+ execution_timeout=timedelta(seconds=2),
+ doc_md="Custom PG operator, with query finished before execution timeout",
+ )
+ pg_hook_happy = PythonOperator(
+ task_id="pg_hook_happy",
+ retries=0,
+ python_callable=timed_pg_hook_sleeper,
+ execution_timeout=timedelta(hours=2),
+ doc_md="Custom PG hook, with query finished before execution timeout",
+ )
+ pg_hook_no_timeout = PythonOperator(
+ task_id="pg_hook_no_timeout",
+ retries=0,
+ python_callable=timed_pg_hook_sleeper,
+ doc_md="Custom PG hook, with no execution timeout",
+ )
+ pg_operator_mapped = PythonOperator.partial(
+ task_id="pg_operator_mapped",
+ retries=0,
+ execution_timeout=timedelta(minutes=1),
+ doc_md="Custom PG operator, mapped to list",
+ python_callable=mapped_select_pg_hook,
+ ).expand(op_args=[(1,), (2,)])
+ [pg_operator_happy, pg_hook_happy, pg_hook_no_timeout, pg_operator_mapped]
+ return dag
+
+
[email protected](scope="session")
+def mock_timeout_dag():
+ return create_pg_timeout_tester_dag()
+
+
[email protected](scope="session")
+def mock_pg_hook_task(mock_timeout_dag) -> PythonOperator:
+ return mock_timeout_dag.get_task("pg_hook_happy")
diff --git a/tests/dags/common/loader/test_loader.py b/tests/dags/common/loader/test_loader.py
index b731bd55b..6419625b1 100644
--- a/tests/dags/common/loader/test_loader.py
+++ b/tests/dags/common/loader/test_loader.py
@@ -13,12 +13,20 @@ from common.loader.reporting import RecordMetrics
(100, (10, 0), 75, RecordMetrics(75, 10, 0, 15)),
],
)
-def test_upsert_data_calculations(load_value, clean_data_value, upsert_value, expected):
+def test_upsert_data_calculations(
+ load_value, clean_data_value, upsert_value, expected, mock_pg_hook_task
+):
with mock.patch("common.loader.loader.sql") as sql_mock:
sql_mock.clean_intermediate_table_data.return_value = clean_data_value
sql_mock.upsert_records_to_db_table.return_value = upsert_value
actual = loader.upsert_data(
- mock.Mock(), "fake", "fake", "fake", load_value, clean_data_value
+ postgres_conn_id=mock.Mock(),
+ media_type="fake",
+ tsv_version="fake",
+ identifier="fake",
+ loaded_count=load_value,
+ duplicates_count=clean_data_value,
+ task=mock_pg_hook_task,
)
assert actual == expected
diff --git a/tests/dags/common/loader/test_sql.py b/tests/dags/common/loader/test_sql.py
index 817a1ff04..6a8387bf4 100644
--- a/tests/dags/common/loader/test_sql.py
+++ b/tests/dags/common/loader/test_sql.py
@@ -160,7 +160,7 @@ def postgres_with_load_and_image_table(load_table, image_table):
conn.close()
-def _load_local_tsv(tmpdir, bucket, tsv_file_name, identifier):
+def _load_local_tsv(tmpdir, bucket, tsv_file_name, identifier, mock_pg_hook_task):
"""
This wraps sql.load_local_data_to_intermediate_table so we can test it
under various conditions.
@@ -173,19 +173,30 @@ def _load_local_tsv(tmpdir, bucket, tsv_file_name, identifier):
path = tmpdir.join(test_tsv)
path.write(f_data)
- sql.load_local_data_to_intermediate_table(POSTGRES_CONN_ID, str(path), identifier)
+ sql.load_local_data_to_intermediate_table(
+ postgres_conn_id=POSTGRES_CONN_ID,
+ tsv_file_name=str(path),
+ identifier=identifier,
+ task=mock_pg_hook_task,
+ )
-def _load_s3_tsv(tmpdir, bucket, tsv_file_name, identifier):
+def _load_s3_tsv(tmpdir, bucket, tsv_file_name, identifier, mock_pg_hook_task):
tsv_file_path = os.path.join(RESOURCES, tsv_file_name)
key = f"path/to/object/{tsv_file_name}"
bucket.upload_file(tsv_file_path, key)
sql.load_s3_data_to_intermediate_table(
- POSTGRES_CONN_ID, bucket.name, key, identifier
+ postgres_conn_id=POSTGRES_CONN_ID,
+ bucket=bucket.name,
+ s3_key=key,
+ identifier=identifier,
+ task=mock_pg_hook_task,
)
-def test_create_loading_table_creates_table(postgres, load_table, identifier):
+def test_create_loading_table_creates_table(
+ postgres, load_table, identifier, mock_pg_hook_task
+):
postgres_conn_id = POSTGRES_CONN_ID
sql.create_loading_table(postgres_conn_id, identifier)
@@ -213,8 +224,11 @@ def test_loaders_load_good_tsv(
load_function,
load_table,
identifier,
+ mock_pg_hook_task,
):
- load_function(tmpdir, empty_s3_bucket, "none_missing.tsv", identifier)
+ load_function(
+ tmpdir, empty_s3_bucket, "none_missing.tsv", identifier, mock_pg_hook_task
+ )
check_query = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(check_query)
num_rows = postgres_with_load_table.cursor.fetchone()[0]
@@ -229,9 +243,14 @@ def test_delete_less_than_max_malformed_rows(
load_function,
load_table,
identifier,
+ mock_pg_hook_task,
):
load_function(
- tmpdir, empty_s3_bucket, "malformed_less_than_max_rows.tsv", identifier
+ tmpdir,
+ empty_s3_bucket,
+ "malformed_less_than_max_rows.tsv",
+ identifier,
+ mock_pg_hook_task,
)
check_query = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(check_query)
@@ -247,8 +266,11 @@ def test_delete_max_malformed_rows(
load_function,
load_table,
identifier,
+ mock_pg_hook_task,
):
- load_function(tmpdir, empty_s3_bucket, "malformed_max_rows.tsv", identifier)
+ load_function(
+ tmpdir, empty_s3_bucket, "malformed_max_rows.tsv", identifier, mock_pg_hook_task
+ )
check_query = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(check_query)
num_rows = postgres_with_load_table.cursor.fetchone()[0]
@@ -257,11 +279,20 @@ def test_delete_max_malformed_rows(
@pytest.mark.parametrize("load_function", [_load_local_tsv])
def test_delete_more_than_max_malformed_rows(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function, identifier
+ postgres_with_load_table,
+ tmpdir,
+ empty_s3_bucket,
+ load_function,
+ identifier,
+ mock_pg_hook_task,
):
with pytest.raises(InvalidTextRepresentation):
load_function(
- tmpdir, empty_s3_bucket, "malformed_more_than_max_rows.tsv", identifier
+ tmpdir,
+ empty_s3_bucket,
+ "malformed_more_than_max_rows.tsv",
+ identifier,
+ mock_pg_hook_task,
)
@@ -274,11 +305,16 @@ def test_loaders_deletes_null_url_rows(
load_function,
load_table,
identifier,
+ mock_pg_hook_task,
):
# Load test data with some null urls into the intermediate table
- load_function(tmpdir, empty_s3_bucket, "url_missing.tsv", identifier)
+ load_function(
+ tmpdir, empty_s3_bucket, "url_missing.tsv", identifier, mock_pg_hook_task
+ )
# Clean data
- sql.clean_intermediate_table_data(POSTGRES_CONN_ID, identifier)
+ sql.clean_intermediate_table_data(
+ POSTGRES_CONN_ID, identifier, task=mock_pg_hook_task
+ )
# Check that rows with null urls were deleted
null_url_check = f"SELECT COUNT (*) FROM {load_table} WHERE url IS NULL;"
@@ -301,11 +337,16 @@ def test_loaders_delete_null_license_rows(
load_function,
load_table,
identifier,
+ mock_pg_hook_task,
):
# Load test data with some null licenses into the intermediate table
- load_function(tmpdir, empty_s3_bucket, "license_missing.tsv", identifier)
+ load_function(
+ tmpdir, empty_s3_bucket, "license_missing.tsv", identifier, mock_pg_hook_task
+ )
# Clean data
- sql.clean_intermediate_table_data(POSTGRES_CONN_ID, identifier)
+ sql.clean_intermediate_table_data(
+ POSTGRES_CONN_ID, identifier, task=mock_pg_hook_task
+ )
# Check that rows with null licenses were deleted
license_check = f"SELECT COUNT (*) FROM {load_table} WHERE license IS NULL;"
@@ -328,13 +369,20 @@ def test_loaders_delete_null_foreign_landing_url_rows(
load_function,
load_table,
identifier,
+ mock_pg_hook_task,
):
# Load test data with null foreign landings url into the intermediate table
load_function(
- tmpdir, empty_s3_bucket, "foreign_landing_url_missing.tsv", identifier
+ tmpdir,
+ empty_s3_bucket,
+ "foreign_landing_url_missing.tsv",
+ identifier,
+ mock_pg_hook_task,
)
# Clean data
- sql.clean_intermediate_table_data(POSTGRES_CONN_ID, identifier)
+ sql.clean_intermediate_table_data(
+ POSTGRES_CONN_ID, identifier, task=mock_pg_hook_task
+ )
# Check that rows with null foreign landing urls were deleted
foreign_landing_url_check = (
@@ -358,11 +406,20 @@ def test_data_loaders_delete_null_foreign_identifier_rows(
load_function,
load_table,
identifier,
+ mock_pg_hook_task,
):
# Load test data with null foreign identifiers into the intermediate table
- load_function(tmpdir, empty_s3_bucket, "foreign_identifier_missing.tsv", identifier)
+ load_function(
+ tmpdir,
+ empty_s3_bucket,
+ "foreign_identifier_missing.tsv",
+ identifier,
+ mock_pg_hook_task,
+ )
# Clean data
- sql.clean_intermediate_table_data(POSTGRES_CONN_ID, identifier)
+ sql.clean_intermediate_table_data(
+ POSTGRES_CONN_ID, identifier, task=mock_pg_hook_task
+ )
# Check that rows with null foreign identifiers were deleted
foreign_identifier_check = (
@@ -386,13 +443,20 @@ def test_import_data_deletes_duplicate_foreign_identifier_rows(
load_function,
load_table,
identifier,
+ mock_pg_hook_task,
):
# Load test data with duplicate foreign identifiers into the intermediate table
load_function(
- tmpdir, empty_s3_bucket, "foreign_identifier_duplicate.tsv", identifier
+ tmpdir,
+ empty_s3_bucket,
+ "foreign_identifier_duplicate.tsv",
+ identifier,
+ mock_pg_hook_task,
)
# Clean data
- sql.clean_intermediate_table_data(POSTGRES_CONN_ID, identifier)
+ sql.clean_intermediate_table_data(
+ POSTGRES_CONN_ID, identifier, task=mock_pg_hook_task
+ )
# Check that rows with duplicate foreign ids were deleted
foreign_id_duplicate_check = (
@@ -409,7 +473,12 @@ def test_import_data_deletes_duplicate_foreign_identifier_rows(
def test_upsert_records_inserts_one_record_to_empty_image_table(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -459,7 +528,9 @@ def test_upsert_records_inserts_one_record_to_empty_image_table(
);"""
postgres_with_load_and_image_table.cursor.execute(load_data_query)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
actual_row = actual_rows[0]
@@ -485,7 +556,12 @@ def test_upsert_records_inserts_one_record_to_empty_image_table(
def test_upsert_records_inserts_two_records_to_image_table(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -514,7 +590,9 @@ def test_upsert_records_inserts_two_records_to_image_table(
);"""
postgres_with_load_and_image_table.cursor.execute(load_data_query)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
assert actual_rows[0][fid_idx] == FID_A
@@ -522,7 +600,12 @@ def test_upsert_records_inserts_two_records_to_image_table(
def test_upsert_records_replaces_updated_on_and_last_synced_with_source(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -543,7 +626,9 @@ def test_upsert_records_replaces_updated_on_and_last_synced_with_source(
postgres_with_load_and_image_table.cursor.execute(load_data_query)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
original_row = postgres_with_load_and_image_table.cursor.fetchall()
logging.info(f"\n{len(original_row)}\nOriginal row: {original_row}\n")
@@ -555,7 +640,9 @@ def test_upsert_records_replaces_updated_on_and_last_synced_with_source(
)
time.sleep(1)
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
updated_result = postgres_with_load_and_image_table.cursor.fetchall()
logging.info(
@@ -571,7 +658,12 @@ def test_upsert_records_replaces_updated_on_and_last_synced_with_source(
def test_upsert_records_replaces_data(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -634,7 +726,9 @@ def test_upsert_records_replaces_data(
);"""
postgres_with_load_and_image_table.cursor.execute(load_data_query_a)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
query_values = create_query_values(
@@ -666,7 +760,9 @@ def test_upsert_records_replaces_data(
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(load_data_query_b)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
@@ -686,7 +782,12 @@ def test_upsert_records_replaces_data(
def test_upsert_records_does_not_replace_with_nulls(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -741,7 +842,9 @@ def test_upsert_records_does_not_replace_with_nulls(
);"""
postgres_with_load_and_image_table.cursor.execute(load_data_query_a)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
query_values_b = create_query_values(
@@ -763,7 +866,9 @@ def test_upsert_records_does_not_replace_with_nulls(
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(load_data_query_b)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
@@ -784,7 +889,12 @@ def test_upsert_records_does_not_replace_with_nulls(
def test_upsert_records_merges_meta_data(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -823,13 +933,17 @@ def test_upsert_records_merges_meta_data(
);"""
postgres_with_load_and_image_table.cursor.execute(load_data_query_a)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(load_data_query_b)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
@@ -841,7 +955,12 @@ def test_upsert_records_merges_meta_data(
def test_upsert_records_does_not_replace_with_null_values_in_meta_data(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -880,13 +999,17 @@ def test_upsert_records_does_not_replace_with_null_values_in_meta_data(
);"""
postgres_with_load_and_image_table.cursor.execute(load_data_query_a)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(load_data_query_b)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
@@ -900,7 +1023,12 @@ def test_upsert_records_does_not_replace_with_null_values_in_meta_data(
def test_upsert_records_merges_tags(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -946,13 +1074,17 @@ def test_upsert_records_merges_tags(
);"""
postgres_with_load_and_image_table.cursor.execute(load_data_query_a)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(load_data_query_b)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
@@ -970,7 +1102,12 @@ def test_upsert_records_merges_tags(
def test_upsert_records_does_not_replace_tags_with_null(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -1010,13 +1147,17 @@ def test_upsert_records_does_not_replace_tags_with_null(
);"""
postgres_with_load_and_image_table.cursor.execute(load_data_query_a)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(load_data_query_b)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
@@ -1033,7 +1174,12 @@ def test_upsert_records_does_not_replace_tags_with_null(
def test_upsert_records_replaces_null_tags(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -1072,13 +1218,17 @@ def test_upsert_records_replaces_null_tags(
postgres_with_load_and_image_table.cursor.execute(load_data_query_a)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(load_data_query_b)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
@@ -1096,7 +1246,12 @@ def test_upsert_records_replaces_null_tags(
def test_upsert_records_handles_duplicate_url_and_does_not_merge(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -1141,7 +1296,9 @@ def test_upsert_records_handles_duplicate_url_and_does_not_merge(
# the image table, and finally the loading table is cleared for the next DAG run.
postgres_with_load_and_image_table.cursor.execute(load_data_query_a)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
postgres_with_load_and_image_table.connection.commit()
@@ -1150,7 +1307,9 @@ def test_upsert_records_handles_duplicate_url_and_does_not_merge(
# attempt to upsert it into the image table which already contains A.
postgres_with_load_and_image_table.cursor.execute(load_data_query_b)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
# Now check the final state of the image table. If we get here, the duplicate key
@@ -1167,7 +1326,12 @@ def test_upsert_records_handles_duplicate_url_and_does_not_merge(
def test_upsert_records_handles_duplicate_urls_in_a_single_batch_and_does_not_merge(
- postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ tmpdir,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -1238,7 +1402,9 @@ def test_upsert_records_handles_duplicate_urls_in_a_single_batch_and_does_not_me
assert len(rows) == 3
# Now try upserting the records from the loading table to the final image table.
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
# Now check the final state of the image table. If we get here, the duplicate key
@@ -1266,7 +1432,11 @@ def test_drop_load_table_drops_table(postgres_with_load_table, load_table, ident
def test_image_expiration(
- postgres_with_load_and_image_table, load_table, image_table, identifier
+ postgres_with_load_and_image_table,
+ load_table,
+ image_table,
+ identifier,
+ mock_pg_hook_task,
):
postgres_conn_id = POSTGRES_CONN_ID
@@ -1305,7 +1475,9 @@ def test_image_expiration(
postgres_with_load_and_image_table.cursor.execute(insert_data_query)
postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, db_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
postgres_with_load_and_image_table.connection.commit()
@@ -1317,9 +1489,13 @@ def test_image_expiration(
postgres_with_load_and_image_table.connection.commit()
- sql.expire_old_images(postgres_conn_id, PROVIDER_A, image_table=image_table)
+ sql.expire_old_images(
+ postgres_conn_id, PROVIDER_A, image_table=image_table, task=mock_pg_hook_task
+ )
- sql.expire_old_images(postgres_conn_id, PROVIDER_B, image_table=image_table)
+ sql.expire_old_images(
+ postgres_conn_id, PROVIDER_B, image_table=image_table, task=mock_pg_hook_task
+ )
postgres_with_load_and_image_table.connection.commit()
diff --git a/tests/dags/common/popularity/test_sql.py b/tests/dags/common/popularity/test_sql.py
index 420a8bf75..239322d81 100644
--- a/tests/dags/common/popularity/test_sql.py
+++ b/tests/dags/common/popularity/test_sql.py
@@ -109,16 +109,17 @@ USING btree (provider, md5(foreign_identifier));
conn.close()
-def _set_up_popularity_metrics(metrics_dict, table_info):
+def _set_up_popularity_metrics(metrics_dict, table_info, mock_pg_hook_task):
conn_id = POSTGRES_CONN_ID
sql.create_media_popularity_metrics(
- conn_id,
+ postgres_conn_id=conn_id,
popularity_metrics_table=table_info.metrics,
)
sql.update_media_popularity_metrics(
- conn_id,
+ postgres_conn_id=conn_id,
popularity_metrics=metrics_dict,
popularity_metrics_table=table_info.metrics,
+ task=mock_pg_hook_task,
)
@@ -136,10 +137,11 @@ def _set_up_popularity_constants(
data_query,
metrics_dict,
table_info,
+ mock_pg_hook_task,
):
conn_id = POSTGRES_CONN_ID
_set_up_popularity_percentile_function(table_info)
- _set_up_popularity_metrics(metrics_dict, table_info)
+ _set_up_popularity_metrics(metrics_dict, table_info, mock_pg_hook_task)
pg.cursor.execute(data_query)
pg.connection.commit()
sql.create_media_popularity_constants_view(
@@ -156,6 +158,7 @@ def _set_up_std_popularity_func(
data_query,
metrics_dict,
table_info,
+ mock_pg_hook_task,
):
conn_id = POSTGRES_CONN_ID
_set_up_popularity_constants(
@@ -163,9 +166,11 @@ def _set_up_std_popularity_func(
data_query,
metrics_dict,
table_info,
+ mock_pg_hook_task,
)
sql.create_standardized_media_popularity_function(
conn_id,
+ mock_pg_hook_task,
function_name=table_info.standardized_popularity,
popularity_constants=table_info.constants,
)
@@ -176,9 +181,12 @@ def _set_up_image_view(
data_query,
metrics_dict,
table_info,
+ mock_pg_hook_task,
):
conn_id = POSTGRES_CONN_ID
- _set_up_std_popularity_func(pg, data_query, metrics_dict, table_info)
+ _set_up_std_popularity_func(
+ pg, data_query, metrics_dict, table_info, mock_pg_hook_task
+ )
sql.create_media_view(
conn_id,
standardized_popularity_func=table_info.standardized_popularity,
@@ -186,6 +194,7 @@ def _set_up_image_view(
db_view_name=table_info.image_view,
db_view_id_idx=table_info.image_view_idx,
db_view_provider_fid_idx=table_info.provider_fid_idx,
+ task=mock_pg_hook_task,
)
@@ -284,7 +293,7 @@ def test_popularity_percentile_function_nones_when_missing_type(
def test_constants_view_adds_values_and_constants(
- postgres_with_image_table, table_info
+ postgres_with_image_table, table_info, mock_pg_hook_task
):
data_query = dedent(
f"""
@@ -325,7 +334,7 @@ def test_constants_view_adds_values_and_constants(
"diff_provider": {"metric": "comments", "percentile": 0.8},
}
_set_up_popularity_constants(
- postgres_with_image_table, data_query, metrics, table_info
+ postgres_with_image_table, data_query, metrics, table_info, mock_pg_hook_task
)
check_query = f"SELECT * FROM {table_info.constants};"
@@ -340,7 +349,7 @@ def test_constants_view_adds_values_and_constants(
def test_constants_view_handles_zeros_and_missing(
- postgres_with_image_table, table_info
+ postgres_with_image_table, table_info, mock_pg_hook_task
):
data_query = dedent(
f"""
@@ -381,7 +390,7 @@ def test_constants_view_handles_zeros_and_missing(
"diff_provider": {"metric": "comments", "percentile": 0.8},
}
_set_up_popularity_constants(
- postgres_with_image_table, data_query, metrics, table_info
+ postgres_with_image_table, data_query, metrics, table_info, mock_pg_hook_task
)
check_query = f"SELECT * FROM {table_info.constants};"
@@ -396,7 +405,7 @@ def test_constants_view_handles_zeros_and_missing(
def test_standardized_popularity_function_calculates(
- postgres_with_image_table, table_info
+ postgres_with_image_table, table_info, mock_pg_hook_task
):
data_query = dedent(
f"""
@@ -426,7 +435,7 @@ def test_standardized_popularity_function_calculates(
"other_provider": {"metric": "likes", "percentile": 0.5},
}
_set_up_std_popularity_func(
- postgres_with_image_table, data_query, metrics, table_info
+ postgres_with_image_table, data_query, metrics, table_info, mock_pg_hook_task
)
check_query = f"SELECT * FROM {table_info.constants};"
postgres_with_image_table.cursor.execute(check_query)
@@ -459,7 +468,9 @@ def test_standardized_popularity_function_calculates(
assert actual_std_pop_val == expect_std_pop_val
-def test_image_view_calculates_std_pop(postgres_with_image_table, table_info):
+def test_image_view_calculates_std_pop(
+ postgres_with_image_table, table_info, mock_pg_hook_task
+):
data_query = dedent(
f"""
INSERT INTO {table_info.image} (
@@ -486,7 +497,9 @@ def test_image_view_calculates_std_pop(postgres_with_image_table, table_info):
"""
)
metrics = {"my_provider": {"metric": "views", "percentile": 0.5}}
- _set_up_image_view(postgres_with_image_table, data_query, metrics, table_info)
+ _set_up_image_view(
+ postgres_with_image_table, data_query, metrics, table_info, mock_pg_hook_task
+ )
check_query = dedent(
f"""
SELECT foreign_identifier, standardized_popularity
diff --git a/tests/dags/common/test_sql.py b/tests/dags/common/test_sql.py
new file mode 100644
index 000000000..4d2169d61
--- /dev/null
+++ b/tests/dags/common/test_sql.py
@@ -0,0 +1,184 @@
+import logging
+import os
+from datetime import datetime, timedelta
+
+import pytest
+from common.constants import DAG_DEFAULT_ARGS, POSTGRES_CONN_ID
+from common.sql import PGExecuteQueryOperator, PostgresHook
+from psycopg2.errors import QueryCanceled
+
+from tests.conftest import mark_extended
+
+
+logger = logging.getLogger(__name__)
+
+
+POSTGRES_TEST_CONN_ID = os.getenv("TEST_CONN_ID")
+DEFAULT_TIMEOUT = timedelta(hours=1).total_seconds()
+default_timeout_msg = (
+ f"DAG_DEFAULT_ARGS sets the default task execution timeout to "
+ f"{DAG_DEFAULT_ARGS['execution_timeout']}. Testing for {DEFAULT_TIMEOUT} seconds."
+)
+HAPPY_TIMEOUT_PARAMETERS = [
+ pytest.param("pg_operator_happy", 2.0, id="pg_operator_happy"),
+ pytest.param("pg_hook_happy", 7_200.0, id="pg_hook_happy"),
+ pytest.param("pg_hook_no_timeout", DEFAULT_TIMEOUT, id="pg_hook_no_timeout"),
+ pytest.param("pg_operator_mapped", 60.0, id="pg_operator_mapped"),
+]
+
+
+# PostgresHook works with or without explicit connection id, and with override conn id
+# Testing mainly for documentation purposes
+ "sql, timeout, expected_result",
+ [
+ pytest.param("select 1;", None, (1,), id="select_1_no_timeout"),
+ pytest.param(
+ ["select 1;", "select 2;"],
+ None,
+ [None, (1,), (2,)],
+ id="select_list_none_timeout",
+ ),
+ pytest.param(
+ ["select 1;", "select 2;"],
+ 0,
+ [None, (1,), (2,)],
+ id="select_list_zero_timeout",
+ ),
+ pytest.param("select 1;", 10, (1,), id="select_1_with_timeout"),
+ pytest.param(
+ ["select 1;", "select 2;"],
+ 10,
+ [None, (1,), (2,)],
+ id="select_list_with_timeout",
+ ),
+ ],
+)
+def test_PostgresHook_init_defaults(sql, timeout, expected_result):
+ pg = PostgresHook()
+ assert pg.postgres_conn_id == POSTGRES_CONN_ID
+ assert pg.default_statement_timeout == DEFAULT_TIMEOUT, default_timeout_msg
+ assert pg.run(sql=sql, statement_timeout=timeout) == expected_result
+
+
+def test_PostgresHook_conn_id_only_defaults():
+ pg = PostgresHook("gibberish")
+ assert pg.postgres_conn_id == "gibberish"
+ assert pg.default_statement_timeout == DEFAULT_TIMEOUT, default_timeout_msg
+
+
+ "conn_id, timeout, expected_results",
+ [
+ pytest.param(None, None, (POSTGRES_CONN_ID, DEFAULT_TIMEOUT), id="both_None"),
+ pytest.param(
+ "xyzqwerty", None, ("xyzqwerty", DEFAULT_TIMEOUT), id="override_connection"
+ ),
+ pytest.param(None, 60, (POSTGRES_CONN_ID, 60), id="override_timeout"),
+ pytest.param("xyzqwerty", 60, ("xyzqwerty", 60), id="override_both"),
+ ],
+)
+def test_PostgresHook_init_connection(conn_id, timeout, expected_results):
+ (expected_conn_id, expected_timeout) = expected_results
+ pg = PostgresHook(conn_id, timeout)
+ assert pg.postgres_conn_id == expected_conn_id
+ assert pg.default_statement_timeout == expected_timeout
+
+
+# PostgresHook gets the database to stop the query and raise an error if the query runs
+# too long.
+ "statement_timeout, default_timeout",
+ [
+ pytest.param(None, 1, id="default_timeout_only"),
+ pytest.param(1, None, id="statement_timeout_only"),
+ pytest.param(1, 30, id="statement_timeout_shorter"),
+ ],
+)
+def test_pgdb_raises_cancel_error(statement_timeout, default_timeout):
+ with pytest.raises(QueryCanceled):
+ hook = PostgresHook(
+ default_statement_timeout=default_timeout,
+ )
+ start_time = datetime.now()
+ hook.run("select pg_sleep(3600);", statement_timeout=statement_timeout)
+ end_time = datetime.now()
+ assert (end_time - start_time) < timedelta(seconds=2)
+
+
+# PostgresHook.get_execution_timeout returns the correct number of seconds.
+# Trusting Airflow controls on what the execution_timeout can be.
+# Accessing from the dag object itself independent of any run status.
[email protected]("task_id, expected_result", HAPPY_TIMEOUT_PARAMETERS)
+def test_PostgresHook_get_execution_timeout_happy_tasks(
+ mock_timeout_dag, task_id, expected_result
+):
+ task = mock_timeout_dag.get_task(task_id)
+ actual_result = PostgresHook.get_execution_timeout(task)
+ assert actual_result == expected_result
+
+
+def test_PostgresHook_get_execution_timeout_no_task(caplog):
+ actual_result = PostgresHook.get_execution_timeout(None)
+ assert len(caplog.records) == 1
+ assert caplog.records[0].levelname == "WARNING"
+ assert "No task supplied, using default timeout of 3600.0s" in caplog.text
+ assert actual_result == DEFAULT_TIMEOUT
+
+
+# PGExecuteQueryOperator passes the correct default timeout to the hook.
+ "execution_timeout, expected_result",
+ [
+ pytest.param(timedelta(seconds=2), 2.0, id="2s_timeout"),
+ pytest.param(timedelta(hours=2), 7_200, id="2h_timeout"),
+ pytest.param(None, DEFAULT_TIMEOUT, id="no_timeout"),
+ ],
+)
+def test_operator_passes_correct_timeout(execution_timeout, expected_result):
+ operator = PGExecuteQueryOperator(
+ task_id="test_task_id",
+ sql="SELECT NOW();",
+ execution_timeout=execution_timeout,
+ )
+ actual_result = operator.get_db_hook().default_statement_timeout
+ assert actual_result == expected_result
+
+
+# Happy path DAG runs without error (Each task is a test case)
+# This generates a warning about running a dag without an explicit data interval being
+# deprecated, but I haven't found a way to get it through with this function.
+@mark_extended
+def test_happy_paths_dag(mock_timeout_dag):
+ mock_timeout_dag.test()
+
+
[email protected](scope="session")
+def happy_dag_run(mock_timeout_dag):
+ exec_dt = datetime.now()
+ interval = timedelta(hours=1)
+ return mock_timeout_dag.create_dagrun(
+ run_id=f"happy_dag_testing_{exec_dt.strftime('%y%m%d%H%M%S')}",
+ state="queued",
+ execution_date=exec_dt,
+ data_interval=(exec_dt - (2 * interval), exec_dt - interval),
+ )
+
+
+# Same timeout setting test as above, but this time in the context of an instantiated
+# dag run.
[email protected]("task_id, expected_timeout", HAPPY_TIMEOUT_PARAMETERS)
+def test_use_task_not_task_instance(task_id, expected_timeout, happy_dag_run):
+ with pytest.raises(AttributeError):
+ execution_timeout = happy_dag_run.get_task_instance(task_id).execution_timeout
+ execution_timeout = PostgresHook.get_execution_timeout(
+ happy_dag_run.get_dag().get_task(task_id)
+ )
+ assert execution_timeout == expected_timeout
+
+
+def test_run_statement_timeout():
+ pg = PostgresHook(default_statement_timeout=10)
+ pg.run_statement_timeout()
+ actual = pg.run(sql="show statement_timeout;", statement_timeout=0)
+ assert actual == ("10s",)
diff --git a/tests/dags/providers/provider_api_scripts/test_inaturalist.py b/tests/dags/providers/provider_api_scripts/test_inaturalist.py
index 79deddfd3..45fdbd28d 100644
--- a/tests/dags/providers/provider_api_scripts/test_inaturalist.py
+++ b/tests/dags/providers/provider_api_scripts/test_inaturalist.py
@@ -4,9 +4,9 @@ from unittest import mock
import pytest
from airflow.models import TaskInstance
-from airflow.providers.postgres.hooks.postgres import PostgresHook
-from common.constants import IMAGE, POSTGRES_CONN_ID
+from common.constants import IMAGE
from common.loader.reporting import RecordMetrics
+from common.sql import PostgresHook
from providers.provider_api_scripts import inaturalist
@@ -38,7 +38,7 @@ from providers.provider_api_scripts import inaturalist
INAT = inaturalist.INaturalistDataIngester()
-PG = PostgresHook(POSTGRES_CONN_ID)
+PG = PostgresHook(default_statement_timeout=5)
SQL_SCRIPT_DIR = (
Path(__file__).parents[4]
/ "openverse_catalog/dags/providers/provider_csv_load_scripts/inaturalist"
@@ -167,6 +167,8 @@ def test_consolidate_load_statistics(all_results, expected):
],
)
def test_get_batches(batch_length, max_id, expected):
- with mock.patch.object(PostgresHook, "get_records", return_value=max_id) as pg_mock:
- actual = INAT.get_batches(batch_length, pg_mock)
- assert actual == expected
+ task = mock.Mock()
+ with mock.patch.object(PostgresHook, "get_execution_timeout", return_value=60):
+ with mock.patch.object(PostgresHook, "get_records", return_value=max_id):
+ actual = INAT.get_batches(batch_length, task)
+ assert actual == expected