'Optimized version of add_dataset above that minimizes database
interactions when adding many datasets to history at once.'

def add_datasets(self, sa_session, datasets, parent_id=None, genome_build=None, set_hid=True, quota=True, flush=False):

    all_hdas = all((is_hda(_) for _ in datasets))
    optimize = ((len(datasets) > 1) and (parent_id is None) and all_hdas and set_hid)
    if optimize:
        self.__add_datasets_optimized(datasets, genome_build=genome_build)
        if (quota and self.user):
            disk_usage = sum([d.get_total_size() for d in datasets])
            self.user.adjust_total_disk_usage(disk_usage)
        sa_session.add_all(datasets)
        if flush:
            sa_session.flush()
    else:
        for dataset in datasets:
            self.add_dataset(dataset, parent_id=parent_id, genome_build=genome_build, set_hid=set_hid, quota=quota)
            sa_session.add(dataset)
            if flush:
                sa_session.flush()
