Skip to content

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

Store catalog XComs as JSON instead of pickles (#5813)

Olga Bulat33238021aa3f
diff --git a/catalog/Dockerfile b/catalog/Dockerfile
index b88ac0afe..24c4a1043 100644
--- a/catalog/Dockerfile
+++ b/catalog/Dockerfile
@@ -30,7 +30,6 @@ ENV OUTPUT_DIR=/var/workflow_output/
ENV AIRFLOW__CORE__DAGS_FOLDER=${DAGS_FOLDER}
ENV AIRFLOW__CORE__LOAD_EXAMPLES=False
ENV AIRFLOW__CORE__LOAD_DEFAULT_CONNECTIONS=False
-ENV AIRFLOW__CORE__ENABLE_XCOM_PICKLING=True
ENV AIRFLOW__WEBSERVER__EXPOSE_STACKTRACE=True
# TODO: Test if moving this to .env changes anything!
diff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.py
index 2c55cd840..97e80a254 100644
--- a/catalog/dags/common/elasticsearch.py
+++ b/catalog/dags/common/elasticsearch.py
@@ -127,7 +127,7 @@ def get_record_count_group_by_sources(es_host: str, index: str):
def create_index(index_config, es_host: str):
es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
- new_index = es_conn.indices.create(**index_config)
+ new_index = es_conn.indices.create(**index_config).body
return new_index
@@ -254,7 +254,7 @@ def trigger_and_wait_for_reindex(
@task
def refresh_index(es_host: str, index_name: str):
es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
- return es_conn.indices.refresh(index=index_name)
+ return es_conn.indices.refresh(index=index_name).body
@task_group(group_id="point_alias")
diff --git a/catalog/dags/common/loader/reporting.py b/catalog/dags/common/loader/reporting.py
index 015b66d5e..779c510f8 100644
--- a/catalog/dags/common/loader/reporting.py
+++ b/catalog/dags/common/loader/reporting.py
@@ -44,6 +44,17 @@ class RecordMetrics(NamedTuple):
MediaTypeRecordMetrics = dict[str, RecordMetrics]
+# The load task's RecordMetrics as a downstream task receives them. XComs are stored
+# as JSON, so each value comes back as a plain list (or a tuple, when the value didn't
+# go through an XCom).
+SerializedRecordMetrics = RecordMetrics | Sequence[int | None] | None
+SerializedMediaTypeRecordMetrics = dict[str, SerializedRecordMetrics]
+
+
+def _as_record_metrics(counts: SerializedRecordMetrics) -> RecordMetrics | None:
+ if counts is None or isinstance(counts, RecordMetrics):
+ return counts
+ return RecordMetrics(*counts)
def humanize_time_duration(seconds: float | int) -> str:
@@ -72,19 +83,28 @@ def clean_duration(duration: float | list[float] | None) -> str | None:
def clean_record_counts(
- record_counts_by_media_type: MediaTypeRecordMetrics | list[MediaTypeRecordMetrics],
+ record_counts_by_media_type: SerializedMediaTypeRecordMetrics
+ | list[SerializedMediaTypeRecordMetrics],
media_types: Sequence[str],
) -> MediaTypeRecordMetrics:
# If a list of record_counts dicts is provided, sum all of the individual values
if isinstance(record_counts_by_media_type, list):
return {
media_type: sum(
- (x[media_type] for x in record_counts_by_media_type),
+ (
+ _as_record_metrics(x[media_type])
+ for x in record_counts_by_media_type
+ ),
RecordMetrics(0, 0, 0, 0),
)
for media_type in media_types
}
- return record_counts_by_media_type
+ if not record_counts_by_media_type:
+ return record_counts_by_media_type
+ return {
+ media_type: _as_record_metrics(counts)
+ for media_type, counts in record_counts_by_media_type.items()
+ }
def skip_report_completion(
@@ -133,7 +153,8 @@ def report_completion(
dag_id: str,
media_types: Sequence[str],
duration: float | str | list[float] | None,
- record_counts_by_media_type: MediaTypeRecordMetrics | list[MediaTypeRecordMetrics],
+ record_counts_by_media_type: SerializedMediaTypeRecordMetrics
+ | list[SerializedMediaTypeRecordMetrics],
dated: bool = False,
date_range_start: str | None = None,
date_range_end: str | None = None,
diff --git a/catalog/dags/common/log_cleanup.py b/catalog/dags/common/log_cleanup.py
index 86df8537f..43d975bea 100644
--- a/catalog/dags/common/log_cleanup.py
+++ b/catalog/dags/common/log_cleanup.py
@@ -91,7 +91,7 @@ def clean_up(
max_log_age_in_days: int | str,
should_delete: bool | str,
**kwargs,
-) -> list[Path]:
+) -> list[str]:
"""
Find and delete all log folders that were modified more than `max_log_age_in_days`.
@@ -160,7 +160,7 @@ def clean_up(
f"\nRun this DAG with ENABLE_DELETE set to True "
f"to free {size_to_delete:.2f} MB."
)
- return folders_to_delete
+ return [str(folder) for folder in folders_to_delete]
if __name__ == "__main__":
diff --git a/catalog/dags/data_augmentation/rekognition/add_rekognition_labels.py b/catalog/dags/data_augmentation/rekognition/add_rekognition_labels.py
index 15b454c81..1f0493a13 100644
--- a/catalog/dags/data_augmentation/rekognition/add_rekognition_labels.py
+++ b/catalog/dags/data_augmentation/rekognition/add_rekognition_labels.py
@@ -146,11 +146,11 @@ def parse_and_insert_labels(
Variable.delete(constants.CURRENT_POS_VAR_NAME)
return types.ParseResults(
- total_processed,
- total_skipped,
- len(failed_records),
+ total_processed=total_processed,
+ total_skipped=total_skipped,
+ total_failed=len(failed_records),
# Only share a sample of the failed records
- failed_records[:5],
+ failed_records_sample=failed_records[:5],
)
@@ -158,13 +158,15 @@ def parse_and_insert_labels(
def notify_parse_complete(results: types.ParseResults):
message = f"""
Rekognition label parsing complete :rocket:
-*Total processed:* {results.total_processed:,}
-*Total skipped:* {results.total_skipped:,}
-*Total failed:* {results.total_failed:,}
+*Total processed:* {results["total_processed"]:,}
+*Total skipped:* {results["total_skipped"]:,}
+*Total failed:* {results["total_failed"]:,}
"""
- if results.failed_records_sample:
+ if results["failed_records_sample"]:
message += "*Failed records sample*:\n"
- message += "\n".join([f" - `{rec}`" for rec in results.failed_records_sample])
+ message += "\n".join(
+ [f" - `{rec}`" for rec in results["failed_records_sample"]]
+ )
slack.send_message(
message,
diff --git a/catalog/dags/data_augmentation/rekognition/types.py b/catalog/dags/data_augmentation/rekognition/types.py
index 4ce50042a..05ee37091 100644
--- a/catalog/dags/data_augmentation/rekognition/types.py
+++ b/catalog/dags/data_augmentation/rekognition/types.py
@@ -1,5 +1,5 @@
# Type definitions for the sample data
-from typing import NamedTuple, TypedDict
+from typing import TypedDict
from psycopg2.extras import Json
@@ -27,7 +27,7 @@ class MachineGeneratedTag(TypedDict):
provider: str
-class ParseResults(NamedTuple):
+class ParseResults(TypedDict):
total_processed: int
total_skipped: int
total_failed: int
diff --git a/catalog/dags/data_refresh/promote_table.py b/catalog/dags/data_refresh/promote_table.py
index a795b9414..082f78707 100644
--- a/catalog/dags/data_refresh/promote_table.py
+++ b/catalog/dags/data_refresh/promote_table.py
@@ -35,7 +35,7 @@ def get_go_live_query(
restore_index_names = ("\n ").join(
[
queries.RENAME_INDEX_QUERY.format(
- old_name=index.temp_index_name, new_name=index.index_name
+ old_name=index["temp_index_name"], new_name=index["index_name"]
)
for index in index_mapping
]
diff --git a/catalog/dags/data_refresh/remap_table_constraints.py b/catalog/dags/data_refresh/remap_table_constraints.py
index 74419188c..544de6adc 100644
--- a/catalog/dags/data_refresh/remap_table_constraints.py
+++ b/catalog/dags/data_refresh/remap_table_constraints.py
@@ -6,7 +6,7 @@ This file contains TaskGroups related to remapping the table constraints from th
"""
import logging
-from typing import NamedTuple
+from typing import TypedDict
from airflow.decorators import task, task_group
@@ -17,16 +17,18 @@ from data_refresh import queries
logger = logging.getLogger(__name__)
-class ConstraintInfo(NamedTuple):
+class ConstraintInfo(TypedDict):
table: str
name: str
statement: str
-def fetch_all_tuples(cursor):
+def fetch_all_constraints(cursor):
try:
rows = cursor.fetchall()
- return [ConstraintInfo(row[0], row[1], row[2]) for row in rows]
+ return [
+ ConstraintInfo(table=row[0], name=row[1], statement=row[2]) for row in rows
+ ]
except Exception as e:
raise ValueError("Unable to extract expected row data from cursor") from e
@@ -55,18 +57,18 @@ def _remap_constraint(
# In all cases, drop the existing constraint
alterations = [
queries.DROP_CONSTRAINT_QUERY.format(
- constraint_table=constraint.table, constraint_name=constraint.name
+ constraint_table=constraint["table"], constraint_name=constraint["name"]
)
]
# If the constraint was applied directly to the media table, then
# we now apply it to the temp table instead
- if constraint.table == table_name:
+ if constraint["table"] == table_name:
alterations.append(
queries.ADD_CONSTRAINT_QUERY.format(
- constraint_name=constraint.name,
+ constraint_name=constraint["name"],
constraint_table=temp_table_name,
- constraint_statement=constraint.statement,
+ constraint_statement=constraint["statement"],
)
)
@@ -74,7 +76,7 @@ def _remap_constraint(
# we add it back to its original table, but altered to reference the temp table
# instead.
else:
- tokens = constraint.statement.split(" ")
+ tokens = constraint["statement"].split(" ")
# Point the constraint to the new table by replacing the referenced table name (always
# appears after the word `REFERENCES`) with the temp table.
@@ -86,8 +88,8 @@ def _remap_constraint(
alterations.append(
queries.ADD_CONSTRAINT_QUERY.format(
- constraint_table=constraint.table,
- constraint_name=constraint.name,
+ constraint_table=constraint["table"],
+ constraint_name=constraint["name"],
constraint_statement=new_constraint_statement,
)
)
@@ -161,11 +163,11 @@ def generate_constraints_for_table(
# which may reference it from another table (foreign key constraints).
# Ignore PRIMARY KEY statements and UNIQUE statements, which are already
# enforced via the table indices copied in an earlier task
- is_fk = _is_foreign_key(constraint.statement, table_name)
+ is_fk = _is_foreign_key(constraint["statement"], table_name)
if (
- (constraint.table == table_name or is_fk)
- and "PRIMARY KEY" not in constraint.statement
- and "UNIQUE" not in constraint.statement
+ (constraint["table"] == table_name or is_fk)
+ and "PRIMARY KEY" not in constraint["statement"]
+ and "UNIQUE" not in constraint["statement"]
):
# Generate the `ALTER TABLE...` statements needed to drop this constraint
# from the live table and apply it to the temp table.
@@ -180,7 +182,7 @@ def generate_constraints_for_table(
# to ensure no records persist which reference deleted media.
if is_fk:
delete_orphans = _generate_delete_orphans(
- constraint.statement, constraint.table, temp_table_name
+ constraint["statement"], constraint["table"], temp_table_name
)
drop_orphans.append(delete_orphans)
@@ -208,7 +210,7 @@ def remap_table_constraints_to_table(
all_constraints = run_sql.override(task_id="get_all_existing_constraints")(
postgres_conn_id=postgres_conn_id,
sql_template=queries.SELECT_ALL_CONSTRAINTS_QUERY,
- handler=fetch_all_tuples,
+ handler=fetch_all_constraints,
map_index_template=table_name,
)
diff --git a/catalog/dags/data_refresh/remap_table_indices.py b/catalog/dags/data_refresh/remap_table_indices.py
index d93bca6a8..5c69b8362 100644
--- a/catalog/dags/data_refresh/remap_table_indices.py
+++ b/catalog/dags/data_refresh/remap_table_indices.py
@@ -5,7 +5,7 @@ This file contains TaskGroups related to rmampping the table indices from the li
"""
import logging
-from typing import NamedTuple
+from typing import TypedDict
from airflow.decorators import task, task_group
@@ -16,7 +16,7 @@ from data_refresh import queries
logger = logging.getLogger(__name__)
-class TableIndex(NamedTuple):
+class TableIndex(TypedDict):
index_name: str
temp_index_name: str
index_def: str
@@ -56,7 +56,11 @@ def _transform_index_def(
schema_name, table_name = tokens[table_name_idx].split(".", maxsplit=1)
tokens[table_name_idx] = f"{schema_name}.{temp_table_name}"
- return TableIndex(old_index_name, temp_index_name, " ".join(tokens))
+ return TableIndex(
+ index_name=old_index_name,
+ temp_index_name=temp_index_name,
+ index_def=" ".join(tokens),
+ )
@task(map_index_template="{{ task.op_kwargs['table_name'] }}")
@@ -79,14 +83,14 @@ def create_table_indices(
):
logger.info(f"Creating indices for `{table_name}`.'")
for index_config in index_configs:
- if "(id)" in index_config.index_def:
+ if "(id)" in index_config["index_def"]:
# Skip the primary key index, as this already exists
- logger.info(f"Skipping adding {index_config.index_name} index.")
+ logger.info(f"Skipping adding {index_config['index_name']} index.")
continue
# Create the index
run_sql.function(
- postgres_conn_id=postgres_conn_id, sql_template=index_config.index_def
+ postgres_conn_id=postgres_conn_id, sql_template=index_config["index_def"]
)
return index_configs
diff --git a/catalog/tests/conftest.py b/catalog/tests/conftest.py
index c9f0c6a6e..5ce12d004 100644
--- a/catalog/tests/conftest.py
+++ b/catalog/tests/conftest.py
@@ -1,11 +1,22 @@
# Registers the FAB `ab_user` table that `task_instance_note` references; without it,
# deleting task instances fails to resolve the foreign key.
+import json
+
import airflow.providers.fab.auth_manager.models # noqa: F401
import pytest
from airflow.models import DagRun, Pool, TaskInstance
+from airflow.utils.json import XComDecoder, XComEncoder
from airflow.utils.session import create_session
+def xcom_round_trip(value):
+ """
+ Return `value` as a downstream task receives it, after Airflow stores it as a JSON
+ XCom. Tuples, including NamedTuples, come back as lists.
+ """
+ return json.loads(json.dumps(value, cls=XComEncoder), cls=XComDecoder)
+
+
def pytest_addoption(parser):
"""
Add options to pytest.
diff --git a/catalog/tests/dags/common/loader/test_reporting.py b/catalog/tests/dags/common/loader/test_reporting.py
index 7c5d482dc..1fd77d882 100644
--- a/catalog/tests/dags/common/loader/test_reporting.py
+++ b/catalog/tests/dags/common/loader/test_reporting.py
@@ -11,6 +11,7 @@ from common.loader.reporting import (
report_completion,
skip_report_completion,
)
+from tests.conftest import xcom_round_trip
@pytest.fixture(autouse=True)
@@ -390,8 +391,38 @@ def test_skip_report_completion(
["image", "audio"],
{"image": RecordMetrics(5, 5, 5, 5), "audio": RecordMetrics(12, 5, 7, 2)},
),
+ # Single, as deserialized from a JSON XCom
+ (
+ {"image": [1, 2, 3, 4], "audio": None},
+ ["image", "audio"],
+ {"image": RecordMetrics(1, 2, 3, 4), "audio": None},
+ ),
+ # Multiple, as deserialized from JSON XComs
+ (
+ [
+ {"image": [1, 2, 3, 4], "audio": None},
+ {"image": [4, 3, 2, 1], "audio": [1, None, 0, 0]},
+ ],
+ ["image", "audio"],
+ {"image": RecordMetrics(5, 5, 5, 5), "audio": RecordMetrics(1, 0, 0, 0)},
+ ),
],
)
def test_clean_record_counts(record_counts_by_media_type, media_types, expected):
actual = clean_record_counts(record_counts_by_media_type, media_types)
assert actual == expected
+ for counts in (actual or {}).values():
+ assert counts is None or isinstance(counts, RecordMetrics)
+
+
+def test_clean_record_counts_reads_metrics_from_xcom():
+ single_run = xcom_round_trip({"image": RecordMetrics(10, 1, 2, 3)})
+ reingestion = xcom_round_trip([single_run, {"image": RecordMetrics(1, 0, 0, 0)}])
+
+ assert clean_record_counts(single_run, ["image"]) == {
+ "image": RecordMetrics(10, 1, 2, 3)
+ }
+ assert clean_record_counts(reingestion, ["image"]) == {
+ "image": RecordMetrics(11, 1, 2, 3)
+ }
+ assert clean_record_counts(single_run, ["image"])["image"].upserted == 10
diff --git a/catalog/tests/dags/data_augmentation/rekognition/test_add_rekognition_labels.py b/catalog/tests/dags/data_augmentation/rekognition/test_add_rekognition_labels.py
index a1e6ebc3e..833ea1a67 100644
--- a/catalog/tests/dags/data_augmentation/rekognition/test_add_rekognition_labels.py
+++ b/catalog/tests/dags/data_augmentation/rekognition/test_add_rekognition_labels.py
@@ -3,6 +3,7 @@ from unittest import mock
import pytest
import smart_open.s3
+from tests.conftest import xcom_round_trip
from data_augmentation.rekognition import add_rekognition_labels, constants
from data_augmentation.rekognition.label_mapping import LABEL_MAPPING
@@ -72,7 +73,12 @@ def test_parse_and_insert_labels_parse(mock_variable, mock_insert_tags, mock_fil
]
actual = add_rekognition_labels.parse_and_insert_labels.function(**DEFAULT_ARGS)
- assert actual == ParseResults(3, 1, 1, ["this line should fail!"])
+ assert actual == ParseResults(
+ total_processed=3,
+ total_skipped=1,
+ total_failed=1,
+ failed_records_sample=["this line should fail!"],
+ )
mock_insert_tags.assert_called_once()
assert (
# Check the first image UUID
@@ -126,7 +132,30 @@ def test_parse_and_insert_labels_buffer_config(
**{**DEFAULT_ARGS, "in_memory_buffer_size": in_memory_buffer_size}
)
- assert actual == ParseResults(expected_processed, expected_skipped, 0, [])
+ assert actual == ParseResults(
+ total_processed=expected_processed,
+ total_skipped=expected_skipped,
+ total_failed=0,
+ failed_records_sample=[],
+ )
assert mock_insert_tags.call_count == expected_insert_call_count
assert mock_variable.set.call_count == expected_insert_call_count - 1
mock_variable.delete.assert_called_once()
+
+
+def test_notify_parse_complete_reads_results_from_xcom():
+ results = xcom_round_trip(
+ ParseResults(
+ total_processed=1200,
+ total_skipped=3,
+ total_failed=1,
+ failed_records_sample=["bad line"],
+ )
+ )
+
+ with mock.patch.object(add_rekognition_labels.slack, "send_message") as send:
+ add_rekognition_labels.notify_parse_complete.function(results)
+
+ message = send.call_args.args[0]
+ assert "*Total processed:* 1,200" in message
+ assert " - `bad line`" in message
diff --git a/catalog/tests/dags/data_refresh/test_remap_table_constraints.py b/catalog/tests/dags/data_refresh/test_remap_table_constraints.py
index 243a2ca1b..b61962567 100644
--- a/catalog/tests/dags/data_refresh/test_remap_table_constraints.py
+++ b/catalog/tests/dags/data_refresh/test_remap_table_constraints.py
@@ -1,38 +1,51 @@
from textwrap import dedent
+from unittest import mock
import pytest
from data_refresh.remap_table_constraints import (
ConstraintInfo,
+ fetch_all_constraints,
generate_constraints_for_table,
)
+from tests.conftest import xcom_round_trip
# Constraint that does not apply to or reference the table_name table
INAPPLICABLE_CONSTRAINT = ConstraintInfo(
- "image", "irrelevant_constraint", "CHECK (char_length(foo) = 5)"
+ table="image",
+ name="irrelevant_constraint",
+ statement="CHECK (char_length(foo) = 5)",
)
# Foreign key constraint that does not apply to or reference the table_name table
INAPPLICABLE_FOREIGN_KEY_CONSTRAINT = ConstraintInfo(
- "imagelist_images",
- "imagelist_images_image_id_fkey",
- "FOREIGN KEY (image_id) REFERENCES image(id) DEFERRABLE INITIALLY DEFERRED",
+ table="imagelist_images",
+ name="imagelist_images_image_id_fkey",
+ statement="FOREIGN KEY (image_id) REFERENCES image(id) DEFERRABLE INITIALLY DEFERRED",
)
# Primary key constraint; no alters should be generated
-PRIMARY_KEY_CONSTRAINT = ConstraintInfo("audio", "audio_pkey", "PRIMARY KEY (id)")
+PRIMARY_KEY_CONSTRAINT = ConstraintInfo(
+ table="audio",
+ name="audio_pkey",
+ statement="PRIMARY KEY (id)",
+)
# Unique constraint; no alters should be generated
-UNIQUE_CONSTRAINT = ConstraintInfo("audio", "audio_url_key", "UNIQUE (url)")
+UNIQUE_CONSTRAINT = ConstraintInfo(
+ table="audio",
+ name="audio_url_key",
+ statement="UNIQUE (url)",
+)
# Constraint that applies to the table_name and should have alters generated
APPLICABLE_CONSTRAINT = ConstraintInfo(
- "audio",
- "example_check_constraint",
- "CHECK (char_length(title) > 5)",
+ table="audio",
+ name="example_check_constraint",
+ statement="CHECK (char_length(title) > 5)",
)
# Foreign key constraint for which alters and drop_orphans should be generated
APPLICABLE_FOREIGN_KEY_CONSTRAINT = ConstraintInfo(
- "audiolist_audios",
- "audiolist_audios_audio_id_fkey",
- "FOREIGN KEY (audio_id) REFERENCES audio(id) DEFERRABLE INITIALLY DEFERRED",
+ table="audiolist_audios",
+ name="audiolist_audios_audio_id_fkey",
+ statement="FOREIGN KEY (audio_id) REFERENCES audio(id) DEFERRABLE INITIALLY DEFERRED",
)
EXPECTED_DROP_ORPHANS_STATEMENT = dedent(
@@ -113,3 +126,29 @@ def test_generate_constraints_for_table(all_constraints, expected_alter_statemen
all_constraints, "audio", "temp_import_audio"
)
assert actual == expected_alter_statements
+
+
+def test_constraints_survive_xcom():
+ cursor = mock.MagicMock()
+ cursor.fetchall.return_value = [
+ (
+ constraint["table"],
+ constraint["name"],
+ constraint["statement"],
+ )
+ for constraint in [APPLICABLE_CONSTRAINT, PRIMARY_KEY_CONSTRAINT]
+ ]
+
+ all_constraints = xcom_round_trip(fetch_all_constraints(cursor))
+ actual = generate_constraints_for_table.function(
+ all_constraints=all_constraints,
+ table_name="audio",
+ temp_table_name="temp_import_audio",
+ )
+
+ assert actual == generate_constraints_for_table.function(
+ all_constraints=[APPLICABLE_CONSTRAINT],
+ table_name="audio",
+ temp_table_name="temp_import_audio",
+ )
+ assert actual
diff --git a/catalog/tests/dags/data_refresh/test_remap_table_indices.py b/catalog/tests/dags/data_refresh/test_remap_table_indices.py
index 14e6c2490..daac087a7 100644
--- a/catalog/tests/dags/data_refresh/test_remap_table_indices.py
+++ b/catalog/tests/dags/data_refresh/test_remap_table_indices.py
@@ -2,11 +2,13 @@ from unittest.mock import call, patch
import pytest
+from data_refresh.promote_table import get_go_live_query
from data_refresh.remap_table_indices import (
TableIndex,
create_table_indices,
transform_index_defs,
)
+from tests.conftest import xcom_round_trip
@pytest.mark.parametrize(
@@ -25,21 +27,21 @@ from data_refresh.remap_table_indices import (
],
[
TableIndex(
- "image_provider_7d11f847",
- "temp_import_image_provider_7d11f847",
- "CREATE INDEX temp_import_image_provider_7d11f847 ON"
+ index_name="image_provider_7d11f847",
+ temp_index_name="temp_import_image_provider_7d11f847",
+ index_def="CREATE INDEX temp_import_image_provider_7d11f847 ON"
" public.temp_import_image USING btree (provider)",
),
TableIndex(
- "image_identifier_key",
- "temp_import_image_identifier_key",
- "CREATE UNIQUE INDEX temp_import_image_identifier_key ON"
+ index_name="image_identifier_key",
+ temp_index_name="temp_import_image_identifier_key",
+ index_def="CREATE UNIQUE INDEX temp_import_image_identifier_key ON"
" public.temp_import_image USING btree (identifier)",
),
TableIndex(
- "image_pkey",
- "temp_import_image_pkey",
- "CREATE UNIQUE INDEX temp_import_image_pkey ON"
+ index_name="image_pkey",
+ temp_index_name="temp_import_image_pkey",
+ index_def="CREATE UNIQUE INDEX temp_import_image_pkey ON"
" public.temp_import_image USING btree (id)",
),
],
@@ -65,9 +67,9 @@ def test_transform_index_defs(existing_index_defs, expected_index_defs):
(
[
TableIndex(
- "image_pkey",
- "temp_import_image_pkey",
- "CREATE UNIQUE INDEX temp_import_image_pk ON"
+ index_name="image_pkey",
+ temp_index_name="temp_import_image_pkey",
+ index_def="CREATE UNIQUE INDEX temp_import_image_pk ON"
" public.temp_import_image USING btree (id)",
),
],
@@ -77,9 +79,9 @@ def test_transform_index_defs(existing_index_defs, expected_index_defs):
(
[
TableIndex(
- "image_provider_7d11f847",
- "temp_import_image_provider_7d11f847",
- "CREATE INDEX temp_import_image_provider_7d11f847 ON"
+ index_name="image_provider_7d11f847",
+ temp_index_name="temp_import_image_provider_7d11f847",
+ index_def="CREATE INDEX temp_import_image_provider_7d11f847 ON"
" public.temp_import_image USING btree (provider)",
),
],
@@ -92,21 +94,21 @@ def test_transform_index_defs(existing_index_defs, expected_index_defs):
(
[
TableIndex(
- "image_provider_7d11f847",
- "temp_import_image_provider_7d11f847",
- "CREATE INDEX temp_import_image_provider_7d11f847 ON"
+ index_name="image_provider_7d11f847",
+ temp_index_name="temp_import_image_provider_7d11f847",
+ index_def="CREATE INDEX temp_import_image_provider_7d11f847 ON"
" public.temp_import_image USING btree (provider)",
),
TableIndex(
- "image_identifier_key",
- "temp_import_image_identifier_key",
- "CREATE UNIQUE INDEX temp_import_image_identifier_key ON"
+ index_name="image_identifier_key",
+ temp_index_name="temp_import_image_identifier_key",
+ index_def="CREATE UNIQUE INDEX temp_import_image_identifier_key ON"
" public.temp_import_image USING btree (identifier)",
),
TableIndex(
- "image_pkey",
- "temp_import_image_pkey",
- "CREATE UNIQUE INDEX temp_import_image_pk ON"
+ index_name="image_pkey",
+ temp_index_name="temp_import_image_pkey",
+ index_def="CREATE UNIQUE INDEX temp_import_image_pk ON"
" public.temp_import_image USING btree (id)",
),
],
@@ -130,3 +132,37 @@ def test_create_table_indices(index_configs, expected_sql):
]
run_sql_mock.assert_has_calls(expected_calls)
+
+
+def test_index_configs_survive_xcom():
+ index_configs = xcom_round_trip(
+ transform_index_defs.function(
+ existing_index_defs=[
+ "CREATE INDEX image_provider_7d11f847 ON public.image USING btree (provider)",
+ "CREATE UNIQUE INDEX image_pkey ON public.image USING btree (id)",
+ ],
+ temp_table_name="temp_import_image",
+ table_name="image",
+ )
+ )
+
+ with patch("common.sql.run_sql.function") as run_sql_mock:
+ returned = create_table_indices.function(
+ postgres_conn_id="test_id", index_configs=index_configs, table_name="image"
+ )
+ run_sql_mock.assert_called_once_with(
+ postgres_conn_id="test_id",
+ sql_template="CREATE INDEX temp_import_image_provider_7d11f847 ON"
+ " public.temp_import_image USING btree (provider)",
+ )
+
+ go_live_query = get_go_live_query.function(
+ table_name="image",
+ temp_table_name="temp_import_image",
+ index_mapping=xcom_round_trip(returned),
+ )
+ assert (
+ "ALTER INDEX temp_import_image_provider_7d11f847"
+ " RENAME TO image_provider_7d11f847;" in go_live_query
+ )
+ assert "ALTER INDEX temp_import_image_pkey RENAME TO image_pkey;" in go_live_query