Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add batched_update dag (#2331)
Staci Mullinsc20f2754490b
diff --git a/catalog/DAGs.md b/catalog/DAGs.mdindex 6d79ac75c..7604e5674 100644--- a/catalog/DAGs.md+++ b/catalog/DAGs.md@@ -42,6 +42,7 @@ The following are DAGs grouped by their primary tag:| DAG ID | Schedule Interval || --------------------------------------------------------------------------------- | ----------------- |+| [`batched_update`](#batched_update) | `None` || [`recreate_audio_popularity_calculation`](#recreate_audio_popularity_calculation) | `None` || [`recreate_image_popularity_calculation`](#recreate_image_popularity_calculation) | `None` || [`report_pending_reported_media`](#report_pending_reported_media) | `@weekly` |@@ -112,6 +113,7 @@ The following is documentation associated with each DAG (where available):1. [`add_license_url`](#add_license_url)1. [`airflow_log_cleanup`](#airflow_log_cleanup)1. [`audio_data_refresh`](#audio_data_refresh)+1. [`batched_update`](#batched_update)1. [`check_silenced_dags`](#check_silenced_dags)1. [`create_filtered_audio_index`](#create_filtered_audio_index)1. [`create_filtered_image_index`](#create_filtered_image_index)@@ -219,6 +221,80 @@ and related PRs:- [[Feature] Data refresh orchestration DAG](https://github.com/WordPress/openverse-catalog/issues/353)- [[Feature] Merge popularity calculations and data refresh into a single DAG](https://github.com/WordPress/openverse-catalog/issues/453)+## `batched_update`++Batched Update DAG++This DAG is used to run a batched SQL update on a media table in the Catalog+database. It is automatically triggered by the `popularity_refresh` DAGs to+refresh popularity data using newly calculated constants, but can also be+triggered manually with custom SQL operations.++The DAG must be run with a valid dag_run configuration specifying the SQL+commands to be run. The DAG will then split the rows to be updated into batches,+and report to Slack when all batches have been updated. It handles all+deadlocking and timeout concerns, ensuring that the provided SQL is run without+interfering with ingestion. For more information, see the implementation plan:+https://docs.openverse.org/projects/proposals/popularity_optimizations/20230420-implementation_plan_popularity_optimizations.html#special-considerations-avoiding-deadlocks-and-timeouts++By default the DAG will run as a dry_run, logging the generated SQL but not+actually running it. To actually perform the update, the `dry_run` parameter+must be explicitly set to `false` in the configuration.++Required Dagrun Configuration parameters:++- query_id: a string identifier which will be appended to temporary table used+ in the update+- table_name: the name of the table to update. Must be a valid media table+- select_query: a SQL `WHERE` clause used to select the rows that will be+ updated+- update_query: the SQL `UPDATE` expression to be run on all selected rows++Optional params:++- dry_run: bool, whether to actually run the generated SQL. True by default.+- batch_size: int number of records to process in each batch. By default, 10_000+- update_timeout: int number of seconds to run an individual batch update before+ timing out. By default, 3600 (or one hour)+- batch_start: int index into the temp table at which to start the update. By+ default, this is 0 and all rows in the temp table are updated.+- resume_update: boolean indicating whether to attempt to resume an update using+ an existing temp table matching the `query_id`. When True, a new temp table is+ not created.++An example dag_run configuration used to set the thumbnails of all Flickr images+to null would look like this:++```+{+ "query_id": "my_flickr_query",+ "table_name": "image",+ "select_query": "WHERE provider='flickr'",+ "update_query": "SET thumbnail=null",+ "batch_size": 10,+ "dry_run": false+}+```++It is possible to resume an update from an arbitrary starting point on an+existing temp table, for example if a DAG succeeds in creating the temp table+but fails midway through the update. To do so, set the `resume_update` param to+True and select your desired `batch_start`. For instance, if the example DAG+given above failed after processing the first 50_000 records, you might run:++```+{+ "query_id": "my_flickr_query",+ "table_name": "image",+ "select_query": "WHERE provider='flickr'",+ "update_query": "SET thumbnail=null",+ "batch_size": 10,+ "batch_start": 50000,+ "resume_update": true,+ "dry_run": false+}+```+## `check_silenced_dags`### Silenced DAGs checkdiff --git a/catalog/dags/database/batched_update/batched_update.py b/catalog/dags/database/batched_update/batched_update.pynew file mode 100644index 000000000..ec7923722--- /dev/null+++ b/catalog/dags/database/batched_update/batched_update.py@@ -0,0 +1,147 @@+import logging+from datetime import timedelta++from airflow.decorators import task+from airflow.models.abstractoperator import AbstractOperator++from common import slack+from common.constants import POSTGRES_CONN_ID+from common.sql import PostgresHook+from database.batched_update import constants+++logger = logging.getLogger(__name__)+++def _single_value(cursor):+ try:+ row = cursor.fetchone()+ return row[0]+ except Exception as e:+ raise ValueError("Unable to extract expected row data from cursor") from e+++def resume_update(+ resume_update: bool,+):+ """+ Return True to short circuit temp table creation if this DagRun is+ resuming from an existing temp table.+ """+ if resume_update:+ # Skip table creation and indexing+ return constants.GET_EXPECTED_COUNT_TASK_ID+ return constants.CREATE_TEMP_TABLE_TASK_ID+++@task+def get_expected_update_count(query_id: str, batch_start: int | None, dry_run: bool):+ """+ Get the number of records left to update, when resuming an update+ on an existing temp table.+ """+ total_count = run_sql.function(+ dry_run=dry_run,+ sql_template=constants.SELECT_TEMP_TABLE_QUERY,+ query_id=query_id,+ handler=_single_value,+ )++ if batch_start:+ total_count -= batch_start+ return max(total_count, 0)+++@task+def run_sql(+ dry_run: bool,+ sql_template: str,+ query_id: str,+ log_sql: bool = True,+ postgres_conn_id: str = POSTGRES_CONN_ID,+ task: AbstractOperator = None,+ timeout: timedelta = None,+ handler: callable = constants.RETURN_ROW_COUNT,+ **kwargs,+):+ query = sql_template.format(+ temp_table_name=constants.TEMP_TABLE_NAME.format(query_id=query_id), **kwargs+ )+ if dry_run:+ logger.info(+ "This is a dry run: no SQL will be executed. To perform the updates,"+ " rerun the DAG with the conf option `'dry_run': false`."+ )+ logger.info(query)+ return 0++ postgres = PostgresHook(+ postgres_conn_id=postgres_conn_id,+ default_statement_timeout=(+ timeout if timeout else PostgresHook.get_execution_timeout(task)+ ),+ log_sql=log_sql,+ )++ return postgres.run(query, handler=handler)+++@task+def update_batches(+ expected_row_count: int,+ batch_size: int,+ dry_run: bool,+ table_name: str,+ query_id: str,+ update_query: str,+ update_timeout: int,+ batch_start: int = 0,+ postgres_conn_id: str = POSTGRES_CONN_ID,+ task: AbstractOperator = None,+ **kwargs,+):+ updated_count = 0+ if batch_start is None:+ batch_start = 0++ while batch_start <= expected_row_count:+ batch_end = batch_start + batch_size++ logger.info(f"Updating rows with id {batch_start} through {batch_end}.")+ count = run_sql.function(+ dry_run=dry_run,+ sql_template=constants.UPDATE_BATCH_QUERY,+ query_id=query_id,+ # Only log the query the first time, so as not to spam the logs+ log_sql=batch_start == 1,+ postgres_conn_id=postgres_conn_id,+ task=task,+ timeout=update_timeout,+ table_name=table_name,+ update_query=update_query,+ batch_start=batch_start,+ batch_end=batch_end,+ )++ updated_count += count+ batch_start = batch_end+ logger.info(+ f"Updated {updated_count} rows. {expected_row_count - updated_count}"+ " remaining."+ )++ return updated_count+++@task+def notify_slack(text: str, dry_run: bool) -> None:+ if not dry_run:+ slack.send_message(+ text,+ username=constants.SLACK_USERNAME,+ icon_emoji=constants.SLACK_ICON,+ dag_id=constants.DAG_ID,+ )+ else:+ logger.info(text)diff --git a/catalog/dags/database/batched_update/batched_update_dag.py b/catalog/dags/database/batched_update/batched_update_dag.pynew file mode 100644index 000000000..6a137a22c--- /dev/null+++ b/catalog/dags/database/batched_update/batched_update_dag.py@@ -0,0 +1,273 @@+"""+Batched Update DAG++This DAG is used to run a batched SQL update on a media table in the Catalog database.+It is automatically triggered by the `popularity_refresh` DAGs to refresh popularity+data using newly calculated constants, but can also be triggered manually with custom+SQL operations.++The DAG must be run with a valid dag_run configuration specifying the SQL commands to+be run. The DAG will then split the rows to be updated into batches, and report to Slack+when all batches have been updated. It handles all deadlocking and timeout concerns,+ensuring that the provided SQL is run without interfering with ingestion. For more+information, see the implementation plan:+https://docs.openverse.org/projects/proposals/popularity_optimizations/20230420-implementation_plan_popularity_optimizations.html#special-considerations-avoiding-deadlocks-and-timeouts++By default the DAG will run as a dry_run, logging the generated SQL but not actually+running it. To actually perform the update, the `dry_run` parameter must be+explicitly set to `false` in the configuration.++Required Dagrun Configuration parameters:++* query_id: a string identifier which will be appended to temporary table used in+ the update+* table_name: the name of the table to update. Must be a valid media table+* select_query: a SQL `WHERE` clause used to select the rows that will be updated+* update_query: the SQL `UPDATE` expression to be run on all selected rows++Optional params:++* dry_run: bool, whether to actually run the generated SQL. True by default.+* batch_size: int number of records to process in each batch. By default, 10_000+* update_timeout: int number of seconds to run an individual batch update before timing+ out. By default, 3600 (or one hour)+* batch_start: int index into the temp table at which to start the update. By default,+ this is 0 and all rows in the temp table are updated.+* resume_update: boolean indicating whether to attempt to resume an update using an+ existing temp table matching the `query_id`. When True, a new temp+ table is not created.++An example dag_run configuration used to set the thumbnails of all Flickr images to+null would look like this:++```+{+ "query_id": "my_flickr_query",+ "table_name": "image",+ "select_query": "WHERE provider='flickr'",+ "update_query": "SET thumbnail=null",+ "batch_size": 10,+ "dry_run": false+}+```++It is possible to resume an update from an arbitrary starting point on an existing+temp table, for example if a DAG succeeds in creating the temp table but fails midway+through the update. To do so, set the `resume_update` param to True and select your+desired `batch_start`. For instance, if the example DAG given above failed after+processing the first 50_000 records, you might run:++```+{+ "query_id": "my_flickr_query",+ "table_name": "image",+ "select_query": "WHERE provider='flickr'",+ "update_query": "SET thumbnail=null",+ "batch_size": 10,+ "batch_start": 50000,+ "resume_update": true,+ "dry_run": false+}+```+"""+++import logging++from airflow.decorators import dag+from airflow.models.param import Param+from airflow.utils.trigger_rule import TriggerRule++from common.constants import AUDIO, DAG_DEFAULT_ARGS, MEDIA_TYPES+from database.batched_update import constants+from database.batched_update.batched_update import (+ get_expected_update_count,+ notify_slack,+ resume_update,+ run_sql,+ update_batches,+)+++logger = logging.getLogger(__name__)+++@dag(+ dag_id=constants.DAG_ID,+ schedule=None,+ start_date=constants.START_DATE,+ tags=["database"],+ # This allows for multiple concurrent batched updates to run, for example popularity+ # refreshes for each provider+ max_active_runs=10,+ dagrun_timeout=constants.DAGRUN_TIMEOUT,+ doc_md=__doc__,+ default_args={+ **DAG_DEFAULT_ARGS,+ "retries": 0,+ },+ render_template_as_native_obj=True,+ params={+ "query_id": Param(+ default="",+ type="string",+ description=(+ "A string which will be appended to the temp table created"+ " during the update, in order to uniquely identify your query."+ ),+ ),+ "table_name": Param(+ default=AUDIO,+ enum=MEDIA_TYPES,+ description=("The name of the media table to be updated."),+ ),+ "select_query": Param(+ default="WHERE...",+ type="string",+ description=(+ "The `WHERE` clause of a query that selects all the rows to"+ " be updated."+ ),+ pattern="^WHERE",+ ),+ "update_query": Param(+ default="SET...",+ type="string",+ description=(+ "The part of the SQL `UPDATE` command, beginning with `SET`, that"+ " will be run for each batch."+ ),+ pattern="^SET",+ ),+ "batch_size": Param(+ default=constants.DEFAULT_BATCH_SIZE,+ type="integer",+ description=("The number of records to update per batch."),+ ),+ "update_timeout": Param(+ default=constants.DEFAULT_UPDATE_BATCH_TIMEOUT,+ type="integer",+ description=(+ "Integer number of seconds giving the maximum length of time it"+ " should take for a single batch to be updated."+ ),+ ),+ "batch_start": Param(+ default=None,+ type=["integer", "null"],+ description=(+ "Optionally, a row_id from which to begin updating records. By"+ " default, all records matching the SELECT will be updated."+ ),+ minimum=0,+ ),+ "resume_update": Param(+ default=False,+ type="boolean",+ description=(+ "Whether to resume an existing update. When True, the DAG will skip"+ " creating a temp table, and instead try to use an existing temp table"+ " matching the `query_id`."+ ),+ ),+ "dry_run": Param(+ default=True,+ type="boolean",+ description=(+ "When True, the SQL commands will not actually be run"+ " but only logged."+ ),+ ),+ },+)+def batched_update():+ check_for_resume_update = resume_update(+ resume_update="{{ params.resume_update }}",+ )++ # Tasks for building a new temp table+ select_rows_to_update = run_sql.override(+ task_id=constants.CREATE_TEMP_TABLE_TASK_ID,+ execution_timeout=constants.SELECT_TIMEOUT,+ )(+ sql_template=constants.CREATE_TEMP_TABLE_QUERY,+ dry_run="{{ params.dry_run }}",+ query_id="{{ params.query_id }}",+ table_name="{{ params.table_name }}",+ select_query="{{ params.select_query }}",+ )++ create_index = run_sql.override(task_id="create_index")(+ sql_template=constants.CREATE_TEMP_TABLE_INDEX_QUERY,+ dry_run="{{ params.dry_run }}",+ query_id="{{ params.query_id }}",+ )++ expected_count = get_expected_update_count.override(+ task_id=constants.GET_EXPECTED_COUNT_TASK_ID,+ trigger_rule=TriggerRule.NONE_FAILED,+ )(+ query_id="{{ params.query_id }}",+ batch_start="{{ params.batch_start }}",+ dry_run="{{ params.dry_run }}",+ )++ check_for_resume_update >> [select_rows_to_update, expected_count]+ select_rows_to_update >> create_index >> expected_count++ notify_before_update = notify_slack.override(task_id="notify_before_update")(+ text=f"Preparing to update {select_rows_to_update} rows for update:"+ " {{ params.query_id }}",+ dry_run="{{ params.dry_run}}",+ )++ perform_batched_update = update_batches.override(+ execution_timeout=constants.UPDATE_TIMEOUT+ )(+ expected_row_count=expected_count,+ batch_size="{{ params.batch_size }}",+ batch_start="{{ params.batch_start }}",+ dry_run="{{ params.dry_run }}",+ table_name="{{ params.table_name }}",+ query_id="{{ params.query_id }}",+ update_query="{{ params.update_query }}",+ update_timeout="{{ params.update_timeout }}",+ )++ expected_count >> [notify_before_update, perform_batched_update]++ notify_updated_count = notify_slack.override(task_id="notify_updated_count")(+ text=f"Updated {perform_batched_update} records for update:"+ " {{ params.query_id }}",+ dry_run="{{ params.dry_run}}",+ )++ # The temporary table is only dropped if all updates were successful; this+ # prevents needing to rebuild a potentially expensive table when+ # retrying the DAG.+ drop_temporary_table = run_sql.override(+ task_id="drop_temp_table",+ )(+ sql_template=constants.DROP_TABLE_QUERY,+ dry_run="{{ params.dry_run }}",+ query_id="{{ params.query_id }}",+ )++ # If there was an error, notify to Slack that the temporary table must be+ # dropped manually or the DAG retried.+ notify_failure = notify_slack.override(+ task_id="notify_failure", trigger_rule=TriggerRule.ONE_FAILED+ )(+ text="Update {{ params.query_id }} failed: retry the DAG or manually drop the"+ " temp table.",+ dry_run="{{ params.dry_run}}",+ )++ perform_batched_update >> [+ notify_updated_count,+ drop_temporary_table,+ notify_failure,+ ]+++batched_update()diff --git a/catalog/dags/database/batched_update/constants.py b/catalog/dags/database/batched_update/constants.pynew file mode 100644index 000000000..4d74d86b4--- /dev/null+++ b/catalog/dags/database/batched_update/constants.py@@ -0,0 +1,43 @@+from datetime import datetime, timedelta+++DAG_ID = "batched_update"+START_DATE = datetime(2023, 5, 1)+SLACK_USERNAME = "Upstream Batched Update"+SLACK_ICON = ":database:"++DEFAULT_BATCH_SIZE = 10_000+DAGRUN_TIMEOUT = timedelta(days=31 * 3)+SELECT_TIMEOUT = timedelta(hours=24)+UPDATE_TIMEOUT = timedelta(days=30 * 3) # 3 months++# Task IDs used for branching operator+GET_EXPECTED_COUNT_TASK_ID = "get_expected_update_count"+CREATE_TEMP_TABLE_TASK_ID = "select_rows_to_update"++# Timeout for an individual batch, given in seconds+DEFAULT_UPDATE_BATCH_TIMEOUT = 60 * 60 # 1 hour++TEMP_TABLE_NAME = "{query_id}_rows_to_update"+CREATE_TEMP_TABLE_QUERY = """+ CREATE TABLE {temp_table_name} AS+ SELECT ROW_NUMBER() OVER() row_id, identifier+ FROM {table_name}+ {select_query};+ """+CREATE_TEMP_TABLE_INDEX_QUERY = "CREATE INDEX ON {temp_table_name}(row_id)"+SELECT_TEMP_TABLE_QUERY = """+ SELECT COUNT(*)+ FROM {temp_table_name};+ """+UPDATE_BATCH_QUERY = """+ UPDATE {table_name}+ {update_query}+ WHERE identifier in (+ SELECT identifier FROM {temp_table_name}+ WHERE row_id > {batch_start} AND row_id <= {batch_end}+ FOR UPDATE SKIP LOCKED+ );+ """+DROP_TABLE_QUERY = "DROP TABLE IF EXISTS {temp_table_name} CASCADE;"+RETURN_ROW_COUNT = lambda c: c.rowcount # noqa: E731diff --git a/catalog/tests/dags/common/loader/test_sql.py b/catalog/tests/dags/common/loader/test_sql.pyindex 2ef6bebe9..b3c48aa6e 100644--- a/catalog/tests/dags/common/loader/test_sql.py+++ b/catalog/tests/dags/common/loader/test_sql.py@@ -2,13 +2,11 @@ import jsonimport loggingimport osimport time-from collections import namedtuplefrom textwrap import dedentfrom unittest import mockimport psycopg2import pytest-from airflow.models import TaskInstancefrom flaky import flakyfrom psycopg2.errors import InvalidTextRepresentation@@ -16,95 +14,14 @@ from catalog.tests.dags.common.popularity.test_sql import (TableInfo,_set_up_std_popularity_func,)-from common.constants import IMAGE+from catalog.tests.test_utils import sql as utilsfrom common.loader import sql-from common.loader.sql import TSV_COLUMNS, create_column_definitionsfrom common.storage import columns as col-from common.storage.db_columns import IMAGE_TABLE_COLUMNSPOSTGRES_CONN_ID = os.getenv("TEST_CONN_ID")-POSTGRES_TEST_URI = os.getenv("AIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING")-S3_LOCAL_ENDPOINT = os.getenv("S3_LOCAL_ENDPOINT")-ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")-SECRET_KEY = os.getenv("AWS_SECRET_KEY")-RESOURCES = os.path.join(os.path.abspath(os.path.dirname(__file__)), "test_resources")-LOADING_TABLE_COLUMN_DEFINITIONS = create_column_definitions(- TSV_COLUMNS[IMAGE], is_loading=True-)--CREATE_LOAD_TABLE_QUERY = f"""CREATE TABLE public.{{}} (- {LOADING_TABLE_COLUMN_DEFINITIONS}-);"""--IMAGE_TABLE_COLUMN_DEFINITIONS = create_column_definitions(IMAGE_TABLE_COLUMNS)--CREATE_IMAGE_TABLE_QUERY = f"""CREATE TABLE public.{{}} (- {IMAGE_TABLE_COLUMN_DEFINITIONS}-);"""--UNIQUE_CONDITION_QUERY = (- "CREATE UNIQUE INDEX {table}_provider_fid_idx"- " ON public.{table}"- " USING btree (provider, md5(foreign_identifier));"- "CREATE UNIQUE INDEX {table}_identifier_key"- " ON public.{table}"- " USING btree (identifier);"- "CREATE UNIQUE INDEX {table}_url_key"- " ON public.{table}"- " USING btree (url);"-)---PostgresRef = namedtuple("PostgresRef", ["cursor", "connection"])-ti = mock.Mock(spec=TaskInstance)-ti.xcom_pull.return_value = None--COLUMN_NAMES = [column.db_name for column in IMAGE_TABLE_COLUMNS]--# ids for main database columns-updated_idx = COLUMN_NAMES.index(col.UPDATED_ON.db_name)-ingestion_idx = COLUMN_NAMES.index(col.INGESTION_TYPE.db_name)-provider_idx = COLUMN_NAMES.index(col.PROVIDER.db_name)-source_idx = COLUMN_NAMES.index(col.SOURCE.db_name)-fid_idx = COLUMN_NAMES.index(col.FOREIGN_ID.db_name)-land_url_idx = COLUMN_NAMES.index(col.LANDING_URL.db_name)-url_idx = COLUMN_NAMES.index(col.DIRECT_URL.db_name)-thm_idx = COLUMN_NAMES.index(col.THUMBNAIL.db_name)-filesize_idx = COLUMN_NAMES.index(col.FILESIZE.db_name)-license_idx = COLUMN_NAMES.index(col.LICENSE.db_name)-version_idx = COLUMN_NAMES.index(col.LICENSE_VERSION.db_name)-creator_idx = COLUMN_NAMES.index(col.CREATOR.db_name)-creator_url_idx = COLUMN_NAMES.index(col.CREATOR_URL.db_name)-title_idx = COLUMN_NAMES.index(col.TITLE.db_name)-metadata_idx = COLUMN_NAMES.index(col.META_DATA.db_name)-tags_idx = COLUMN_NAMES.index(col.TAGS.db_name)-synced_idx = COLUMN_NAMES.index(col.LAST_SYNCED.db_name)-removed_idx = COLUMN_NAMES.index(col.REMOVED.db_name)-watermarked_idx = COLUMN_NAMES.index(col.WATERMARKED.db_name)-width_idx = COLUMN_NAMES.index(col.WIDTH.db_name)-height_idx = COLUMN_NAMES.index(col.HEIGHT.db_name)-standardized_popularity_idx = COLUMN_NAMES.index(col.STANDARDIZED_POPULARITY.db_name)---def create_query_values(- column_values: dict,- columns=None,-):- if columns is None:- columns = TSV_COLUMNS[IMAGE]- result = []- for column in columns:- val = column_values.get(column.db_name)- if val is None:- val = "null"- else:- val = f"'{str(val)}'"- result.append(val)- return ",".join(result)-@pytest.fixturedef load_table(identifier):@@ -131,14 +48,14 @@ def table_info(@pytest.fixture-def postgres(load_table) -> PostgresRef:- conn = psycopg2.connect(POSTGRES_TEST_URI)+def postgres(load_table) -> utils.PostgresRef:+ conn = psycopg2.connect(utils.POSTGRES_TEST_URI)cur = conn.cursor()drop_command = f"DROP TABLE IF EXISTS {load_table}"cur.execute(drop_command)conn.commit()- yield PostgresRef(cursor=cur, connection=conn)+ yield utils.PostgresRef(cursor=cur, connection=conn)cur.execute(drop_command)cur.close()@@ -147,8 +64,10 @@ def postgres(load_table) -> PostgresRef:@pytest.fixture-def postgres_with_load_table(postgres: PostgresRef, load_table) -> PostgresRef:- create_command = CREATE_LOAD_TABLE_QUERY.format(load_table)+def postgres_with_load_table(+ postgres: utils.PostgresRef, load_table+) -> utils.PostgresRef:+ create_command = utils.CREATE_LOAD_TABLE_QUERY.format(load_table)postgres.cursor.execute(create_command)postgres.connection.commit()@@ -159,7 +78,7 @@ def postgres_with_load_table(postgres: PostgresRef, load_table) -> PostgresRef:def postgres_with_load_and_image_table(load_table, image_table, table_info, mock_pg_hook_task):- conn = psycopg2.connect(POSTGRES_TEST_URI)+ conn = psycopg2.connect(utils.POSTGRES_TEST_URI)cur = conn.cursor()drop_test_relations_query = f"""DROP TABLE IF EXISTS {load_table} CASCADE;@@ -173,14 +92,14 @@ def postgres_with_load_and_image_table(cur.execute(drop_test_relations_query)- cur.execute(CREATE_LOAD_TABLE_QUERY.format(load_table))+ cur.execute(utils.CREATE_LOAD_TABLE_QUERY.format(load_table))cur.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;')- cur.execute(CREATE_IMAGE_TABLE_QUERY.format(image_table))- cur.execute(UNIQUE_CONDITION_QUERY.format(table=image_table))+ cur.execute(utils.CREATE_IMAGE_TABLE_QUERY.format(image_table))+ cur.execute(utils.UNIQUE_CONDITION_QUERY.format(table=image_table))conn.commit()- yield PostgresRef(cursor=cur, connection=conn)+ yield utils.PostgresRef(cursor=cur, connection=conn)cur.execute(drop_test_relations_query)cur.close()@@ -529,7 +448,7 @@ def test_upsert_records_inserts_one_record_to_empty_image_table(SOURCE = "images_source"INGESTION_TYPE = "test_ingestion"- query_values = create_query_values(+ query_values = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.LANDING_URL.db_name: LAND_URL,@@ -563,24 +482,24 @@ def test_upsert_records_inserts_one_record_to_empty_image_table(actual_rows = postgres_with_load_and_image_table.cursor.fetchall()actual_row = actual_rows[0]assert len(actual_rows) == 1- assert actual_row[ingestion_idx] == INGESTION_TYPE- assert actual_row[provider_idx] == PROVIDER- assert actual_row[source_idx] == SOURCE- assert actual_row[fid_idx] == FID- assert actual_row[land_url_idx] == LAND_URL- assert actual_row[url_idx] == IMG_URL- assert actual_row[thm_idx] == THM_URL- assert actual_row[filesize_idx] == FILESIZE- assert actual_row[license_idx] == LICENSE- assert actual_row[version_idx] == VERSION- assert actual_row[creator_idx] == CREATOR- assert actual_row[creator_url_idx] == CREATOR_URL- assert actual_row[title_idx] == TITLE- assert actual_row[metadata_idx] == json.loads(META_DATA)- assert actual_row[tags_idx] == json.loads(TAGS)- assert actual_row[watermarked_idx] is False- assert actual_row[width_idx] == WIDTH- assert actual_row[height_idx] == HEIGHT+ assert actual_row[utils.ingestion_idx] == INGESTION_TYPE+ assert actual_row[utils.provider_idx] == PROVIDER+ assert actual_row[utils.source_idx] == SOURCE+ assert actual_row[utils.fid_idx] == FID+ assert actual_row[utils.land_url_idx] == LAND_URL+ assert actual_row[utils.url_idx] == IMG_URL+ assert actual_row[utils.thm_idx] == THM_URL+ assert actual_row[utils.filesize_idx] == FILESIZE+ assert actual_row[utils.license_idx] == LICENSE+ assert actual_row[utils.version_idx] == VERSION+ assert actual_row[utils.creator_idx] == CREATOR+ assert actual_row[utils.creator_url_idx] == CREATOR_URL+ assert actual_row[utils.title_idx] == TITLE+ assert actual_row[utils.metadata_idx] == json.loads(META_DATA)+ assert actual_row[utils.tags_idx] == json.loads(TAGS)+ assert actual_row[utils.watermarked_idx] is False+ assert actual_row[utils.width_idx] == WIDTH+ assert actual_row[utils.height_idx] == HEIGHTdef test_upsert_records_inserts_two_records_to_image_table(@@ -623,8 +542,8 @@ def test_upsert_records_inserts_two_records_to_image_table()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- assert actual_rows[1][fid_idx] == FID_B+ assert actual_rows[0][utils.fid_idx] == FID_A+ assert actual_rows[1][utils.fid_idx] == FID_Bdef test_upsert_records_replaces_updated_on_and_last_synced_with_source(@@ -661,8 +580,8 @@ def test_upsert_records_replaces_updated_on_and_last_synced_with_source(original_row = postgres_with_load_and_image_table.cursor.fetchall()logging.info(f"\n{len(original_row)}\nOriginal row: {original_row}\n")original_row = original_row[0]- original_updated_on = original_row[updated_idx]- original_last_synced = original_row[synced_idx]+ original_updated_on = original_row[utils.updated_idx]+ original_last_synced = original_row[utils.synced_idx]logging.info(f"\nLast updated: {original_updated_on}\nSynced: {original_last_synced}")@@ -677,8 +596,8 @@ def test_upsert_records_replaces_updated_on_and_last_synced_with_source(f"\n{len(updated_result)}\nLast updated: {original_updated_on}\nSynced: {original_last_synced}")updated_row = updated_result[0]- updated_updated_on = updated_row[updated_idx]- updated_last_synced = updated_row[synced_idx]+ updated_updated_on = updated_row[utils.updated_idx]+ updated_last_synced = updated_row[utils.synced_idx]assert len(updated_result) == 1assert updated_updated_on > original_updated_on@@ -727,7 +646,7 @@ def test_upsert_records_replaces_data(TITLE_B = "Bobs Great Pic"META_DATA_B = '{"description": "Bobs cool picture"}'- query_values = create_query_values(+ query_values = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.LANDING_URL.db_name: LAND_URL_A,@@ -759,7 +678,7 @@ def test_upsert_records_replaces_data()postgres_with_load_and_image_table.connection.commit()- query_values = create_query_values(+ query_values = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.LANDING_URL.db_name: LAND_URL_B,@@ -796,17 +715,17 @@ def test_upsert_records_replaces_data(actual_rows = postgres_with_load_and_image_table.cursor.fetchall()actual_row = actual_rows[0]assert len(actual_rows) == 1- assert actual_row[land_url_idx] == LAND_URL_B- assert actual_row[url_idx] == IMG_URL_B- assert actual_row[thm_idx] == THM_URL_B- assert actual_row[license_idx] == LICENSE_B- assert actual_row[version_idx] == VERSION_B- assert actual_row[creator_idx] == CREATOR_B- assert actual_row[creator_url_idx] == CREATOR_URL_B- assert actual_row[title_idx] == TITLE_B- assert actual_row[metadata_idx] == json.loads(META_DATA_B)- assert actual_row[tags_idx] == json.loads(TAGS)- assert actual_row[width_idx] == WIDTH_B+ assert actual_row[utils.land_url_idx] == LAND_URL_B+ assert actual_row[utils.url_idx] == IMG_URL_B+ assert actual_row[utils.thm_idx] == THM_URL_B+ assert actual_row[utils.license_idx] == LICENSE_B+ assert actual_row[utils.version_idx] == VERSION_B+ assert actual_row[utils.creator_idx] == CREATOR_B+ assert actual_row[utils.creator_url_idx] == CREATOR_URL_B+ assert actual_row[utils.title_idx] == TITLE_B+ assert actual_row[utils.metadata_idx] == json.loads(META_DATA_B)+ assert actual_row[utils.tags_idx] == json.loads(TAGS)+ assert actual_row[utils.width_idx] == WIDTH_Bdef test_upsert_records_does_not_replace_with_nulls(@@ -843,7 +762,7 @@ def test_upsert_records_does_not_replace_with_nulls(LICENSE_B = "cc0"VERSION_B = "1.0"- query_values_a = create_query_values(+ query_values_a = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.LANDING_URL.db_name: LAND_URL_A,@@ -875,7 +794,7 @@ def test_upsert_records_does_not_replace_with_nulls()postgres_with_load_and_image_table.connection.commit()- query_values_b = create_query_values(+ query_values_b = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.LANDING_URL.db_name: LAND_URL_B,@@ -902,18 +821,18 @@ def test_upsert_records_does_not_replace_with_nulls(actual_rows = postgres_with_load_and_image_table.cursor.fetchall()actual_row = actual_rows[0]assert len(actual_rows) == 1- assert actual_row[land_url_idx] == LAND_URL_B- assert actual_row[thm_idx] == THM_URL_A- assert actual_row[filesize_idx] == FILESIZE- assert actual_row[license_idx] == LICENSE_B- assert actual_row[version_idx] == VERSION_B- assert actual_row[creator_idx] == CREATOR_A- assert actual_row[creator_url_idx] == CREATOR_URL_A- assert actual_row[title_idx] == TITLE_A- assert actual_row[metadata_idx] == json.loads(META_DATA_A)- assert actual_row[tags_idx] == json.loads(TAGS)- assert actual_row[width_idx] == WIDTH_A- assert actual_row[height_idx] == HEIGHT_A+ assert actual_row[utils.land_url_idx] == LAND_URL_B+ assert actual_row[utils.thm_idx] == THM_URL_A+ assert actual_row[utils.filesize_idx] == FILESIZE+ assert actual_row[utils.license_idx] == LICENSE_B+ assert actual_row[utils.version_idx] == VERSION_B+ assert actual_row[utils.creator_idx] == CREATOR_A+ assert actual_row[utils.creator_url_idx] == CREATOR_URL_A+ assert actual_row[utils.title_idx] == TITLE_A+ assert actual_row[utils.metadata_idx] == json.loads(META_DATA_A)+ assert actual_row[utils.tags_idx] == json.loads(TAGS)+ assert actual_row[utils.width_idx] == WIDTH_A+ assert actual_row[utils.height_idx] == HEIGHT_Adef test_upsert_records_merges_meta_data(@@ -934,7 +853,7 @@ def test_upsert_records_merges_meta_data(META_DATA_A = '{"description": "a cool picture", "test": "should stay"}'META_DATA_B = '{"description": "I updated my description"}'- query_values_a = create_query_values(+ query_values_a = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -947,7 +866,7 @@ def test_upsert_records_merges_meta_data({query_values_a});"""- query_values_b = create_query_values(+ query_values_b = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -979,7 +898,7 @@ def test_upsert_records_merges_meta_data(assert len(actual_rows) == 1expected_meta_data = json.loads(META_DATA_A)expected_meta_data.update(json.loads(META_DATA_B))- assert actual_row[metadata_idx] == expected_meta_data+ assert actual_row[utils.metadata_idx] == expected_meta_datadef test_upsert_records_does_not_replace_with_null_values_in_meta_data(@@ -1000,7 +919,7 @@ def test_upsert_records_does_not_replace_with_null_values_in_meta_data(META_DATA_A = '{"description": "a cool picture", "test": "should stay"}'META_DATA_B = '{"description": "I updated my description", "test": null}'- query_values_a = create_query_values(+ query_values_a = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -1013,7 +932,7 @@ def test_upsert_records_does_not_replace_with_null_values_in_meta_data({query_values_a});"""- query_values_b = create_query_values(+ query_values_b = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -1047,7 +966,7 @@ def test_upsert_records_does_not_replace_with_null_values_in_meta_data("description": json.loads(META_DATA_B)["description"],"test": json.loads(META_DATA_A)["test"],}- assert actual_row[metadata_idx] == expected_meta_data+ assert actual_row[utils.metadata_idx] == expected_meta_datadef test_upsert_records_merges_tags(@@ -1075,7 +994,7 @@ def test_upsert_records_merges_tags(])- query_values_a = create_query_values(+ query_values_a = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -1088,7 +1007,7 @@ def test_upsert_records_merges_tags({query_values_a});"""- query_values_b = create_query_values(+ query_values_b = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -1123,7 +1042,7 @@ def test_upsert_records_merges_tags({"name": "tagtwo", "provider": "test"},{"name": "tagthree", "provider": "test"},]- actual_tags = actual_row[tags_idx]+ actual_tags = actual_row[utils.tags_idx]assert len(actual_tags) == 3assert all([t in expect_tags for t in actual_tags])assert all([t in actual_tags for t in expect_tags])@@ -1149,7 +1068,7 @@ def test_upsert_records_does_not_replace_tags_with_null({"name": "tagtwo", "provider": "test"},]- query_values_a = create_query_values(+ query_values_a = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -1162,7 +1081,7 @@ def test_upsert_records_does_not_replace_tags_with_null({query_values_a});"""- query_values_b = create_query_values(+ query_values_b = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -1195,7 +1114,7 @@ def test_upsert_records_does_not_replace_tags_with_null({"name": "tagone", "provider": "test"},{"name": "tagtwo", "provider": "test"},]- actual_tags = actual_row[tags_idx]+ actual_tags = actual_row[utils.tags_idx]assert len(actual_tags) == 2assert all([t in expect_tags for t in actual_tags])assert all([t in actual_tags for t in expect_tags])@@ -1219,7 +1138,7 @@ def test_upsert_records_replaces_null_tags({"name": "tagone", "provider": "test"},{"name": "tagtwo", "provider": "test"},]- query_values_a = create_query_values(+ query_values_a = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -1231,7 +1150,7 @@ def test_upsert_records_replaces_null_tags(load_data_query_a = f"""INSERT INTO {load_table} VALUES({query_values_a});"""- query_values_b = create_query_values(+ query_values_b = utils.create_query_values({col.FOREIGN_ID.db_name: FID,col.DIRECT_URL.db_name: IMG_URL,@@ -1267,7 +1186,7 @@ def test_upsert_records_replaces_null_tags({"name": "tagone", "provider": "test"},{"name": "tagtwo", "provider": "test"},]- actual_tags = actual_row[tags_idx]+ actual_tags = actual_row[utils.tags_idx]assert len(actual_tags) == 2assert all([t in expect_tags for t in actual_tags])assert all([t in actual_tags for t in expect_tags])@@ -1294,7 +1213,7 @@ def test_upsert_records_handles_duplicate_url_and_does_not_merge(META_DATA_B = '{"description": "the same cool picture"}'# A and B have different foreign identifiers, but the same url- query_values_a = create_query_values(+ query_values_a = utils.create_query_values({col.FOREIGN_ID.db_name: FID_A,col.DIRECT_URL.db_name: IMG_URL,@@ -1307,7 +1226,7 @@ def test_upsert_records_handles_duplicate_url_and_does_not_merge({query_values_a});"""- query_values_b = create_query_values(+ query_values_b = utils.create_query_values({col.FOREIGN_ID.db_name: FID_B,col.DIRECT_URL.db_name: IMG_URL,@@ -1349,8 +1268,8 @@ def test_upsert_records_handles_duplicate_url_and_does_not_merge(assert len(actual_rows) == 1# No data in A should have been updated or mergedexpected_meta_data = json.loads(META_DATA_A)- assert actual_row[metadata_idx] == expected_meta_data- assert actual_row[fid_idx] == "a"+ assert actual_row[utils.metadata_idx] == expected_meta_data+ assert actual_row[utils.fid_idx] == "a"def test_upsert_records_handles_duplicate_urls_in_a_single_batch_and_does_not_merge(@@ -1376,7 +1295,7 @@ def test_upsert_records_handles_duplicate_urls_in_a_single_batch_and_does_not_meIMG_URL_C = "https://images.com/c/img.jpg"# A and B have different foreign identifiers, but the same url- query_values_a = create_query_values(+ query_values_a = utils.create_query_values({col.FOREIGN_ID.db_name: FID_A,col.DIRECT_URL.db_name: IMG_URL,@@ -1389,7 +1308,7 @@ def test_upsert_records_handles_duplicate_urls_in_a_single_batch_and_does_not_me{query_values_a});"""- query_values_b = create_query_values(+ query_values_b = utils.create_query_values({col.FOREIGN_ID.db_name: FID_B,col.DIRECT_URL.db_name: IMG_URL,@@ -1403,7 +1322,7 @@ def test_upsert_records_handles_duplicate_urls_in_a_single_batch_and_does_not_me);"""# C is not a duplicate of anything, just a normal image- query_values_c = create_query_values(+ query_values_c = utils.create_query_values({col.FOREIGN_ID.db_name: FID_C,col.DIRECT_URL.db_name: IMG_URL_C,@@ -1443,9 +1362,9 @@ def test_upsert_records_handles_duplicate_urls_in_a_single_batch_and_does_not_meassert len(actual_rows) == 2# No data in A should have been updated or mergedexpected_meta_data = json.loads(META_DATA_A)- assert actual_rows[0][metadata_idx] == expected_meta_data- assert actual_rows[0][fid_idx] == "a"- assert actual_rows[1][fid_idx] == "c"+ assert actual_rows[0][utils.metadata_idx] == expected_meta_data+ assert actual_rows[0][utils.fid_idx] == "a"+ assert actual_rows[1][utils.fid_idx] == "c"def test_upsert_records_calculates_standardized_popularity(@@ -1509,7 +1428,7 @@ def test_upsert_records_calculates_standardized_popularity(# records, and also insert a new one.# A record matching one of our existing records into the load table.- query_values_update_old_record = create_query_values(+ query_values_update_old_record = utils.create_query_values({col.FOREIGN_ID.db_name: FID_A, # Matching a record that was already insertedcol.DIRECT_URL.db_name: "https://test.com/a.jpg",@@ -1520,7 +1439,7 @@ def test_upsert_records_calculates_standardized_popularity()# A brand new record into the load table.- query_values_update_new_record = create_query_values(+ query_values_update_new_record = utils.create_query_values({col.FOREIGN_ID.db_name: FID_C,col.DIRECT_URL.db_name: "https://test.com/z.jpg",@@ -1567,17 +1486,17 @@ def test_upsert_records_calculates_standardized_popularity(assert len(actual_rows) == 3# This record was present on the image table but was not updated, so it still has null popularity.- assert actual_rows[0][fid_idx] == FID_B- assert actual_rows[0][standardized_popularity_idx] is None+ assert actual_rows[0][utils.fid_idx] == FID_B+ assert actual_rows[0][utils.standardized_popularity_idx] is None# This is the row that was updated; it should have standardized popularity calculated based on its# updated raw popularity score, rather than the initial raw score.- assert actual_rows[1][fid_idx] == FID_A- assert actual_rows[1][standardized_popularity_idx] == 0.44444444444444453+ assert actual_rows[1][utils.fid_idx] == FID_A+ assert actual_rows[1][utils.standardized_popularity_idx] == 0.44444444444444453# This is the new record- assert actual_rows[2][fid_idx] == FID_C- assert actual_rows[2][standardized_popularity_idx] == 0.6153846153846154+ assert actual_rows[2][utils.fid_idx] == FID_C+ assert actual_rows[2][utils.standardized_popularity_idx] == 0.6153846153846154def test_drop_load_table_drops_table(postgres_with_load_table, load_table, identifier):diff --git a/catalog/tests/dags/database/test_batched_update.py b/catalog/tests/dags/database/test_batched_update.pynew file mode 100644index 000000000..fe2bb1a83--- /dev/null+++ b/catalog/tests/dags/database/test_batched_update.py@@ -0,0 +1,304 @@+import logging+import uuid++import psycopg2+import pytest++from catalog.tests.test_utils import sql+from common.storage import columns as col+from common.storage.db_columns import IMAGE_TABLE_COLUMNS+from database.batched_update import constants+from database.batched_update.batched_update import (+ get_expected_update_count,+ update_batches,+)+++logger = logging.getLogger(__name__)+++FID_A = "a"+FID_B = "b"+FID_C = "c"+MATCHING_PROVIDER = "foo"+NOT_MATCHING_PROVIDER = "bar"+OLD_TITLE = "old title"+NEW_TITLE = "new title"+LICENSE = "by"+++def identifier(request):+ return f"{hash(request.node.name)}".replace("-", "_")+++def image_table(identifier):+ # Parallelized tests need to use distinct database tables+ return f"image_{identifier}"+++def temp_table(identifier):+ return f"test_{identifier}_rows_to_update"+++def postgres_with_image_and_temp_table(image_table, temp_table):+ conn = psycopg2.connect(sql.POSTGRES_TEST_URI)+ cur = conn.cursor()+ drop_table_query = f"""+ DROP TABLE IF EXISTS {image_table} CASCADE;+ DROP TABLE IF EXISTS {temp_table} CASCADE;+ """+ cur.execute(drop_table_query)+ cur.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;')+ # The temp table is created as part of tests.+ cur.execute(sql.CREATE_IMAGE_TABLE_QUERY.format(image_table))++ conn.commit()++ yield sql.PostgresRef(cursor=cur, connection=conn)++ cur.execute(drop_table_query)+ cur.close()+ conn.commit()+ conn.close()+++def _get_insert_query(image_table, values: dict):+ # Append the required identifier+ values[col.IDENTIFIER.db_name] = uuid.uuid4()++ query_values = sql.create_query_values(values, columns=IMAGE_TABLE_COLUMNS)++ return f"INSERT INTO {image_table} VALUES({query_values});"+++def _load_sample_data_into_image_table(image_table, postgres):+ DEFAULT_COLS = {+ col.LICENSE.db_name: LICENSE,+ col.UPDATED_ON.db_name: "NOW()",+ col.CREATED_ON.db_name: "NOW()",+ col.TITLE.db_name: OLD_TITLE,+ }++ # Load sample data into the image table+ sample_records = [+ {+ col.FOREIGN_ID.db_name: FID_A,+ col.DIRECT_URL.db_name: f"https://images.com/{FID_A}/img.jpg",+ col.PROVIDER.db_name: MATCHING_PROVIDER,+ },+ {+ col.FOREIGN_ID.db_name: FID_B,+ col.DIRECT_URL.db_name: f"https://images.com/{FID_B}/img.jpg",+ col.PROVIDER.db_name: MATCHING_PROVIDER,+ },+ {+ col.FOREIGN_ID.db_name: FID_C,+ col.DIRECT_URL.db_name: f"https://images.com/{FID_C}/img.jpg",+ col.PROVIDER.db_name: NOT_MATCHING_PROVIDER,+ },+ ]++ for record in sample_records:+ load_data_query = _get_insert_query(+ image_table,+ {+ **record,+ **DEFAULT_COLS,+ },+ )+ postgres.cursor.execute(load_data_query)++ postgres.connection.commit()+++ "batch_start, expected_count",+ [+ (None, 3),+ (0, 3),+ (1, 2),+ (2, 1),+ # Batch start greater than the total number of records+ (4, 0),+ ],+)+def test_get_expected_update_count(+ postgres_with_image_and_temp_table,+ image_table,+ temp_table,+ identifier,+ batch_start,+ expected_count,+):+ # Load sample data into the image table+ _load_sample_data_into_image_table(+ image_table,+ postgres_with_image_and_temp_table,+ )++ # Create the temp table with a query that will select all records+ select_query = f"WHERE title='{OLD_TITLE}'"+ create_temp_table_query = constants.CREATE_TEMP_TABLE_QUERY.format(+ temp_table_name=temp_table, table_name=image_table, select_query=select_query+ )+ postgres_with_image_and_temp_table.cursor.execute(create_temp_table_query)+ postgres_with_image_and_temp_table.connection.commit()++ total_count = get_expected_update_count.function(+ query_id=f"test_{identifier}", batch_start=batch_start, dry_run=False+ )++ assert total_count == expected_count+++def test_update_batches(+ postgres_with_image_and_temp_table,+ image_table,+ temp_table,+ identifier,+):+ # Load sample data into the image table+ _load_sample_data_into_image_table(+ image_table,+ postgres_with_image_and_temp_table,+ )++ # Create the temp table with a query that will select records A and B+ select_query = f"WHERE provider='{MATCHING_PROVIDER}'"+ create_temp_table_query = constants.CREATE_TEMP_TABLE_QUERY.format(+ temp_table_name=temp_table, table_name=image_table, select_query=select_query+ )+ postgres_with_image_and_temp_table.cursor.execute(create_temp_table_query)+ postgres_with_image_and_temp_table.connection.commit()++ # Test update query+ update_query = f"SET title='{NEW_TITLE}'"+ updated_count = update_batches.function(+ dry_run=False,+ query_id=f"test_{identifier}",+ table_name=image_table,+ expected_row_count=2,+ batch_size=1,+ update_query=update_query,+ update_timeout=3600,+ postgres_conn_id=sql.POSTGRES_CONN_ID,+ )++ # Both records A and C should be updated+ assert updated_count == 2++ postgres_with_image_and_temp_table.cursor.execute(f"SELECT * FROM {image_table};")+ actual_rows = postgres_with_image_and_temp_table.cursor.fetchall()++ assert len(actual_rows) == 3+ # This is the row that did not match the initial select_query, and will+ # therefore not be updated regardless of whether it is a dry run+ assert actual_rows[0][sql.fid_idx] == FID_C+ assert actual_rows[0][sql.title_idx] == OLD_TITLE++ # These are the updated rows+ assert actual_rows[1][sql.fid_idx] == FID_A+ assert actual_rows[1][sql.title_idx] == NEW_TITLE+ assert actual_rows[2][sql.fid_idx] == FID_B+ assert actual_rows[2][sql.title_idx] == NEW_TITLE+++def test_update_batches_dry_run(+ postgres_with_image_and_temp_table,+ image_table,+ temp_table,+ identifier,+):+ # Load sample data into the image table+ _load_sample_data_into_image_table(+ image_table,+ postgres_with_image_and_temp_table,+ )++ # Create the temp table with a query that will select records A and B+ select_query = f"WHERE provider='{MATCHING_PROVIDER}'"+ create_temp_table_query = constants.CREATE_TEMP_TABLE_QUERY.format(+ temp_table_name=temp_table, table_name=image_table, select_query=select_query+ )+ postgres_with_image_and_temp_table.cursor.execute(create_temp_table_query)+ postgres_with_image_and_temp_table.connection.commit()++ # Test update query+ update_query = f"SET title='{NEW_TITLE}'"+ updated_count = update_batches.function(+ dry_run=True,+ query_id=f"test_{identifier}",+ batch_start=None,+ table_name=image_table,+ expected_row_count=2,+ batch_size=1,+ update_query=update_query,+ update_timeout=3600,+ postgres_conn_id=sql.POSTGRES_CONN_ID,+ )++ # No records should be updated+ assert updated_count == 0++ postgres_with_image_and_temp_table.cursor.execute(f"SELECT * FROM {image_table};")+ actual_rows = postgres_with_image_and_temp_table.cursor.fetchall()++ assert len(actual_rows) == 3+ for row in actual_rows:+ assert row[sql.title_idx] == OLD_TITLE+++def test_update_batches_from_batch_start(+ postgres_with_image_and_temp_table,+ image_table,+ temp_table,+ identifier,+):+ # Load sample data into the image table+ _load_sample_data_into_image_table(+ image_table,+ postgres_with_image_and_temp_table,+ )++ # Create the temp table with a query that will select all three records+ select_query = f"WHERE title='{OLD_TITLE}'"+ create_temp_table_query = constants.CREATE_TEMP_TABLE_QUERY.format(+ temp_table_name=temp_table, table_name=image_table, select_query=select_query+ )+ postgres_with_image_and_temp_table.cursor.execute(create_temp_table_query)+ postgres_with_image_and_temp_table.connection.commit()++ # Test update query, setting batch_start to 1+ update_query = f"SET title='{NEW_TITLE}'"+ updated_count = update_batches.function(+ dry_run=False,+ query_id=f"test_{identifier}",+ table_name=image_table,+ expected_row_count=2,+ batch_size=1,+ batch_start=1,+ update_query=update_query,+ update_timeout=3600,+ postgres_conn_id=sql.POSTGRES_CONN_ID,+ )++ # Only records B and C should have been updated+ assert updated_count == 2++ postgres_with_image_and_temp_table.cursor.execute(f"SELECT * FROM {image_table};")+ actual_rows = postgres_with_image_and_temp_table.cursor.fetchall()++ assert len(actual_rows) == 3+ # This is the first row, that was skipped by setting the batch_start to 1+ assert actual_rows[0][sql.fid_idx] == FID_A+ assert actual_rows[0][sql.title_idx] == OLD_TITLE++ # These are the updated rows+ assert actual_rows[1][sql.fid_idx] == FID_B+ assert actual_rows[1][sql.title_idx] == NEW_TITLE+ assert actual_rows[2][sql.fid_idx] == FID_C+ assert actual_rows[2][sql.title_idx] == NEW_TITLEdiff --git a/catalog/tests/test_utils/sql.py b/catalog/tests/test_utils/sql.pynew file mode 100644index 000000000..b58c11a4e--- /dev/null+++ b/catalog/tests/test_utils/sql.py@@ -0,0 +1,92 @@+import os+from collections import namedtuple+from unittest import mock++from airflow.models import TaskInstance++from common.constants import IMAGE+from common.loader.sql import TSV_COLUMNS, create_column_definitions+from common.storage import columns as col+from common.storage.db_columns import IMAGE_TABLE_COLUMNS+++POSTGRES_CONN_ID = os.getenv("TEST_CONN_ID")+POSTGRES_TEST_URI = os.getenv("AIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING")+S3_LOCAL_ENDPOINT = os.getenv("S3_LOCAL_ENDPOINT")+ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")+SECRET_KEY = os.getenv("AWS_SECRET_KEY")+++LOADING_TABLE_COLUMN_DEFINITIONS = create_column_definitions(+ TSV_COLUMNS[IMAGE], is_loading=True+)++CREATE_LOAD_TABLE_QUERY = f"""CREATE TABLE public.{{}} (+ {LOADING_TABLE_COLUMN_DEFINITIONS}+);"""++IMAGE_TABLE_COLUMN_DEFINITIONS = create_column_definitions(IMAGE_TABLE_COLUMNS)++CREATE_IMAGE_TABLE_QUERY = f"""CREATE TABLE public.{{}} (+ {IMAGE_TABLE_COLUMN_DEFINITIONS}+);"""++UNIQUE_CONDITION_QUERY = (+ "CREATE UNIQUE INDEX {table}_provider_fid_idx"+ " ON public.{table}"+ " USING btree (provider, md5(foreign_identifier));"+ "CREATE UNIQUE INDEX {table}_identifier_key"+ " ON public.{table}"+ " USING btree (identifier);"+ "CREATE UNIQUE INDEX {table}_url_key"+ " ON public.{table}"+ " USING btree (url);"+)+++PostgresRef = namedtuple("PostgresRef", ["cursor", "connection"])+ti = mock.Mock(spec=TaskInstance)+ti.xcom_pull.return_value = None++COLUMN_NAMES = [column.db_name for column in IMAGE_TABLE_COLUMNS]++# ids for main database columns+updated_idx = COLUMN_NAMES.index(col.UPDATED_ON.db_name)+ingestion_idx = COLUMN_NAMES.index(col.INGESTION_TYPE.db_name)+provider_idx = COLUMN_NAMES.index(col.PROVIDER.db_name)+source_idx = COLUMN_NAMES.index(col.SOURCE.db_name)+fid_idx = COLUMN_NAMES.index(col.FOREIGN_ID.db_name)+land_url_idx = COLUMN_NAMES.index(col.LANDING_URL.db_name)+url_idx = COLUMN_NAMES.index(col.DIRECT_URL.db_name)+thm_idx = COLUMN_NAMES.index(col.THUMBNAIL.db_name)+filesize_idx = COLUMN_NAMES.index(col.FILESIZE.db_name)+license_idx = COLUMN_NAMES.index(col.LICENSE.db_name)+version_idx = COLUMN_NAMES.index(col.LICENSE_VERSION.db_name)+creator_idx = COLUMN_NAMES.index(col.CREATOR.db_name)+creator_url_idx = COLUMN_NAMES.index(col.CREATOR_URL.db_name)+title_idx = COLUMN_NAMES.index(col.TITLE.db_name)+metadata_idx = COLUMN_NAMES.index(col.META_DATA.db_name)+tags_idx = COLUMN_NAMES.index(col.TAGS.db_name)+synced_idx = COLUMN_NAMES.index(col.LAST_SYNCED.db_name)+removed_idx = COLUMN_NAMES.index(col.REMOVED.db_name)+watermarked_idx = COLUMN_NAMES.index(col.WATERMARKED.db_name)+width_idx = COLUMN_NAMES.index(col.WIDTH.db_name)+height_idx = COLUMN_NAMES.index(col.HEIGHT.db_name)+standardized_popularity_idx = COLUMN_NAMES.index(col.STANDARDIZED_POPULARITY.db_name)+++def create_query_values(+ column_values: dict,+ columns=None,+):+ if columns is None:+ columns = TSV_COLUMNS[IMAGE]+ result = []+ for column in columns:+ val = column_values.get(column.db_name)+ if val is None:+ val = "null"+ else:+ val = f"'{str(val)}'"+ result.append(val)+ return ",".join(result)