"""fetch_country_groups task.""" from garcon import task from snowflake_connector.snowflake_conn import get_session from snowflake_connector.snowflake_conn import SQLLoader from activity_detector import base_config from activity_detector.flows.trending_tracks import config sql_loader = SQLLoader(config.QUERY_PATH) @task.decorate(timeout=300) def fetch_country_groups(activity, country_groups=None): """Fetch the trending tracks country groups. Args: activity (ActivityWorker): garcon activity worker country_groups (dict): the country groups to fetch data for Returns: [dict]: the orchard trending tracks country groups """ sql = sql_loader.load_query('fetch_country_groups') sql = sql.replace('{env}', base_config.ENVIRONMENT) where_clause = '' if country_groups: country_groups_list = country_groups.split(',') country_groups_list.append('Global') country_groups_str = ( ', '.join("'{0}'".format(country_group.strip()) for country_group in country_groups_list)) where_clause = 'WHERE ttcg.trending_tracks_country_group_name in ({0})' where_clause = where_clause.format(country_groups_str) sql = sql.replace('{where_clause}', where_clause) with get_session() as session: result = session.execute(sql) return { 'country_groups': map_country_groups(result.cursor.fetchall()) } def map_country_groups(country_groups): """Map orchard trending tracks country groups. Args: country_groups ([tuple]): the list of country groups from the DB Returns: [dict]: the mapped country groups """ mapped_country_groups = [] if len(country_groups): for country_group in country_groups: (country_group_id, country_group_name, country_group_floor) = country_group mapped_country_groups.append({ 'country_group_id': country_group_id, 'country_group_name': country_group_name, 'country_group_floor': country_group_floor }) return mapped_country_groups