'Return a query scalar that will get any history\'s size in bytes by summing
the \'total_size\'s of all non-purged, unique datasets within it.'

@disk_size.expression
def disk_size(cls):

    hda_to_dataset_join = join(HistoryDatasetAssociation, Dataset, (HistoryDatasetAssociation.table.c.dataset_id == Dataset.table.c.id))
    distinct_datasets = select([HistoryDatasetAssociation.table.c.history_id.label('history_id'), Dataset.total_size.label('dataset_size'), Dataset.id.label('dataset_id')]).where((HistoryDatasetAssociation.table.c.purged != true())).where((Dataset.table.c.purged != true())).select_from(hda_to_dataset_join).distinct()
    distinct_datasets_alias = aliased(distinct_datasets, name='datasets')
    size_query = select([func.coalesce(func.sum(distinct_datasets_alias.c.dataset_size), 0)]).select_from(distinct_datasets_alias).where((distinct_datasets_alias.c.history_id == cls.id))
    return size_query.label('disk_size')
