"""Utility Functions for Models.""" from conflict_manager import config def query_results_to_dict(query_results): """Convert query results in dict format. Args: query_results (ResultProxy): SQL Alchemy DB-API cursor wrapper. Returns: dict """ results = [] for row in query_results: results.append({key: row[key] for key in query_results.keys()}) return results def run_query(session, sql, account=None, params={}): """Run query with params. Expands table names and adds account info. Use these aliases within any query that is written: Alias | Substitution --------------------------------------------------------------------- {fact_conflict_table} | The fully qualified fact conflict table name {action_table} | The fully qualified acount table {account_id} | The vendor or subaccount id table field Args: session: SQLAlchemy session sql (str): SQL to run account (namedtuple): Account information (optional) params (dict): Parameters to add into query (handles SQL escaping) """ aliases = { 'fact_conflict_table': '{}.{}.fact_conflict'.format( config.FACTS_DATABASE, config.SNOWFLAKE_SCHEMA), 'action_table': '{}.{}.action'.format( config.CONFLICT_MANAGER_DATABASE, config.SNOWFLAKE_SCHEMA), 'track': '{}.track'.format(config.ART_RELATIONS_DATABASE_SCHEMA), 'track_artist': '{}.track_artist'.format( config.ART_RELATIONS_DATABASE_SCHEMA), 'releases': '{}.releases'.format(config.ART_RELATIONS_DATABASE_SCHEMA), 'subaccount': '{}.subaccount'.format( config.ART_RELATIONS_DATABASE_SCHEMA), 'conflict_status_table': '{}.{}.conflict_status'.format( config.CONFLICT_MANAGER_DATABASE, config.SNOWFLAKE_SCHEMA), } if account: aliases['account_id_field'] = '{}_id'.format(account.type) params['account_id'] = account.id return session.execute(sql.format(**aliases), params) def get_total_records(results, offset, limit): """Try to get total records from pagination data. Args: results (list): List of items offset (int): Pagination offset limit (int): Pagination limit Returns: int, None """ if len(results) > 0 and len(results) < limit: # This is the last page of results return offset + len(results) elif len(results) == 0 and offset == 0: # Total records is 0 when on the first page and there are no results return 0 return None def _validate_query_args(args): """Validate the presence of necessary arguments for filtering.""" keys = list(args.copy().keys()) return ('query' in keys and 'fields' in keys)