"""Dms delivery spec model.""" import sqlalchemy from src.connectors import direct_delivery from src.constants import fields from src.models import sql_queries def get_dms_delivery_spec_bulk(order_types_store_ids): """Get dms_delivery_spec fields values by (store_id, order_type) pairs. Args: order_types_store_ids (iterable): Pairs of integers as an iterable: (vector order type, store_id). Example: [('ringtone', 1), ('release', 286)] Returns: dict: A two-level dict with (order_type, store_id) tuple as a key and a subset records as nested dicts. Example: { ('ringtone', 1): {'encoding': 'N', 'delivery': 'N'}, ('release', 286): {'encoding': 'Y', 'delivery': 'N'}, } """ # There are just about 550 possible records (as of 2018) in this table but # we can receive an input just for a few records, so we're simply # concatenating all the conditions. This works well for up to 8K items. # Another option could be just always returning all the table records. conditions = [] for order_type, store_id in order_types_store_ids: conditions.append( sql_queries.DD_SELECT_DDS_BULK_CONDITION_TEMPLATE.format( order_type=order_type, store_id=store_id)) if not conditions: return {} query_conditions = '\nOR'.join(conditions) query = '{} {}'.format( sql_queries.DD_SELECT_DDS_BULK_NO_CONDITION, query_conditions) result_dict = {} with direct_delivery.session_scope() as session: result = session.execute(sqlalchemy.text(query)) key_fields = (fields.ORDER_TYPE, fields.DMS_MASTER_MASTER_ID) for row in result.mappings().all(): row_dict = dict(row) key = tuple(row_dict[f] for f in key_fields) # Remove fields that form the key. for f in key_fields: del row_dict[f] result_dict[key] = row_dict return result_dict