Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Calculate standardized popularity during ingestion load_data (#2098)
Staci Mullinsb9943d1d6c28
diff --git a/catalog/dags/common/loader/sql.py b/catalog/dags/common/loader/sql.pyindex 386f27f8b..ca9401820 100644--- a/catalog/dags/common/loader/sql.py+++ b/catalog/dags/common/loader/sql.py@@ -7,6 +7,10 @@ from psycopg2.errors import InvalidTextRepresentationfrom common.constants import AUDIO, IMAGE, MediaTypefrom common.loader import provider_details as provfrom common.loader.paths import _extract_media_type+from common.popularity.constants import (+ STANDARDIZED_AUDIO_POPULARITY_FUNCTION,+ STANDARDIZED_IMAGE_POPULARITY_FUNCTION,+)from common.sql import PostgresHookfrom common.storage import columns as colfrom common.storage.columns import NULL, Column, UpsertStrategy@@ -244,7 +248,8 @@ def _is_tsv_column_from_different_version(Check that a column appears in the available columns for a TSV verison.Check that column is a column that exists in TSV files (unlike the db-only- columns like IDENTIFIER or CREATED_ON), but is not available for `tsv_version`.+ columns like IDENTIFIER or CREATED_ON, or calculated values like+ STANDARDIZED_POPULARITY), but is not available for `tsv_version`.For example, Category column was added to Image TSV in version 001:>>> from common.storage import CATEGORY, DIRECT_URL>>> _is_tsv_column_from_different_version(CATEGORY, IMAGE, '000')@@ -254,6 +259,8 @@ def _is_tsv_column_from_different_version(>>> from common.storage import IDENTIFIER>>> _is_tsv_column_from_different_version(IDENTIFIER, IMAGE, '000')False+ >>> _is_tsv_column_from_different_version(STANDARDIZED_POPULARITY, IMAGE, '000')+ False"""return (column not in COLUMNS[media_type][tsv_version]@@ -267,6 +274,7 @@ def upsert_records_to_db_table(db_table: str = None,media_type: str = IMAGE,tsv_version: str = CURRENT_TSV_VERSION,+ popularity_function: str = STANDARDIZED_IMAGE_POPULARITY_FUNCTION,task: AbstractOperator = None,):"""@@ -287,6 +295,9 @@ def upsert_records_to_db_table(if db_table is None:db_table = TABLE_NAMES.get(media_type, TABLE_NAMES[IMAGE])+ if media_type is AUDIO:+ popularity_function = STANDARDIZED_AUDIO_POPULARITY_FUNCTION+load_table = _get_load_table_name(identifier, media_type=media_type)logger.info(f"Upserting new records into {db_table}.")postgres = PostgresHook(@@ -299,17 +310,23 @@ def upsert_records_to_db_table(column_inserts = {}column_conflict_values = {}for column in db_columns:+ args = []+ if column.db_name == col.STANDARDIZED_POPULARITY.db_name:+ args = [+ popularity_function,+ ]+if column.upsert_strategy == UpsertStrategy.no_change:- column_inserts[column.db_name] = column.upsert_name+ column_inserts[column.db_name] = column.get_insert_value()elif _is_tsv_column_from_different_version(column, media_type, tsv_version):column_inserts[column.db_name] = NULLcolumn_conflict_values[column.db_name] = NULLelse:- column_conflict_values[column.db_name] = column.upsert_value+ column_conflict_values[column.db_name] = column.get_update_value(*args)# The direct_url is handled specially to ensure uniqueness and# should not be added to the column_inserts.if not column.db_name == col.DIRECT_URL.name:- column_inserts[column.db_name] = column.upsert_name+ column_inserts[column.db_name] = column.get_insert_value(*args)upsert_conflict_string = ",\n ".join(column_conflict_values.values())upsert_query = dedent(diff --git a/catalog/dags/common/popularity/constants.py b/catalog/dags/common/popularity/constants.pynew file mode 100644index 000000000..6742027eb--- /dev/null+++ b/catalog/dags/common/popularity/constants.py@@ -0,0 +1,9 @@+IMAGE_VIEW_NAME = "image_view"+AUDIO_VIEW_NAME = "audio_view"+AUDIOSET_VIEW_NAME = "audioset_view"+IMAGE_POPULARITY_CONSTANTS_VIEW = "image_popularity_constants"+AUDIO_POPULARITY_CONSTANTS_VIEW = "audio_popularity_constants"+IMAGE_POPULARITY_PERCENTILE_FUNCTION = "image_popularity_percentile"+AUDIO_POPULARITY_PERCENTILE_FUNCTION = "audio_popularity_percentile"+STANDARDIZED_IMAGE_POPULARITY_FUNCTION = "standardized_image_popularity"+STANDARDIZED_AUDIO_POPULARITY_FUNCTION = "standardized_audio_popularity"diff --git a/catalog/dags/common/popularity/sql.py b/catalog/dags/common/popularity/sql.pyindex c5ce51095..752620951 100644--- a/catalog/dags/common/popularity/sql.py+++ b/catalog/dags/common/popularity/sql.py@@ -6,21 +6,24 @@ from airflow.models.abstractoperator import AbstractOperatorfrom common.constants import AUDIO, IMAGEfrom common.loader.sql import TABLE_NAMES+from common.popularity.constants import (+ AUDIO_POPULARITY_CONSTANTS_VIEW,+ AUDIO_POPULARITY_PERCENTILE_FUNCTION,+ AUDIO_VIEW_NAME,+ AUDIOSET_VIEW_NAME,+ IMAGE_POPULARITY_CONSTANTS_VIEW,+ IMAGE_POPULARITY_PERCENTILE_FUNCTION,+ IMAGE_VIEW_NAME,+ STANDARDIZED_AUDIO_POPULARITY_FUNCTION,+ STANDARDIZED_IMAGE_POPULARITY_FUNCTION,+)from common.sql import PostgresHookfrom common.storage import columns as col+from common.storage.db_columns import AUDIO_TABLE_COLUMNS, IMAGE_TABLE_COLUMNSDEFAULT_PERCENTILE = 0.85-IMAGE_VIEW_NAME = "image_view"-AUDIO_VIEW_NAME = "audio_view"-AUDIOSET_VIEW_NAME = "audioset_view"-IMAGE_POPULARITY_CONSTANTS_VIEW = "image_popularity_constants"-AUDIO_POPULARITY_CONSTANTS_VIEW = "audio_popularity_constants"-IMAGE_POPULARITY_PERCENTILE_FUNCTION = "image_popularity_percentile"-AUDIO_POPULARITY_PERCENTILE_FUNCTION = "audio_popularity_percentile"-STANDARDIZED_IMAGE_POPULARITY_FUNCTION = "standardized_image_popularity"-STANDARDIZED_AUDIO_POPULARITY_FUNCTION = "standardized_audio_popularity"IMAGE_POP_CONSTANTS_IDX = "image_popularity_constants_provider_metric_idx"AUDIO_POP_CONSTANTS_IDX = "audio_popularity_constants_provider_metric_idx"@@ -247,6 +250,7 @@ def create_media_popularity_constants_view(popularity_constants_idx = AUDIO_POP_CONSTANTS_IDXpopularity_metrics = AUDIO_POPULARITY_METRICS_TABLE_NAMEpopularity_percentile = AUDIO_POPULARITY_PERCENTILE_FUNCTION+create_view_query = dedent(f"""CREATE MATERIALIZED VIEW public.{popularity_constants} AS@@ -365,6 +369,7 @@ def create_media_view(media_type=IMAGE,standardized_popularity_func=STANDARDIZED_IMAGE_POPULARITY_FUNCTION,table_name=TABLE_NAMES[IMAGE],+ db_columns=IMAGE_TABLE_COLUMNS,db_view_name=IMAGE_VIEW_NAME,db_view_id_idx=IMAGE_VIEW_ID_IDX,db_view_provider_fid_idx=IMAGE_VIEW_PROVIDER_FID_IDX,@@ -372,6 +377,7 @@ def create_media_view():if media_type == AUDIO:table_name = TABLE_NAMES[AUDIO]+ db_columns = AUDIO_TABLE_COLUMNSdb_view_name = AUDIO_VIEW_NAMEdb_view_id_idx = AUDIO_VIEW_ID_IDXdb_view_provider_fid_idx = AUDIO_VIEW_PROVIDER_FID_IDX@@ -383,11 +389,19 @@ def create_media_view(audio_set_id_str = ("\naudio_set ->> 'foreign_identifier' AS audio_set_foreign_identifier,")+ # We want to copy all columns except standardized popularity, which is calculated+ columns_to_select = (", ").join(+ [+ column.db_name+ for column in db_columns+ if column.db_name != col.STANDARDIZED_POPULARITY.db_name+ ]+ )create_view_query = dedent(f"""CREATE MATERIALIZED VIEW public.{db_view_name} ASSELECT- *,{audio_set_id_str if media_type == AUDIO else ""}+ {columns_to_select},{audio_set_id_str if media_type == AUDIO else ""}{standardized_popularity_func}({table_name}.{PARTITION},{table_name}.{METADATA_COLUMN}diff --git a/catalog/dags/common/storage/columns.py b/catalog/dags/common/storage/columns.pyindex bc4b51551..1b272fd12 100644--- a/catalog/dags/common/storage/columns.py+++ b/catalog/dags/common/storage/columns.py@@ -19,6 +19,7 @@ class Datatype(Enum):jsonb = "jsonb"timestamp = "timestamp with time zone"uuid = "uuid"+ double = "double precision"class UpsertStrategy(Enum):@@ -29,12 +30,26 @@ class UpsertStrategy(Enum):merge_jsonb_arrays = auto()merge_array = auto()no_change = ()+ calculate_value = auto()Datatypes = NewType("Datatype", Datatype)UpsertStrategies = NewType("UpsertStrategy", UpsertStrategy)+def _calculate_value(function: str, prefix: str, *args) -> str:+ """+ Return SQL to calculate the value by calling the given+ function with the given args.+ """+ if args:+ arguments = ", ".join([prefix + str(arg) for arg in args])+ return f"{function}({arguments})"++ # Handle function with no args+ return f"{function}()"++def _newest_non_null(column: str) -> str:return f"{column} = COALESCE(EXCLUDED.{column}, old.{column})"@@ -169,8 +184,8 @@ class Column(ABC):else:return string- @property- def upsert_name(self):+ def get_insert_value(self, *args):+ """Return the string used for this column in an INSERT statement."""if self.upsert_strategy == UpsertStrategy.now:return NOWelif self.upsert_strategy == UpsertStrategy.false:@@ -178,8 +193,8 @@ class Column(ABC):else:return self.db_name- @property- def upsert_value(self):+ def get_update_value(self, *args):+ """Return the string used for this column in the UPDATE statement."""strategy = Column.strategies.get(self.upsert_strategy)if strategy is None:logging.warning(@@ -228,7 +243,7 @@ class IntegerColumn(Column):"""Return a string representation to the best integer approx of input.- If there is no sane mapping from the input to an integer,+ If there is no reasonable mapping from the input to an integer,returns None.value: for useful output this should be reasonably castable to an int.@@ -241,6 +256,87 @@ class IntegerColumn(Column):return number+class CalculatedColumn(Column):+ """+ A specially handled PostgreSQL column of type double precision, which+ is always calculated at insertion and update.++ name: name of the corresponding column in the DB+ required: whether the column should be considered required by the+ instantiating script. (Not necessarily mapping to+ `not null` columns in the PostgreSQL table)+ sql_args: optionally, a list of string arguments passed to the SQL+ function used to calculate the column value+ """++ def __init__(+ self,+ name: str,+ required: bool,+ sql_args: list[str] | None = None,+ constraint: str | None = None,+ db_name: str | None = None,+ ):+ super().__init__(+ name,+ required,+ datatype=Datatype.double,+ upsert_strategy=UpsertStrategy.calculate_value,+ constraint=constraint,+ db_name=db_name,+ )+ self.sql_args = sql_args++ def get_insert_value(self, sql_function, prefix=""):+ """+ Return the string used for this column in an INSERT statement.++ For a calculated column, this will be a call to the SQL function with the+ given arguments, with no prefix applied. E.g.:++ `standardized_image_popularity(provider, meta_data)`+ """+ return _calculate_value(sql_function, prefix, *self.sql_args)++ def get_update_value(self, sql_function):+ """+ Return the string used for this column in an UPDATE statement, when there is+ a conflict during INSERT.++ For a calculated column, this will be an assignment to the SQL function with+ the given arguments, with the `EXCLUDED.` prefix applied: this indicates that+ in the upsert, the columns used as arguments should come from the new row we+ are attempting to upsert, rather than the existing data (i.e., we should use the+ more up-to-date information). E.g.:++ ```+ standardized_popularity = standardized_image_popularity(+ EXCLUDED.provider, EXCLUDED.meta_data+ )+ ```+ """+ function_call = self.get_insert_value(sql_function, prefix="EXCLUDED.")+ return f"{self.db_name} = {function_call}"++ def prepare_string(self, value):+ """+ Return a string representation to the best float approx of input.++ If there is no reasonable mapping from the input to a float,+ returns None.++ value: for useful output this should be reasonably castable to a float.+ """+ try:+ number = str(float(value))+ except (TypeError, ValueError) as e:+ logger.debug(+ f"input {value} is not castable to a float. The error was {e}"+ )+ number = None+ return number++class BooleanColumn(Column):"""Represents a PostgreSQL column of type boolean.@@ -273,7 +369,7 @@ class BooleanColumn(Column):"""Return a string `t` or `f`, as appropriate to input.- If there is no sane mapping from the input to a boolean,+ If there is no reasonable mapping from the input to a boolean,returns None.value: for useful output this should be reasonably castable to a bool.@@ -444,8 +540,7 @@ class TimestampColumn(Column):upsert_strategy=upsert_strategy or UpsertStrategy.now,)- @property- def upsert_name(self):+ def get_insert_value(self, *args):return NOWdef prepare_string(self, value):@@ -659,3 +754,9 @@ REMOVED = BooleanColumn()FILETYPE = StringColumn(name="filetype", required=False, truncate=False, size=5)++STANDARDIZED_POPULARITY = CalculatedColumn(+ name="standardized_popularity",+ required=False,+ sql_args=[PROVIDER.db_name, META_DATA.db_name],+)diff --git a/catalog/dags/common/storage/db_columns.py b/catalog/dags/common/storage/db_columns.pyindex 29233c25e..06d38faa4 100644--- a/catalog/dags/common/storage/db_columns.py+++ b/catalog/dags/common/storage/db_columns.py@@ -42,6 +42,7 @@ IMAGE_TABLE_COLUMNS = [col.REMOVED,col.FILETYPE,col.CATEGORY,+ col.STANDARDIZED_POPULARITY,]AUDIO_TABLE_COLUMNS = [@@ -75,4 +76,5 @@ AUDIO_TABLE_COLUMNS = [col.SET_POSITION,col.ALT_FILES,col.FILETYPE,+ col.STANDARDIZED_POPULARITY,]diff --git a/catalog/tests/dags/common/loader/test_sql.py b/catalog/tests/dags/common/loader/test_sql.pyindex 54fc6753c..2ef6bebe9 100644--- a/catalog/tests/dags/common/loader/test_sql.py+++ b/catalog/tests/dags/common/loader/test_sql.py@@ -3,6 +3,7 @@ import loggingimport osimport timefrom collections import namedtuple+from textwrap import dedentfrom unittest import mockimport psycopg2@@ -11,6 +12,10 @@ from airflow.models import TaskInstancefrom flaky import flakyfrom psycopg2.errors import InvalidTextRepresentation+from catalog.tests.dags.common.popularity.test_sql import (+ TableInfo,+ _set_up_std_popularity_func,+)from common.constants import IMAGEfrom common.loader import sqlfrom common.loader.sql import TSV_COLUMNS, create_column_definitions@@ -81,6 +86,7 @@ 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(@@ -106,6 +112,24 @@ def load_table(identifier):return f"load_image_{identifier}"+def table_info(+ image_table,+ identifier,+) -> TableInfo:+ return TableInfo(+ image=image_table,+ image_view=f"image_view_{identifier}",+ constants=f"image_popularity_constants_{identifier}",+ metrics=f"image_popularity_metrics_{identifier}",+ standardized_popularity=f"standardized_popularity_{identifier}",+ popularity_percentile=f"popularity_percentile_{identifier}",+ pop_constants_idx=f"test_popularity_constants_{identifier}_idx",+ image_view_idx=f"test_view_id_{identifier}_idx",+ provider_fid_idx=f"test_view_provider_fid_{identifier}_idx",+ )++@pytest.fixturedef postgres(load_table) -> PostgresRef:conn = psycopg2.connect(POSTGRES_TEST_URI)@@ -132,18 +156,23 @@ def postgres_with_load_table(postgres: PostgresRef, load_table) -> PostgresRef:@pytest.fixture-def postgres_with_load_and_image_table(load_table, image_table):+def postgres_with_load_and_image_table(+ load_table, image_table, table_info, mock_pg_hook_task+):conn = psycopg2.connect(POSTGRES_TEST_URI)cur = conn.cursor()- drop_load_table_query = f"DROP TABLE IF EXISTS {load_table} CASCADE;"- drop_image_table_query = f"DROP TABLE IF EXISTS {image_table} CASCADE;"- drop_image_index_query = f"DROP INDEX IF EXISTS {image_table}_provider_fid_idx;"-- logging.info(f"dropping load table: {drop_load_table_query}")- logging.info(f"dropping image table: {drop_image_table_query}")- cur.execute(drop_load_table_query)- cur.execute(drop_image_table_query)- cur.execute(drop_image_index_query)+ drop_test_relations_query = f"""+ DROP TABLE IF EXISTS {load_table} CASCADE;+ DROP TABLE IF EXISTS {image_table} CASCADE;+ DROP INDEX IF EXISTS {image_table}_provider_fid_idx;+ DROP MATERIALIZED VIEW IF EXISTS {table_info.constants} CASCADE;+ DROP TABLE IF EXISTS {table_info.metrics} CASCADE;+ DROP FUNCTION IF EXISTS {table_info.standardized_popularity} CASCADE;+ DROP FUNCTION IF EXISTS {table_info.popularity_percentile} CASCADE;+ """++ cur.execute(drop_test_relations_query)+cur.execute(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))@@ -153,9 +182,7 @@ def postgres_with_load_and_image_table(load_table, image_table):yield PostgresRef(cursor=cur, connection=conn)- cur.execute(drop_load_table_query)- cur.execute(drop_image_table_query)- cur.execute(drop_image_index_query)+ cur.execute(drop_test_relations_query)cur.close()conn.commit()conn.close()@@ -1421,6 +1448,138 @@ def test_upsert_records_handles_duplicate_urls_in_a_single_batch_and_does_not_meassert actual_rows[1][fid_idx] == "c"+def test_upsert_records_calculates_standardized_popularity(+ postgres_with_load_and_image_table,+ tmpdir,+ load_table,+ image_table,+ identifier,+ table_info,+ mock_pg_hook_task,+):+ postgres_conn_id = POSTGRES_CONN_ID++ PROVIDER = "images_provider"+ FID_A = "fid_a"+ FID_B = "fid_b"+ FID_C = "fid_c"++ # To test standardized popularity calculation, we want to have existing popularity+ # data. This query will be used to insert a few rows into the image table.+ data_query = dedent(+ f"""+ INSERT INTO {image_table} (+ created_on, updated_on, provider, foreign_identifier, url,+ meta_data, license, removed_from_source+ )+ VALUES+ (+ NOW(), NOW(), '{PROVIDER}', '{FID_A}', 'https://test.com/a.jpg',+ '{{"views": 0, "description": "cats"}}', 'cc0', false+ ),+ (+ NOW(), NOW(), '{PROVIDER}', '{FID_B}', 'https://test.com/b.jpg',+ '{{"views": 50, "description": "cats"}}', 'cc0', false+ )+ ;+ """+ )++ # Sample data to insert into the `image_popularity_metrics` table, so that popularity+ # constants will be calculated for our fake provider.+ metrics = {+ PROVIDER: {"metric": "views", "percentile": 0.8},+ }++ # Now we set up the popularity constants tables, views, and functions. This method will+ # run the `data_query` to insert our test rows, which will initially have `null` standardized+ # popularity (because no popularity constants exist). Then it will insert `metrics` into+ # the `image_popularity_metrics` table, and create the `image_popularity_constants` view,+ # calculating a value for the popularity constant for PROVIDER using those initial records.+ # Then it sets up the standardized popularity function itself.+ _set_up_std_popularity_func(+ postgres_with_load_and_image_table,+ data_query,+ metrics,+ table_info,+ mock_pg_hook_task,+ )++ # Now we want to try to upsert some records into the db. We want to update one of the existing+ # 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(+ {+ col.FOREIGN_ID.db_name: FID_A, # Matching a record that was already inserted+ col.DIRECT_URL.db_name: "https://test.com/a.jpg",+ col.LICENSE.db_name: "cc0",+ col.META_DATA.db_name: '{"views": 10, "description": "cats"}', # Update the number of views+ col.PROVIDER.db_name: PROVIDER,+ }+ )++ # A brand new record into the load table.+ query_values_update_new_record = create_query_values(+ {+ col.FOREIGN_ID.db_name: FID_C,+ col.DIRECT_URL.db_name: "https://test.com/z.jpg",+ col.LICENSE.db_name: "cc0",+ col.META_DATA.db_name: '{"views": 20, "description": "dogs"}',+ col.PROVIDER.db_name: PROVIDER,+ }+ )++ # Queries to insert the two records into the load table.+ load_data_query_old_record = f"""INSERT INTO {load_table} VALUES(+ {query_values_update_old_record}+ );"""++ load_data_query_new_record = f"""INSERT INTO {load_table} VALUES(+ {query_values_update_new_record}+ );"""++ # Now actually insert the records into the load table. This simulates a DagRun which ingests both+ # records.+ postgres_with_load_and_image_table.cursor.execute(load_data_query_old_record)+ postgres_with_load_and_image_table.cursor.execute(load_data_query_new_record)+ postgres_with_load_and_image_table.connection.commit()++ # Confirm that both made it to the loading table.+ postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {load_table};")+ rows = postgres_with_load_and_image_table.cursor.fetchall()+ assert len(rows) == 2++ # Now try upserting the records from the loading table to the final image table. Standardized popularity+ # should be calculated for both records.+ sql.upsert_records_to_db_table(+ postgres_conn_id,+ identifier,+ db_table=image_table,+ popularity_function=table_info.standardized_popularity,+ task=mock_pg_hook_task,+ )+ postgres_with_load_and_image_table.connection.commit()++ # Now check the final state of the image table. We expect there to be three rows total.+ postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")+ actual_rows = postgres_with_load_and_image_table.cursor.fetchall()+ 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++ # 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++ # This is the new record+ assert actual_rows[2][fid_idx] == FID_C+ assert actual_rows[2][standardized_popularity_idx] == 0.6153846153846154++def test_drop_load_table_drops_table(postgres_with_load_table, load_table, identifier):postgres_conn_id = POSTGRES_CONN_IDsql.drop_load_table(postgres_conn_id, identifier)diff --git a/catalog/tests/dags/common/popularity/test_sql.py b/catalog/tests/dags/common/popularity/test_sql.pyindex 2d0c67a56..b1d4eed7b 100644--- a/catalog/tests/dags/common/popularity/test_sql.py+++ b/catalog/tests/dags/common/popularity/test_sql.py@@ -8,7 +8,9 @@ from typing import NamedTupleimport psycopg2import pytest+from common.loader.sql import create_column_definitionsfrom common.popularity import sql+from common.storage.db_columns import IMAGE_TABLE_COLUMNSDDL_DEFINITIONS_PATH = Path(__file__).parents[5] / "docker" / "upstream_db"@@ -63,35 +65,10 @@ def postgres_with_image_table(table_info):cur.execute(drop_test_relations_query)cur.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;')- cur.execute(- f"""-CREATE TABLE public.{table_info.image} (-identifier uuid PRIMARY KEY DEFAULT public.uuid_generate_v4(),-created_on timestamp with time zone NOT NULL,-updated_on timestamp with time zone NOT NULL,-ingestion_type character varying(80),-provider character varying(80),-source character varying(80),-foreign_identifier character varying(3000),-foreign_landing_url character varying(1000),-url character varying(3000) NOT NULL,-thumbnail character varying(3000),-width integer,-height integer,-filesize integer,-license character varying(50) NOT NULL,-license_version character varying(25),-creator character varying(2000),-creator_url character varying(2000),-title character varying(5000),-meta_data jsonb,-tags jsonb,-watermarked boolean,-last_synced_with_source timestamp with time zone,-removed_from_source boolean NOT NULL-);-"""- )++ image_columns = create_column_definitions(IMAGE_TABLE_COLUMNS)+ cur.execute(f"CREATE TABLE public.{table_info.image} ({image_columns});")+cur.execute(f"""CREATE UNIQUE INDEX {table_info.image}_provider_fid_idxdiff --git a/catalog/tests/dags/common/storage/test_columns.py b/catalog/tests/dags/common/storage/test_columns.pyindex cfbe8ba49..5b0619572 100644--- a/catalog/tests/dags/common/storage/test_columns.py+++ b/catalog/tests/dags/common/storage/test_columns.py@@ -1,6 +1,7 @@import loggingimport string+import pytestimport tldextractfrom common import urls@@ -367,3 +368,58 @@ def test_ArrayColumn_of_IntegerColumn_prepare_string_returns_pg_array():actual_str = ac.prepare_string(given_list)expected_str = '{"1", "22", "3", "456"}'assert actual_str == expected_str+++ "function, prefix, args, expected_output",+ [+ ("my_func", "", [], "my_func()"),+ ("my_func", "EXCLUDED.", [], "my_func()"),+ ("my_func", "", ["foo"], "my_func(foo)"),+ ("my_func", "", ["foo", "bar"], "my_func(foo, bar)"),+ ("my_func", "EXCLUDED.", ["foo"], "my_func(EXCLUDED.foo)"),+ ("my_func", "EXCLUDED.", ["foo", "bar"], "my_func(EXCLUDED.foo, EXCLUDED.bar)"),+ ("my_func", "", [1, 2, "foo"], "my_func(1, 2, foo)"),+ ],+)+def test_calculate_value(function, prefix, args, expected_output):+ actual_output = columns._calculate_value(function, prefix, *args)+ assert actual_output == expected_output+++ "input, expected_output",+ [+ # returns None for non-number strings+ ("abc123", None),+ # Returns string representation of float when possible+ (2.34, "2.34"),+ ("3.45", "3.45"),+ (4, "4.0"),+ ("5", "5.0"),+ # Maximally preserves sigfigs+ (1.123456789012345678901234567890, "1.1234567890123457"),+ ],+)+def test_CalculatedColumn_prepare_string_nones_non_number_strings(+ input, expected_output+):+ cc = columns.CalculatedColumn("test", False, [])+ actual_output = cc.prepare_string(input)+ assert actual_output == expected_output+++def test_CalculatedColumn_get_insert_value():+ cc = columns.CalculatedColumn("test", required=False, sql_args=["foo", "bar"])+ actual_insert_value = cc.get_insert_value(sql_function="my_func")++ # _calculate_value is tested separately+ assert actual_insert_value == "my_func(foo, bar)"+++def test_CalculatedColumn_get_update_value():+ cc = columns.CalculatedColumn("test", required=False, sql_args=["foo", "bar"])+ actual_insert_value = cc.get_update_value(sql_function="my_func")++ # _calculate_value is tested separately+ assert actual_insert_value == "test = my_func(EXCLUDED.foo, EXCLUDED.bar)"