Skip to content

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

Add filtered index and promotion steps to data refresh (#4833)

Staci Mullins8b2f037b1884
diff --git a/catalog/dags/common/sql.py b/catalog/dags/common/sql.py
index 6a6e7ec09..33d8fac0f 100644
--- a/catalog/dags/common/sql.py
+++ b/catalog/dags/common/sql.py
@@ -40,6 +40,14 @@ def single_value(cursor):
raise ValueError("Unable to extract expected row data from cursor") from e
+def fetch_all(cursor):
+ try:
+ rows = cursor.fetchall()
+ return [row[0] for row in rows]
+ except Exception as e:
+ raise ValueError("Unable to extract expected row data from cursor") from e
+
+
class PostgresHook(UpstreamPostgresHook):
"""
PostgresHook that sets the database timeout on any query to match the airflow task
diff --git a/catalog/dags/data_refresh/copy_data.py b/catalog/dags/data_refresh/copy_data.py
index eecda7b3e..76f357244 100644
--- a/catalog/dags/data_refresh/copy_data.py
+++ b/catalog/dags/data_refresh/copy_data.py
@@ -25,7 +25,7 @@ from common.constants import (
PRODUCTION,
Environment,
)
-from common.sql import RETURN_ROW_COUNT, PostgresHook
+from common.sql import PostgresHook, run_sql
from data_refresh import queries
from data_refresh.data_refresh_types import DataRefreshConfig
@@ -36,28 +36,7 @@ logger = logging.getLogger(__name__)
DEFAULT_DATA_REFRESH_LIMIT = 10_000
-@task
-def _run_sql(
- postgres_conn_id: str,
- sql_template: str,
- task: AbstractOperator = None,
- timeout: float = None,
- handler: callable = RETURN_ROW_COUNT,
- **kwargs,
-):
- query = sql_template.format(**kwargs)
-
- postgres = PostgresHook(
- postgres_conn_id=postgres_conn_id,
- default_statement_timeout=(
- timeout if timeout else PostgresHook.get_execution_timeout(task)
- ),
- )
-
- return postgres.run(query, handler=handler)
-
-
-@task
+@task(max_active_tis_per_dagrun=1)
def initialize_fdw(
upstream_conn_id: str,
downstream_conn_id: str,
@@ -66,7 +45,7 @@ def initialize_fdw(
"""Create the FDW and prepare it for copying."""
upstream_connection = Connection.get_connection_from_secrets(upstream_conn_id)
- _run_sql.function(
+ run_sql.function(
postgres_conn_id=downstream_conn_id,
sql_template=queries.CREATE_FDW_QUERY,
task=task,
@@ -78,7 +57,10 @@ def initialize_fdw(
)
-@task(map_index_template="{{ task.op_kwargs['upstream_table_name'] }}")
+@task(
+ max_active_tis_per_dagrun=1,
+ map_index_template="{{ task.op_kwargs['upstream_table_name'] }}",
+)
def create_schema(downstream_conn_id: str, upstream_table_name: str) -> str:
"""
Create a new schema in the downstream DB through which the upstream table
@@ -104,7 +86,7 @@ def get_record_limit() -> int | None:
Airflow is running.
If a limit is explicitly configured, it is always used. Otherwise, production
- defaults to no limit, and all other environments default to 100,000.
+ defaults to no limit, and all other environments default to 10,000.
"""
try:
# If a limit is explicitly configured, always use it.
@@ -122,7 +104,10 @@ def get_record_limit() -> int | None:
return DEFAULT_DATA_REFRESH_LIMIT
-@task(map_index_template="{{ task.op_kwargs['upstream_table_name'] }}")
+@task(
+ max_active_tis_per_dagrun=1,
+ map_index_template="{{ task.op_kwargs['upstream_table_name'] }}",
+)
def get_shared_columns(
upstream_conn_id: str,
downstream_conn_id: str,
@@ -181,7 +166,7 @@ def copy_data(
LIMIT {limit};"""
)
- return _run_sql.function(
+ return run_sql.function(
postgres_conn_id=postgres_conn_id,
sql_template=sql_template,
task=task,
@@ -223,7 +208,7 @@ def copy_upstream_table(
upstream_table_name=upstream_table_name,
)
- create_temp_table = _run_sql.override(
+ create_temp_table = run_sql.override(
task_id="create_temp_table",
map_index_template="{{ task.op_kwargs['temp_table_name'] }}",
)(
@@ -233,7 +218,7 @@ def copy_upstream_table(
downstream_table_name=downstream_table_name,
)
- setup_id_columns = _run_sql.override(
+ setup_id_columns = run_sql.override(
task_id="setup_id_columns",
map_index_template="{{ task.op_kwargs['temp_table_name'] }}",
)(
@@ -242,7 +227,7 @@ def copy_upstream_table(
temp_table_name=temp_table_name,
)
- setup_tertiary_columns = _run_sql.override(
+ setup_tertiary_columns = run_sql.override(
task_id="setup_tertiary_columns",
map_index_template="{{ task.op_kwargs['temp_table_name'] }}",
)(
@@ -262,7 +247,7 @@ def copy_upstream_table(
columns=shared_cols,
)
- add_primary_key = _run_sql.override(
+ add_primary_key = run_sql.override(
task_id="add_primary_key",
map_index_template="{{ task.op_kwargs['temp_table_name'] }}",
)(
@@ -293,7 +278,7 @@ def copy_upstream_tables(
downstream_conn_id = POSTGRES_API_CONN_IDS.get(target_environment)
upstream_conn_id = POSTGRES_CONN_ID
- create_fdw = _run_sql.override(task_id="create_fdw")(
+ create_fdw = run_sql.override(task_id="create_fdw")(
postgres_conn_id=downstream_conn_id,
sql_template=queries.CREATE_FDW_EXTENSION_QUERY,
)
@@ -313,7 +298,7 @@ def copy_upstream_tables(
limit=limit,
).expand_kwargs([asdict(tm) for tm in data_refresh_config.table_mappings])
- drop_fdw = _run_sql.override(task_id="drop_fdw")(
+ drop_fdw = run_sql.override(task_id="drop_fdw")(
postgres_conn_id=downstream_conn_id,
sql_template=queries.DROP_SERVER_QUERY,
)
diff --git a/catalog/dags/data_refresh/create_and_populate_filtered_index.py b/catalog/dags/data_refresh/create_and_populate_filtered_index.py
new file mode 100644
index 000000000..acb47f00e
--- /dev/null
+++ b/catalog/dags/data_refresh/create_and_populate_filtered_index.py
@@ -0,0 +1,105 @@
+"""
+# Create and Promote Index
+
+This file contains TaskGroups related to creating and populating the filtered Elasticsearch indices
+as part of the Data Refresh.
+
+TODO: We'll swap out the create and populate filtered index DAG to use this instead
+of the one defined in the legacy_data_refresh.
+"""
+
+import logging
+import uuid
+from datetime import timedelta
+
+from airflow.decorators import task, task_group
+from airflow.providers.http.operators.http import HttpOperator
+from airflow.utils.trigger_rule import TriggerRule
+from requests import Response
+
+from common import elasticsearch as es
+from common.constants import MediaType
+from data_refresh.es_mapping import index_settings
+
+
+logger = logging.getLogger(__name__)
+
+SENSITIVE_TERMS_CONN_ID = "sensitive_terms"
+
+
+def response_filter_sensitive_terms_endpoint(response: Response) -> list[str]:
+ return [term.decode("utf-8").strip() for term in response.iter_lines()]
+
+
+@task(trigger_rule=TriggerRule.NONE_FAILED)
+def get_filtered_index_name(media_type: str, destination_index_name: str) -> str:
+ # If a destination index name is explicitly passed, use it.
+ if destination_index_name:
+ return destination_index_name
+
+ # Otherwise, generate an index name with a new UUID. This is useful when
+ # filtered index creation is run outside of a data refresh, because it
+ # avoids naming collisions when a filtered index already exists.
+ logger.info("Generating new destination index name.")
+ return f"{media_type}-{uuid.uuid4().hex}-filtered"
+
+
+@task_group(group_id="create_and_populate_filtered_index")
+def create_and_populate_filtered_index(
+ es_host: str,
+ media_type: MediaType,
+ origin_index_name: str,
+ timeout: timedelta,
+ destination_index_name: str | None = None,
+):
+ """
+ Create and populate a filtered index based on the given origin index, excluding
+ documents with sensitive terms.
+ """
+ filtered_index_name = get_filtered_index_name(
+ media_type=media_type, destination_index_name=destination_index_name
+ )
+
+ create_filtered_index = es.create_index.override(
+ trigger_rule=TriggerRule.NONE_FAILED,
+ )(
+ index_config={
+ "index": filtered_index_name,
+ "body": index_settings(media_type),
+ },
+ es_host=es_host,
+ )
+
+ sensitive_terms = HttpOperator(
+ task_id="get_sensitive_terms",
+ http_conn_id=SENSITIVE_TERMS_CONN_ID,
+ method="GET",
+ response_check=lambda response: response.status_code == 200,
+ response_filter=response_filter_sensitive_terms_endpoint,
+ trigger_rule=TriggerRule.NONE_FAILED,
+ )
+
+ populate_filtered_index = es.trigger_and_wait_for_reindex(
+ es_host=es_host,
+ destination_index=filtered_index_name,
+ source_index=origin_index_name,
+ timeout=timeout,
+ requests_per_second="{{ var.value.get('ES_INDEX_THROTTLING_RATE', 20_000) }}",
+ query={
+ "bool": {
+ "must_not": [
+ # Use `terms` query for exact matching against unanalyzed raw fields
+ {"terms": {f"{field}.raw": sensitive_terms.output}}
+ for field in ["tags.name", "title", "description"]
+ ]
+ }
+ },
+ refresh=False,
+ )
+
+ refresh_index = es.refresh_index(es_host=es_host, index_name=filtered_index_name)
+
+ sensitive_terms >> populate_filtered_index
+ create_filtered_index >> populate_filtered_index >> refresh_index
+
+ return filtered_index_name
diff --git a/catalog/dags/data_refresh/create_and_promote_index.py b/catalog/dags/data_refresh/create_index.py
similarity index 58%
rename from catalog/dags/data_refresh/create_and_promote_index.py
rename to catalog/dags/data_refresh/create_index.py
index 2f5dd2650..78a4066c2 100644
--- a/catalog/dags/data_refresh/create_and_promote_index.py
+++ b/catalog/dags/data_refresh/create_index.py
@@ -1,7 +1,7 @@
"""
-# Create and Promote Index
+# Create Index
-This file contains TaskGroups related to creating and promoting Elasticsearch indices
+This file contains TaskGroups related to creating Elasticsearch indices
as part of the Data Refresh.
"""
@@ -12,6 +12,7 @@ from airflow.decorators import task, task_group
from common import elasticsearch as es
from data_refresh.data_refresh_types import DataRefreshConfig
+from data_refresh.es_mapping import index_settings
logger = logging.getLogger(__name__)
@@ -30,17 +31,14 @@ def create_index(
# Generate a UUID suffix that will be used by the newly created index.
temp_index_name = generate_index_name(media_type=data_refresh_config.media_type)
- # Get the configuration for the new Elasticsearch index, based off the existing index.
- index_config = es.get_index_configuration_copy.override(
- task_id="get_index_configuration"
- )(
- source_index=data_refresh_config.media_type,
- target_index_name=temp_index_name,
+ # Create a new index
+ es.create_index(
+ index_config={
+ "index": temp_index_name,
+ "body": index_settings(data_refresh_config.media_type),
+ },
es_host=es_host,
)
- # Create a new index matching the existing configuration
- es.create_index(index_config=index_config, es_host=es_host)
-
# Return the name of the created index
return temp_index_name
diff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.py
index bb92755bd..7c1e975a5 100644
--- a/catalog/dags/data_refresh/dag_factory.py
+++ b/catalog/dags/data_refresh/dag_factory.py
@@ -48,9 +48,13 @@ from common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGs
from common.sensors.utils import wait_for_external_dags_with_tag
from data_refresh.alter_data import alter_table_data
from data_refresh.copy_data import copy_upstream_tables
-from data_refresh.create_and_promote_index import create_index
+from data_refresh.create_and_populate_filtered_index import (
+ create_and_populate_filtered_index,
+)
+from data_refresh.create_index import create_index
from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefreshConfig
from data_refresh.distributed_reindex import perform_distributed_reindex
+from data_refresh.promote_table import promote_tables
from data_refresh.reporting import report_record_difference
@@ -174,13 +178,21 @@ def create_data_refresh_dag(
# Populate the Elasticsearch index.
reindex = perform_distributed_reindex(
+ es_host=es_host,
environment="{{ var.value.ENVIRONMENT }}",
target_environment=target_environment,
target_index=target_index,
data_refresh_config=data_refresh_config,
)
- # TODO create_and_populate_filtered_index
+ # Create and populate the filtered index
+ filtered_index = create_and_populate_filtered_index(
+ es_host=es_host,
+ media_type=data_refresh_config.media_type,
+ origin_index_name=target_index,
+ destination_index_name=f"{target_index}-filtered",
+ timeout=data_refresh_config.create_filtered_index_timeout,
+ )
# Re-enable Cloudwatch alarms once reindexing is complete, even if it
# failed.
@@ -193,9 +205,27 @@ def create_data_refresh_dag(
trigger_rule=TriggerRule.ALL_DONE,
)
- # TODO Promote
- # (TaskGroup that reapplies constraints, promotes new tables and indices,
- # deletes old ones)
+ # Promote the API table
+ promote_table = promote_tables(
+ data_refresh_config=data_refresh_config,
+ target_environment=target_environment,
+ )
+
+ promote_index = es.point_alias.override(group_id="promote_index")(
+ es_host=es_host,
+ target_index=target_index,
+ target_alias=data_refresh_config.media_type,
+ should_delete_old_index=True,
+ )
+
+ promote_filtered_index = es.point_alias.override(
+ group_id="promote_filtered_index"
+ )(
+ es_host=es_host,
+ target_index=filtered_index,
+ target_alias=f"{data_refresh_config.media_type}-filtered",
+ should_delete_old_index=True,
+ )
# Get the final number of records in the API table after the refresh
after_record_count = es.get_record_count_group_by_sources.override(
@@ -226,9 +256,13 @@ def create_data_refresh_dag(
>> target_index
>> disable_alarms
>> reindex
+ >> filtered_index
)
- reindex >> [enable_alarms, after_record_count]
- after_record_count >> report_counts
+ # Note filtered_index must be directly upstream of promote_table to
+ # ensure that table promotion does not run if there was an error during reindexing
+ filtered_index >> [enable_alarms, promote_table]
+ promote_table >> [promote_index, promote_filtered_index]
+ promote_index >> after_record_count >> report_counts
return dag
diff --git a/catalog/dags/data_refresh/data_refresh_types.py b/catalog/dags/data_refresh/data_refresh_types.py
index 643671389..5faf4c3ea 100644
--- a/catalog/dags/data_refresh/data_refresh_types.py
+++ b/catalog/dags/data_refresh/data_refresh_types.py
@@ -75,10 +75,13 @@ class DataRefreshConfig:
the distributed reindex
index_readiness_timeout: timedelta expressing amount of time it may take
to await a healthy ES index after reindexing
+ create_filtered_index_timeout: timedelta expressing amount of time it may take to await
+ the creation of the filtered index
concurrency_check_poke_interval: int number of seconds to wait between
checks to see if conflicting DAGs are running
reindex_poke_interval: int number of seconds to wait between checks to see if
the reindexing task has completed
+
doc_md: str used for the DAG's documentation markdown
"""
@@ -94,6 +97,7 @@ class DataRefreshConfig:
copy_data_timeout: timedelta = timedelta(hours=1)
indexer_worker_timeout: timedelta = timedelta(hours=12)
index_readiness_timeout: timedelta = timedelta(days=1)
+ create_filtered_index_timeout: timedelta = timedelta(days=1)
concurrency_check_poke_interval: int = REFRESH_POKE_INTERVAL
reindex_poke_interval: int = REFRESH_POKE_INTERVAL
diff --git a/catalog/dags/data_refresh/distributed_reindex.py b/catalog/dags/data_refresh/distributed_reindex.py
index 1a9b50881..e4a7116a6 100644
--- a/catalog/dags/data_refresh/distributed_reindex.py
+++ b/catalog/dags/data_refresh/distributed_reindex.py
@@ -14,11 +14,14 @@ from airflow import settings
from airflow.decorators import task, task_group
from airflow.exceptions import AirflowSkipException
from airflow.models.connection import Connection
+from airflow.operators.empty import EmptyOperator
from airflow.providers.amazon.aws.hooks.ec2 import EC2Hook
+from airflow.providers.common.sql.hooks.sql import fetch_one_handler
from airflow.sensors.base import PokeReturnValue
from airflow.utils.trigger_rule import TriggerRule
from requests import Response
+from common import elasticsearch as es
from common.constants import (
AWS_CONN_ID,
OPENLEDGER_API_CONN_ID,
@@ -27,7 +30,7 @@ from common.constants import (
)
from common.operators.http import TemplatedConnectionHttpOperator
from common.sensors.http import TemplatedConnectionHttpSensor
-from common.sql import PGExecuteQueryOperator, single_value
+from common.sql import PGExecuteQueryOperator
from data_refresh.constants import INDEXER_LAUNCH_TEMPLATES, INDEXER_WORKER_COUNTS
from data_refresh.data_refresh_types import DataRefreshConfig
@@ -84,7 +87,7 @@ def response_check_wait_for_completion(response: Response) -> bool:
@task
def get_worker_params(
- estimated_record_count: int,
+ id_range: tuple[int, int],
environment: str,
target_environment: Environment,
):
@@ -95,12 +98,15 @@ def get_worker_params(
if environment == PRODUCTION
else 1
)
+
+ min_id, max_id = id_range
+ estimated_record_count = max_id - min_id + 1
records_per_worker = math.floor(estimated_record_count / worker_count)
return [
{
- "start_id": worker_index * records_per_worker,
- "end_id": (1 + worker_index) * records_per_worker,
+ "start_id": min_id + worker_index * records_per_worker,
+ "end_id": min_id + (1 + worker_index) * records_per_worker,
}
for worker_index in range(worker_count)
]
@@ -274,6 +280,25 @@ def drop_connection(worker_conn: str):
session.commit()
+def assert_reindexing_success() -> EmptyOperator:
+ """
+ Fail if the direct upstream tasks, which perform the actual reindexing,
+ fail. Otherwise simply pass.
+
+ This is necessary because we have some tasks after the reindex step
+ which always run even on reindexing failure (to drop the connection
+ and terminate the worker instance). However in the event of failures,
+ we still need the last task in the TaskGroup to be marked as `Failed`
+ or else subsequent tasks (like the promotion steps) will run. It is
+ not possible to set individual tasks within a TaskGroup as
+ directly upstream of later tasks; the last task in the TaskGroup
+ must fail.
+ """
+ return EmptyOperator(
+ task_id="assert_reindexing_success", trigger_rule=TriggerRule.NONE_FAILED
+ )
+
+
@task_group(group_id="reindex")
def reindex(
data_refresh_config: DataRefreshConfig,
@@ -345,32 +370,35 @@ def reindex(
instance_id=instance_id,
)
+ status = assert_reindexing_success()
+
drop_conn = drop_connection(worker_conn=worker_conn)
instance_id >> [await_worker, instance_ip_address]
worker_conn >> trigger_reindexing_task >> wait_for_reindexing_task
- wait_for_reindexing_task >> [terminate_instance, drop_conn]
+ wait_for_reindexing_task >> [terminate_instance, drop_conn, status]
@task_group(
group_id="run_distributed_reindex",
)
def perform_distributed_reindex(
+ es_host: str,
environment: str,
target_environment: Environment,
target_index: str,
data_refresh_config: DataRefreshConfig,
):
"""Perform the distributed reindex on a fleet of remote indexer workers."""
- estimated_record_count = PGExecuteQueryOperator(
- task_id="get_estimated_record_count",
+ id_range = PGExecuteQueryOperator(
+ task_id="get_record_id_range",
conn_id=OPENLEDGER_API_CONN_ID,
sql=dedent(
f"""
- SELECT max(id) FROM {data_refresh_config.table_mapping.temp_table_name};
+ SELECT min(id), max(id) FROM {data_refresh_config.table_mapping.temp_table_name};
"""
),
- handler=single_value,
+ handler=fetch_one_handler,
return_last=True,
trigger_rule=TriggerRule.NONE_FAILED,
)
@@ -381,17 +409,28 @@ def perform_distributed_reindex(
)
worker_params = get_worker_params(
- estimated_record_count=estimated_record_count.output,
+ id_range=id_range.output,
environment=environment,
target_environment=target_environment,
)
- estimated_record_count >> worker_params
+ id_range >> worker_params
- reindex.partial(
+ perform_reindex = reindex.partial(
data_refresh_config=data_refresh_config,
target_index=target_index,
launch_template_version_number=launch_template_version_number,
environment=environment,
target_environment=target_environment,
).expand_kwargs(worker_params)
+
+ # Refresh the index at the end, in order to make the documents available for
+ # filtered index creation
+ refresh_index = es.refresh_index.override(
+ trigger_rule=TriggerRule.NONE_FAILED,
+ )(
+ es_host=es_host,
+ index_name=target_index,
+ )
+
+ perform_reindex >> refresh_index
diff --git a/catalog/dags/data_refresh/es_mapping.py b/catalog/dags/data_refresh/es_mapping.py
new file mode 100644
index 000000000..7a0e75ea4
--- /dev/null
+++ b/catalog/dags/data_refresh/es_mapping.py
@@ -0,0 +1,136 @@
+from common.constants import AUDIO, IMAGE, MediaType
+
+
+def index_settings(media_type: MediaType):
+ """
+ Return the Elasticsearch mapping for a given table in the database.
+
+ :param media_type: The name of the table in the upstream database.
+ :return: the settings for the ES mapping
+ """
+
+ number_of_shards: dict[MediaType, int] = {
+ IMAGE: 18,
+ AUDIO: 1,
+ }
+
+ settings = {
+ "index": {
+ "number_of_shards": number_of_shards[media_type],
+ "number_of_replicas": 0,
+ "refresh_interval": "-1",
+ },
+ "analysis": {
+ "filter": {
+ "stem_overrides": {
+ "type": "stemmer_override",
+ "rules": [
+ # Override unwanted 'anim' stems
+ "animals => animal",
+ "animal => animal",
+ "anime => anime",
+ "animate => animate",
+ "animated => animate",
+ # Override "universe" to prevent matching to
+ # "university" or "universal".
+ "universe => universe",
+ ],
+ },
+ "english_stop": {"type": "stop", "stopwords": "_english_"},
+ "english_stemmer": {"type": "stemmer", "language": "english"},
+ "english_possessive_stemmer": {
+ "type": "stemmer",
+ "language": "possessive_english",
+ },
+ },
+ "analyzer": {
+ "custom_english": {
+ "tokenizer": "standard",
+ "filter": [
+ # Stem overrides must appear before the primary
+ # language stemmer.
+ "stem_overrides",
+ "english_possessive_stemmer",
+ "lowercase",
+ "english_stop",
+ "english_stemmer",
+ ],
+ }
+ },
+ },
+ }
+ common_mappings = {
+ "dynamic": False, # extra fields are stored in ``_source`` but not indexed
+ "properties": {
+ "id": {"type": "long"},
+ "created_on": {"type": "date"},
+ "mature": {"type": "boolean"},
+ # Keyword fields
+ "identifier": {"type": "keyword"},
+ "extension": {"type": "keyword"},
+ "license": {"type": "keyword"},
+ "provider": {"type": "keyword"},
+ "source": {"type": "keyword"},
+ "filetype": {"type": "keyword"},
+ "category": {"type": "keyword"},
+ # Text-based fields
+ "title": {
+ "type": "text",
+ "analyzer": "custom_english",
+ "similarity": "boolean",
+ "fields": {
+ "keyword": {"type": "keyword", "ignore_above": 256},
+ "raw": {"type": "text", "index": True},
+ },
+ },
+ "description": {
+ "type": "text",
+ "analyzer": "custom_english",
+ "similarity": "boolean",
+ "fields": {"raw": {"type": "text", "index": True}},
+ },
+ "creator": {
+ "type": "text",
+ "fields": {"keyword": {"type": "keyword", "ignore_above": 256}},
+ },
+ # Rank feature fields
+ "standardized_popularity": {"type": "rank_feature"},
+ "authority_boost": {"type": "rank_feature"},
+ "authority_penalty": {
+ "type": "rank_feature",
+ "positive_score_impact": False,
+ },
+ "max_boost": {"type": "rank_feature"},
+ "min_boost": {"type": "rank_feature"},
+ # Nested fields
+ "tags": {
+ "properties": {
+ "accuracy": {"type": "float"},
+ # Text-based fields
+ "name": {
+ "type": "text",
+ "analyzer": "custom_english",
+ "fields": {
+ "keyword": {"type": "keyword", "ignore_above": 256},
+ "raw": {"type": "text", "index": True},
+ },
+ },
+ }
+ },
+ },
+ }
+ media_properties = {
+ "image": {
+ # Keyword fields
+ "aspect_ratio": {"type": "keyword"},
+ "size": {"type": "keyword"},
+ },
+ "audio": {
+ # Keyword fields
+ "length": {"type": "keyword"},
+ },
+ }
+ media_mappings = common_mappings.copy()
+ media_mappings["properties"].update(media_properties[media_type])
+ result = {"settings": settings.copy(), "mappings": media_mappings}
+ return result
diff --git a/catalog/dags/data_refresh/promote_table.py b/catalog/dags/data_refresh/promote_table.py
new file mode 100644
index 000000000..a795b9414
--- /dev/null
+++ b/catalog/dags/data_refresh/promote_table.py
@@ -0,0 +1,99 @@
+"""
+# Promote Table
+
+This file contains TaskGroups related to promoting the API DB tables as part of the data refresh.
+
+In this TaskGroup, indices and constraints from the original table are applied to the temp table before dropping the original table and "promoting" the temp table by renaming it.
+"""
+
+import logging
+from dataclasses import asdict
+
+from airflow.decorators import task, task_group
+
+from common.constants import POSTGRES_API_CONN_IDS, Environment
+from common.sql import run_sql
+from data_refresh import queries
+from data_refresh.data_refresh_types import DataRefreshConfig
+from data_refresh.remap_table_constraints import remap_table_constraints_to_table
+from data_refresh.remap_table_indices import TableIndex, remap_table_indices_to_table
+
+
+logger = logging.getLogger(__name__)
+
+
+@task
+def get_go_live_query(
+ table_name: str, temp_table_name: str, index_mapping: list[TableIndex]
+):
+ """Get the query for replacing the original media table with the new temp table."""
+
+ # The remapped indices on the temp table all have temporary names to avoid
+ # naming collisions with the indices on the original table. Prepare the ALTER
+ # TABLE statements for restoring them to their original names once the original
+ # table is dropped.
+ restore_index_names = ("\n ").join(
+ [
+ queries.RENAME_INDEX_QUERY.format(
+ old_name=index.temp_index_name, new_name=index.index_name
+ )
+ for index in index_mapping
+ ]
+ )
+
+ return queries.GO_LIVE_QUERY.format(
+ table_name=table_name,
+ temp_table_name=temp_table_name,
+ restore_index_names=restore_index_names,
+ )
+
+
+@task_group
+def promote_table(
+ postgres_conn_id: str,
+ downstream_table_name: str,
+ temp_table_name: str,
+):
+ # Recreate indices from the original table.
+ remap_table_indices = remap_table_indices_to_table(
+ postgres_conn_id=postgres_conn_id,
+ table_name=downstream_table_name,
+ temp_table_name=temp_table_name,
+ )
+
+ # Recreate constraints from the original table.
+ remap_table_constraints = remap_table_constraints_to_table(
+ postgres_conn_id=postgres_conn_id,
+ table_name=downstream_table_name,
+ temp_table_name=temp_table_name,
+ )
+
+ # Get the query to replace the current media table with the temp table.
+ go_live_query = get_go_live_query(
+ table_name=downstream_table_name,
+ temp_table_name=temp_table_name,
+ index_mapping=remap_table_indices,
+ )
+
+ # Run the promotion
+ run_sql.override(task_id="promote")(
+ postgres_conn_id=postgres_conn_id, sql_template=go_live_query
+ )
+
+ remap_table_indices >> remap_table_constraints >> go_live_query
+
+
+@task_group
+def promote_tables(
+ data_refresh_config: DataRefreshConfig, target_environment: Environment
+):
+ """
+ Promote the temporary table in the API database to the main one after remapping all
+ constraints and indices from the original table, then delete the original.
+ """
+
+ downstream_conn_id = POSTGRES_API_CONN_IDS.get(target_environment)
+
+ promote_table.partial(
+ postgres_conn_id=downstream_conn_id,
+ ).expand_kwargs([asdict(tm) for tm in data_refresh_config.table_mappings])
diff --git a/catalog/dags/data_refresh/queries.py b/catalog/dags/data_refresh/queries.py
index 6a53fe674..d3f6c0dcf 100644
--- a/catalog/dags/data_refresh/queries.py
+++ b/catalog/dags/data_refresh/queries.py
@@ -80,3 +80,44 @@ ADVANCED_COPY_DATA_QUERY = dedent(
ADD_PRIMARY_KEY_QUERY = "ALTER TABLE {temp_table_name} ADD PRIMARY KEY (id);"
DROP_SERVER_QUERY = "DROP SERVER upstream CASCADE;"
+
+SELECT_TABLE_INDICES_QUERY = (
+ "SELECT indexdef FROM pg_indexes WHERE tablename='{table_name}';"
+)
+
+SELECT_ALL_CONSTRAINTS_QUERY = dedent(
+ """
+ SELECT conrelid::regclass AS table, conname, pg_get_constraintdef(c.oid)
+ FROM pg_constraint AS c
+ JOIN pg_namespace AS n
+ ON n.oid = c.connamespace
+ AND n.nspname = 'public'
+ ORDER BY conrelid::regclass::text, contype DESC;
+ """
+)
+
+ADD_CONSTRAINT_QUERY = "ALTER TABLE {constraint_table} ADD CONSTRAINT {constraint_name} {constraint_statement};"
+
+DROP_CONSTRAINT_QUERY = (
+ "ALTER TABLE {constraint_table} DROP CONSTRAINT {constraint_name};"
+)
+
+DELETE_ORPHANS_QUERY = dedent(
+ """
+ DELETE FROM {foreign_key_table} AS fk_table
+ WHERE NOT EXISTS(
+ SELECT 1 FROM {referenced_table} AS r
+ WHERE r.{referenced_field} = fk_table.{foreign_key_field}
+ );
+ """
+)
+
+RENAME_INDEX_QUERY = "ALTER INDEX {old_name} RENAME TO {new_name};"
+
+GO_LIVE_QUERY = dedent(
+ """
+ DROP TABLE {table_name};
+ {restore_index_names}
+ ALTER TABLE {temp_table_name} RENAME TO {table_name};
+ """
+)
diff --git a/catalog/dags/data_refresh/remap_table_constraints.py b/catalog/dags/data_refresh/remap_table_constraints.py
new file mode 100644
index 000000000..74419188c
--- /dev/null
+++ b/catalog/dags/data_refresh/remap_table_constraints.py
@@ -0,0 +1,226 @@
+"""
+# Remap Table Constraints
+
+This file contains TaskGroups related to remapping the table constraints from the live media table onto the temp table to prepare it for promotion.
+
+"""
+
+import logging
+from typing import NamedTuple
+
+from airflow.decorators import task, task_group
+
+from common.sql import run_sql
+from data_refresh import queries
+
+
+logger = logging.getLogger(__name__)
+
+
+class ConstraintInfo(NamedTuple):
+ table: str
+ name: str
+ statement: str
+
+
+def fetch_all_tuples(cursor):
+ try:
+ rows = cursor.fetchall()
+ return [ConstraintInfo(row[0], row[1], row[2]) for row in rows]
+ except Exception as e:
+ raise ValueError("Unable to extract expected row data from cursor") from e
+
+
+def _is_foreign_key(statement, table):
+ return f"REFERENCES {table}(" in statement
+
+
+def _remap_constraint(
+ constraint: ConstraintInfo,
+ table_name: str,
+ temp_table_name: str,
+) -> list[str]:
+ """
+ Given information about an existing CONSTRAINT involving the original media table,
+ produce a list of `ALTER TABLE...` statements to remove the constraint from the
+ existing table and apply it to the temp table.
+
+ The constraint to remap may be a constraint directly on the live media table, in
+ which case it is dropped and then added directly to the temp table. Alternatively,
+ it may be a foreign key constraint on a related table which references the
+ live media table, in which case it is dropped from the related table and
+ re-added, altered to reference the temp table instead.
+ """
+
+ # In all cases, drop the existing constraint
+ alterations = [
+ queries.DROP_CONSTRAINT_QUERY.format(
+ 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:
+ alterations.append(
+ queries.ADD_CONSTRAINT_QUERY.format(
+ constraint_name=constraint.name,
+ constraint_table=temp_table_name,
+ constraint_statement=constraint.statement,
+ )
+ )
+
+ # If the constraint was a foreign key constraint which referenced the media table,
+ # we add it back to its original table, but altered to reference the temp table
+ # instead.
+ else:
+ 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.
+ reference_idx = tokens.index("REFERENCES") + 1
+ table_reference = tokens[reference_idx]
+ new_reference = table_reference.replace(f"{table_name}(", f"{temp_table_name}(")
+ tokens[reference_idx] = new_reference
+ new_constraint_statement = " ".join(tokens)
+
+ alterations.append(
+ queries.ADD_CONSTRAINT_QUERY.format(
+ constraint_table=constraint.table,
+ constraint_name=constraint.name,
+ constraint_statement=new_constraint_statement,
+ )
+ )
+
+ return alterations
+
+
+def _generate_delete_orphans(
+ constraint_statement: str, constraint_table: str, temp_table_name: str
+):
+ """
+ Parse a foreign key constraint and generate a `DELETE` statement to
+ delete records which would become invalid when the tables are swapped.
+
+ Takes a foreign key constraint statement from an API table, which
+ references the media table being replaced. It is possible that some records which
+ exist in the current (live) media table may no longer exist in the temp table
+ (for example, records that were moved to a `deleted_media` table as part of the
+ `delete_records` DAG). It is necessary to DROP any records in related tables
+ that have a foreign key reference to records that will no longer exist when
+ the tables are swapped.
+
+ Example: if the following CONSTRAINT exists on the `imagelist_images` table:
+ `FOREIGN KEY (imagelist_id) REFERENCES imagelist(id) DEFERRABLE INITIALLY DEFERRED;`
+
+ Then the following DELETE statement will be generated to drop records from
+ `imagelist_images` which reference images that do not exist in the temp table:
+ ```
+ DELETE FROM imagelist_images AS fk_table
+ WHERE NOT EXISTS(
+ SELECT 1 FROM temp_import_image AS r
+ WHERE r.id = fk.imagelist_id
+ );
+ ```
+ """
+ tokens = constraint_statement.split(" ")
+ # The foreign key field always comes after the word `KEY`
+ foreign_key_field_idx = tokens.index("KEY") + 1
+ # The field referenced by the foreign key
+ referenced_field_idx = tokens.index("REFERENCES") + 1
+
+ foreign_key_field = tokens[foreign_key_field_idx].strip("()")
+ # We will replace the referenced table with the temp table
+ _, referenced_field = tokens[referenced_field_idx].strip(")").split("(")
+
+ return queries.DELETE_ORPHANS_QUERY.format(
+ foreign_key_table=constraint_table,
+ foreign_key_field=foreign_key_field,
+ referenced_table=temp_table_name,
+ referenced_field=referenced_field,
+ )
+
+
+@task(map_index_template="{{ task.op_kwargs['table_name'] }}")
+def generate_constraints_for_table(
+ all_constraints: list[ConstraintInfo], table_name: str, temp_table_name: str
+):
+ """
+ Produce `ALTER TABLE...` statements needed to drop constraints from the
+ live (old) tables and remap them to the temp tables.
+ """
+ # `ALTER TABLE...` statements for dropping/applying the new constraints
+ remap_constraints = []
+ # Statements for dropping records in related tables that reference records
+ # that exist in the current (live) media table but not the temp table.
+ # These must be dropped before other constraints can be applied.
+ drop_orphans = []
+
+ for constraint in all_constraints:
+ # Consider all constraints that either apply directly to the given table or
+ # 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)
+ if (
+ (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.
+ alter_statements = _remap_constraint(
+ constraint,
+ table_name,
+ temp_table_name,
+ )
+ remap_constraints.extend(alter_statements)
+
+ # If the constraint was a foreign key constraint, generate statements
+ # to ensure no records persist which reference deleted media.
+ if is_fk:
+ delete_orphans = _generate_delete_orphans(
+ constraint.statement, constraint.table, temp_table_name
+ )
+ drop_orphans.append(delete_orphans)
+
+ constraint_statements = []
+ # Drop orphans first
+ constraint_statements.extend(drop_orphans)
+ constraint_statements.extend(remap_constraints)
+
+ return constraint_statements
+
+
+@task(map_index_template="{{ task.op_kwargs['table_name'] }}")
+def apply_constraints_to_table(
+ postgres_conn_id: str, table_name: str, constraints: list[str]
+):
+ logger.info(f"Applying constraints for `{table_name}`.")
+ for constraint in constraints:
+ run_sql.function(postgres_conn_id=postgres_conn_id, sql_template=constraint)
+
+
+@task_group
+def remap_table_constraints_to_table(
+ table_name: str, temp_table_name: str, postgres_conn_id: str
+):
+ 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,
+ map_index_template=table_name,
+ )
+
+ # Generate SQL for remapping constraints from the table to the temp_table
+ remapped_constraints = generate_constraints_for_table(
+ all_constraints=all_constraints,
+ table_name=table_name,
+ temp_table_name=temp_table_name,
+ )
+
+ apply_constraints_to_table(
+ postgres_conn_id=postgres_conn_id,
+ table_name=table_name,
+ constraints=remapped_constraints,
+ )
diff --git a/catalog/dags/data_refresh/remap_table_indices.py b/catalog/dags/data_refresh/remap_table_indices.py
new file mode 100644
index 000000000..7b7efd1bf
--- /dev/null
+++ b/catalog/dags/data_refresh/remap_table_indices.py
@@ -0,0 +1,133 @@
+"""
+# Remap Table Indices
+
+This file contains TaskGroups related to rmampping the table indices from the live media table onto the temp table to prepare it for promotion.
+"""
+
+import logging
+from typing import NamedTuple
+
+from airflow.decorators import task, task_group
+from airflow.utils.trigger_rule import TriggerRule
+
+from common.sql import fetch_all, run_sql
+from data_refresh import queries
+
+
+logger = logging.getLogger(__name__)
+
+
+class TableIndex(NamedTuple):
+ index_name: str
+ temp_index_name: str
+ index_def: str
+
+
+def _transform_index_def(
+ existing_index_def: str, temp_table_name: str, table_name: str
+) -> TableIndex:
+ """
+ Given a CREATE INDEX statement for an index on the existing media table, return a
+ transformed statement that can be run to apply an identical index to the temp table.
+ """
+ is_pk = "(id)" in existing_index_def
+ tokens = existing_index_def.split(" ")
+
+ # Avoid a naming collision with the existing index by prepending
+ # `temp_import` to the index name. Later when the temp table is promoted,
+ # and the current media table is deleted, the indices will be restored
+ # to their original names.
+ # The index name always follows the word 'INDEX' in the def,
+ # e.g. `CREATE [UNIQUE] INDEX {index_name}`
+ index_name_idx = tokens.index("INDEX") + 1
+ old_index_name = tokens[index_name_idx]
+ # For most indices, we just prefix the index name with `temp_import_`. The pk
+ # index is automatically created at an earlier step and has a different
+ # naming convention.
+ temp_index_name = (
+ f"temp_import_{old_index_name}"
+ if not is_pk
+ else f"temp_import_{table_name}_pkey"
+ )
+ tokens[index_name_idx] = temp_index_name
+
+ # Update the table name to the temp table. The table name always follows
+ # the word 'ON' in the def, e.g. `ON public.audio`
+ table_name_idx = tokens.index("ON") + 1
+ 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))
+
+
+@task(map_index_template="{{ task.op_kwargs['table_name'] }}")
+def transform_index_defs(
+ existing_index_defs: list[str], temp_table_name: str, table_name: str
+) -> list[TableIndex]:
+ """
+ Given a CREATE INDEX statement for an index on the existing media table, return a
+ transformed statement that can be run to apply an identical index to the temp table.
+ """
+ return [
+ _transform_index_def(index_def, temp_table_name, table_name)
+ for index_def in existing_index_defs
+ ]
+
+
+@task(map_index_template="{{ task.op_kwargs['table_name'] }}")
+def create_table_indices(
+ postgres_conn_id: str, table_name: str, index_configs: list[TableIndex]
+):
+ logger.info(f"Creating indices for `{table_name}`.'")
+ for index_config in index_configs:
+ 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.")
+ continue
+
+ # Create the index
+ run_sql.function(
+ postgres_conn_id=postgres_conn_id, sql_template=index_config.index_def
+ )
+
+ return index_configs
+
+
+@task_group
+def remap_table_indices_to_table(
+ table_name: str, temp_table_name: str, postgres_conn_id: str
+):
+ """
+ Apply all indices on the main media table to the temp table. Indices will be given
+ names prefixed with `temp_import_` in this step to avoid collisions, and renamed
+ later when the table is promoted.
+ """
+ # Get the CREATE statements for the indices applied to the live (old) table
+ existing_index_defs = run_sql.override(
+ task_id="get_existing_index_defs", trigger_rule=TriggerRule.NONE_FAILED
+ )(
+ postgres_conn_id=postgres_conn_id,
+ sql_template=queries.SELECT_TABLE_INDICES_QUERY,
+ handler=fetch_all,
+ table_name=table_name,
+ map_index_template=table_name,
+ )
+
+ # Transform the CREATE statements so they can be used to apply identical indices
+ # to the temp table
+ new_index_configs = transform_index_defs(
+ temp_table_name=temp_table_name,
+ table_name=table_name,
+ existing_index_defs=existing_index_defs,
+ )
+
+ # Actually create the new indices on the temp table
+ indices = create_table_indices(
+ postgres_conn_id=postgres_conn_id,
+ table_name=table_name,
+ index_configs=new_index_configs,
+ )
+
+ # Return the information for the newly created indices, so that they can later
+ # be renamed to match the live index names
+ return indices
diff --git a/catalog/entrypoint.sh b/catalog/entrypoint.sh
index 1576309fd..2b42653f4 100755
--- a/catalog/entrypoint.sh
+++ b/catalog/entrypoint.sh
@@ -58,8 +58,8 @@ while read -r var_string; do
# set the environment variable
export "$var_name"="$new_value"
- # only include Slack airflow connections
-done < <(env | grep "^AIRFLOW_CONN_SLACK*")
+ # only include Slack airflow connections and the Sensitive Terms connection
+done < <(env | grep "^AIRFLOW_CONN_SLACK*\|AIRFLOW_CONN_SENSITIVE_TERMS")
if [[ $* == "webserver" ]]; then
# Wait for the database to initialize, will time out if not
diff --git a/catalog/env.template b/catalog/env.template
index fcfc7b02e..9ddc0861e 100644
--- a/catalog/env.template
+++ b/catalog/env.template
@@ -78,6 +78,11 @@ AIRFLOW_CONN_DATA_REFRESH=http://ingestion_server:8001
# server.
AIRFLOW_CONN_STAGING_DATA_REFRESH=http://ingestion_server:8001
+# Connect to sensitive terms list used for filtered index creation in the data refresh.
+# For local development, the mock terms list is served by the catalog indexer worker. Change to the
+# full production URL in order to use the production sensitive terms list.
+AIRFLOW_CONN_SENSITIVE_TERMS="http://catalog_indexer_worker:8003/static/mock_sensitive_terms.txt"
+
# Django Admin url. Change the following line to use the appropriate environment.
DJANGO_ADMIN_URL="https://localhost:8000/admin"
diff --git a/catalog/tests/dags/data_refresh/test_remap_table_constraints.py b/catalog/tests/dags/data_refresh/test_remap_table_constraints.py
new file mode 100644
index 000000000..243a2ca1b
--- /dev/null
+++ b/catalog/tests/dags/data_refresh/test_remap_table_constraints.py
@@ -0,0 +1,115 @@
+from textwrap import dedent
+
+import pytest
+
+from data_refresh.remap_table_constraints import (
+ ConstraintInfo,
+ generate_constraints_for_table,
+)
+
+
+# Constraint that does not apply to or reference the table_name table
+INAPPLICABLE_CONSTRAINT = ConstraintInfo(
+ "image", "irrelevant_constraint", "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",
+)
+# Primary key constraint; no alters should be generated
+PRIMARY_KEY_CONSTRAINT = ConstraintInfo("audio", "audio_pkey", "PRIMARY KEY (id)")
+# Unique constraint; no alters should be generated
+UNIQUE_CONSTRAINT = ConstraintInfo("audio", "audio_url_key", "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)",
+)
+# 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",
+)
+
+EXPECTED_DROP_ORPHANS_STATEMENT = dedent(
+ """
+ DELETE FROM audiolist_audios AS fk_table
+ WHERE NOT EXISTS(
+ SELECT 1 FROM temp_import_audio AS r
+ WHERE r.id = fk_table.audio_id
+ );
+ """
+)
+
+# Statements to drop example_check_constraint from audio and then add to temp_import_audio
+EXPECTED_ALTER_TABLE_STATEMENTS = [
+ "ALTER TABLE audio DROP CONSTRAINT example_check_constraint;",
+ "ALTER TABLE temp_import_audio ADD CONSTRAINT example_check_constraint CHECK (char_length(title) > 5);",
+]
+
+# Statements to drop the fkey constraint which previously referenced audio, and
+# add it back referencing temp_import_audio
+EXPECTED_ALTER_TABLE_FOREIGN_KEY_STATEMENTS = [
+ "ALTER TABLE audiolist_audios DROP CONSTRAINT audiolist_audios_audio_id_fkey;",
+ "ALTER TABLE audiolist_audios ADD CONSTRAINT audiolist_audios_audio_id_fkey FOREIGN KEY"
+ " (audio_id) REFERENCES temp_import_audio(id) DEFERRABLE INITIALLY DEFERRED;",
+]
+
+
+ "all_constraints, expected_alter_statements",
+ [
+ # No constraints
+ ([], []),
+ pytest.param([INAPPLICABLE_CONSTRAINT], [], id="inapplicable_constraint"),
+ pytest.param(
+ [INAPPLICABLE_FOREIGN_KEY_CONSTRAINT], [], id="inapplicable_fk_constraint"
+ ),
+ pytest.param(
+ [PRIMARY_KEY_CONSTRAINT], [], id="pk_constraint_generates_no_alters"
+ ),
+ pytest.param(
+ [UNIQUE_CONSTRAINT], [], id="unique_constraint_generates_no_alters"
+ ),
+ pytest.param(
+ [APPLICABLE_CONSTRAINT],
+ EXPECTED_ALTER_TABLE_STATEMENTS,
+ id="applicable_constraint",
+ ),
+ pytest.param(
+ [APPLICABLE_FOREIGN_KEY_CONSTRAINT],
+ [
+ # Drop orphans first
+ EXPECTED_DROP_ORPHANS_STATEMENT,
+ *EXPECTED_ALTER_TABLE_FOREIGN_KEY_STATEMENTS,
+ ],
+ id="applicable_foreign_key_constraint",
+ ),
+ pytest.param(
+ [
+ INAPPLICABLE_CONSTRAINT,
+ INAPPLICABLE_FOREIGN_KEY_CONSTRAINT,
+ PRIMARY_KEY_CONSTRAINT,
+ UNIQUE_CONSTRAINT,
+ APPLICABLE_CONSTRAINT,
+ APPLICABLE_FOREIGN_KEY_CONSTRAINT,
+ ],
+ [
+ # Drop orphans first
+ EXPECTED_DROP_ORPHANS_STATEMENT,
+ *EXPECTED_ALTER_TABLE_STATEMENTS,
+ *EXPECTED_ALTER_TABLE_FOREIGN_KEY_STATEMENTS,
+ ],
+ id="correct_alter_table_order",
+ ),
+ ],
+)
+def test_generate_constraints_for_table(all_constraints, expected_alter_statements):
+ actual = generate_constraints_for_table.function(
+ all_constraints, "audio", "temp_import_audio"
+ )
+ assert actual == expected_alter_statements
diff --git a/catalog/tests/dags/data_refresh/test_remap_table_indices.py b/catalog/tests/dags/data_refresh/test_remap_table_indices.py
new file mode 100644
index 000000000..14e6c2490
--- /dev/null
+++ b/catalog/tests/dags/data_refresh/test_remap_table_indices.py
@@ -0,0 +1,132 @@
+from unittest.mock import call, patch
+
+import pytest
+
+from data_refresh.remap_table_indices import (
+ TableIndex,
+ create_table_indices,
+ transform_index_defs,
+)
+
+
+ "existing_index_defs, expected_index_defs",
+ [
+ # Empty
+ ([], []),
+ # Transform all indices, including pk
+ (
+ [
+ "CREATE INDEX image_provider_7d11f847 ON public.image USING btree (provider)",
+ # Unique index
+ "CREATE UNIQUE INDEX image_identifier_key ON public.image USING btree (identifier)",
+ # Pk is ignored
+ "CREATE UNIQUE INDEX image_pkey ON public.image USING btree (id)",
+ ],
+ [
+ TableIndex(
+ "image_provider_7d11f847",
+ "temp_import_image_provider_7d11f847",
+ "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"
+ " public.temp_import_image USING btree (identifier)",
+ ),
+ TableIndex(
+ "image_pkey",
+ "temp_import_image_pkey",
+ "CREATE UNIQUE INDEX temp_import_image_pkey ON"
+ " public.temp_import_image USING btree (id)",
+ ),
+ ],
+ ),
+ ],
+)
+def test_transform_index_defs(existing_index_defs, expected_index_defs):
+ actual = transform_index_defs.function(
+ existing_index_defs=existing_index_defs,
+ temp_table_name="temp_import_image",
+ table_name="image",
+ )
+
+ assert actual == expected_index_defs
+
+
+ "index_configs, expected_sql",
+ [
+ # Empty
+ ([], []),
+ # run_sql never called if there is only a pk index
+ (
+ [
+ TableIndex(
+ "image_pkey",
+ "temp_import_image_pkey",
+ "CREATE UNIQUE INDEX temp_import_image_pk ON"
+ " public.temp_import_image USING btree (id)",
+ ),
+ ],
+ [],
+ ),
+ # Single index that should be remapped
+ (
+ [
+ TableIndex(
+ "image_provider_7d11f847",
+ "temp_import_image_provider_7d11f847",
+ "CREATE INDEX temp_import_image_provider_7d11f847 ON"
+ " public.temp_import_image USING btree (provider)",
+ ),
+ ],
+ [
+ "CREATE INDEX temp_import_image_provider_7d11f847 ON"
+ " public.temp_import_image USING btree (provider)",
+ ],
+ ),
+ # If there are multiple indices, run_sql is called for all except the pk
+ (
+ [
+ TableIndex(
+ "image_provider_7d11f847",
+ "temp_import_image_provider_7d11f847",
+ "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"
+ " public.temp_import_image USING btree (identifier)",
+ ),
+ TableIndex(
+ "image_pkey",
+ "temp_import_image_pkey",
+ "CREATE UNIQUE INDEX temp_import_image_pk ON"
+ " public.temp_import_image USING btree (id)",
+ ),
+ ],
+ [
+ "CREATE INDEX temp_import_image_provider_7d11f847 ON"
+ " public.temp_import_image USING btree (provider)",
+ "CREATE UNIQUE INDEX temp_import_image_identifier_key ON"
+ " public.temp_import_image USING btree (identifier)",
+ ],
+ ),
+ ],
+)
+def test_create_table_indices(index_configs, expected_sql):
+ with patch("common.sql.run_sql.function") as run_sql_mock:
+ create_table_indices.function(
+ postgres_conn_id="test_id", index_configs=index_configs, table_name="image"
+ )
+
+ expected_calls = [
+ call(postgres_conn_id="test_id", sql_template=sql) for sql in expected_sql
+ ]
+
+ run_sql_mock.assert_has_calls(expected_calls)
diff --git a/indexer_worker/indexer_worker/api.py b/indexer_worker/indexer_worker/api.py
index f55a8d010..5d1c7e77a 100644
--- a/indexer_worker/indexer_worker/api.py
+++ b/indexer_worker/indexer_worker/api.py
@@ -7,6 +7,7 @@ Accept an HTTP request specifying a range of image IDs to reindex.
import logging as log
import uuid
from multiprocessing import Process, Value
+from pathlib import Path
from urllib.parse import urlparse
import boto3
@@ -117,6 +118,10 @@ def create_api():
_api.add_route("/task", IndexingJobResource(task_tracker))
_api.add_route("/task/{task_id}", TaskStatusResource(task_tracker))
+ # Used to serve the mock sensitive terms list. Intended for local testing
+ # only.
+ _api.add_static_route("/static", (Path(".") / "static").absolute())
+
return _api
diff --git a/indexer_worker/indexer_worker/static/mock_sensitive_terms.txt b/indexer_worker/indexer_worker/static/mock_sensitive_terms.txt
new file mode 100644
index 000000000..c2c370b80
--- /dev/null
+++ b/indexer_worker/indexer_worker/static/mock_sensitive_terms.txt
@@ -0,0 +1,3 @@
+running
+water
+bird