'Copy this HDA to a library optionally replacing an existing LDDA.'

def to_library_dataset_dataset_association(self, trans, target_folder, replace_dataset=None, parent_id=None, user=None, roles=None, ldda_message='', element_identifier=None):

    if replace_dataset:
        library_dataset = replace_dataset
    else:
        library_dataset = LibraryDataset(folder=target_folder, name=self.name, info=self.info)
        object_session(self).add(library_dataset)
        object_session(self).flush()
    if (not user):
        user = self.history.user
    ldda = LibraryDatasetDatasetAssociation(name=(element_identifier or self.name), info=self.info, blurb=self.blurb, peek=self.peek, tool_version=self.tool_version, extension=self.extension, dbkey=self.dbkey, dataset=self.dataset, library_dataset=library_dataset, visible=self.visible, deleted=self.deleted, parent_id=parent_id, copied_from_history_dataset_association=self, user=user)
    object_session(self).add(ldda)
    object_session(self).flush()
    roles = (roles or [])
    for role in roles:
        dp = trans.model.DatasetPermissions(trans.app.security_agent.permitted_actions.DATASET_ACCESS.action, ldda.dataset, role)
        trans.sa_session.add(dp)
        trans.sa_session.flush()
    ldda.metadata = self.metadata
    if ldda_message:
        ldda.message = ldda_message
    if (not replace_dataset):
        target_folder.add_library_dataset(library_dataset, genome_build=ldda.dbkey)
        object_session(self).add(target_folder)
        object_session(self).flush()
    library_dataset.library_dataset_dataset_association_id = ldda.id
    object_session(self).add(library_dataset)
    object_session(self).flush()
    for child in self.children:
        child.to_library_dataset_dataset_association(trans, target_folder=target_folder, replace_dataset=replace_dataset, parent_id=ldda.id, user=ldda.user)
    if (not self.datatype.copy_safe_peek):
        ldda.set_peek()
    object_session(self).flush()
    return ldda
