Ejemplo n.º 1
0
    def get(self, computer, user):
        """Return an entry from the collection that is configured for the given computer and user

        :param computer: a :class:`aiida.orm.implementation.computers.BackendComputer` instance
        :param user: a :class:`aiida.orm.implementation.users.BackendUser` instance
        :return: :class:`aiida.orm.implementation.authinfos.BackendAuthInfo`
        :raise aiida.common.exceptions.NotExistent: if no entry exists for the computer/user pair
        :raise aiida.common.exceptions.MultipleObjectsError: if multiple entries exist for the computer/user pair
        """
        # pylint: disable=import-error,no-name-in-module
        from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned

        try:
            authinfo = DbAuthInfo.objects.get(dbcomputer=computer.id,
                                              aiidauser=user.id)
        except ObjectDoesNotExist:
            raise exceptions.NotExistent(
                f'User<{user.email}> has no configuration for Computer<{computer.name}>'
            )
        except MultipleObjectsReturned:
            raise exceptions.MultipleObjectsError(
                f'User<{user.email}> has multiple configurations for Computer<{computer.name}>'
            )
        else:
            return self.from_dbmodel(authinfo)
Ejemplo n.º 2
0
    def get(cls, **kwargs):
        """
        Custom get for group which can be used to get a group with the given attributes

        :param kwargs: the attributes to match the group to

        :return: the group
        :type nodes: :class:`aiida.orm.Node` or list
        """
        from aiida.orm import QueryBuilder

        filters = {}
        if 'type_string' in kwargs:
            if not isinstance(kwargs['type_string'], six.string_types):
                raise exceptions.ValidationError(
                    'type_string must be {}, you provided an object of type '
                    '{}'.format(str, type(kwargs['type_string'])))

        query = QueryBuilder()
        for key, val in kwargs.items():
            filters[key] = val

        query.append(cls, filters=filters)
        results = query.all()
        if len(results) > 1:
            raise exceptions.MultipleObjectsError(
                "Found {} groups matching criteria '{}'".format(
                    len(results), kwargs))
        if not results:
            raise exceptions.NotExistent(
                "No group found matching criteria '{}'".format(kwargs))
        return results[0][0]
Ejemplo n.º 3
0
    def get(cls, pk=None, label=None, machinename=None):
        """
        Get a Computer object with given identifier string, that can either be
        the numeric ID (pk), or the label (and computername) (if unique).

        :param pk: the numeric ID (pk) for code
        :param label: the code label identifying the code to load
        :param machinename: the machine name where code is setup

        :raise aiida.common.NotExistent: if no code identified by the given string is found
        :raise aiida.common.MultipleObjectsError: if the string cannot identify uniquely a code
        :raise aiida.common.InputValidationError: if neither a pk nor a label was passed in
        """
        # pylint: disable=arguments-differ
        from aiida.orm.utils import load_code

        # first check if code pk is provided
        if pk:
            code_int = int(pk)
            try:
                return load_code(pk=code_int)
            except exceptions.NotExistent:
                raise ValueError('{} is not valid code pk'.format(pk))
            except exceptions.MultipleObjectsError:
                raise exceptions.MultipleObjectsError(
                    "More than one code in the DB with pk='{}'!".format(pk))

        # check if label (and machinename) is provided
        elif label is not None:
            return cls.get_code_helper(label, machinename)

        else:
            raise exceptions.InputValidationError(
                'Pass either pk or code label (and machinename)')
Ejemplo n.º 4
0
    def get(self, computer, user):
        """Return an entry from the collection that is configured for the given computer and user

        :param computer: a :class:`aiida.orm.implementation.computers.BackendComputer` instance
        :param user: a :class:`aiida.orm.implementation.users.BackendUser` instance
        :return: :class:`aiida.orm.implementation.authinfos.BackendAuthInfo`
        :raise aiida.common.exceptions.NotExistent: if no entry exists for the computer/user pair
        :raise aiida.common.exceptions.MultipleObjectsError: if multiple entries exist for the computer/user pair
        """
        # pylint: disable=import-error,no-name-in-module
        from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound

        session = get_scoped_session()

        try:
            authinfo = session.query(DbAuthInfo).filter_by(
                dbcomputer_id=computer.id, aiidauser_id=user.id).one()
        except NoResultFound:
            raise exceptions.NotExistent(
                f'User<{user.email}> has no configuration for Computer<{computer.name}>'
            )
        except MultipleResultsFound:
            raise exceptions.MultipleObjectsError(
                f'User<{user.email}> has multiple configurations for Computer<{computer.name}>'
            )
        else:
            return self.from_dbmodel(authinfo)
Ejemplo n.º 5
0
        def get_or_create(self, label=None, **kwargs):
            """
            Try to retrieve a group from the DB with the given arguments;
            create (and store) a new group if such a group was not present yet.

            :param label: group label
            :type label: str

            :return: (group, created) where group is the group (new or existing,
              in any case already stored) and created is a boolean saying
            :rtype: (:class:`aiida.orm.Group`, bool)
            """
            if not label:
                raise ValueError('Group label must be provided')

            res = self.find(filters={'label': label})

            if not res:
                return self.entity_type(label, backend=self.backend,
                                        **kwargs).store(), True

            if len(res) > 1:
                raise exceptions.MultipleObjectsError(
                    'More than one groups found in the database')

            return res[0], False
Ejemplo n.º 6
0
    def get(self, **filters):
        """
        Get the group matching the given filters

        :param filters: the attributes of the group to get
        :return: the group
        :rtype: :class:`aiida.orm.implementation.BackendGroup`
        """
        results = self.query(**filters)
        if len(results) > 1:
            raise exceptions.MultipleObjectsError("Found multiple groups matching criteria '{}'".format(filters))
        if not results:
            raise exceptions.NotExistent("No group bound matching criteria '{}'".format(filters))
        return results[0]
Ejemplo n.º 7
0
 def get(self, email):
     """
     Get a user using the email address
     :param email: The user's email address
     :return: The corresponding user object
     :raises: :class:`aiida.common.exceptions.MultipleObjectsError`, :class:`aiida.common.exceptions.NotExistent`
     """
     results = self.find(email=email)
     if not results:
         raise exceptions.NotExistent()
     else:
         if len(results) > 1:
             raise exceptions.MultipleObjectsError()
         else:
             return results[0]
Ejemplo n.º 8
0
    def get_or_create(cls, *args, **kwargs):
        """
        Try to retrieve a group from the DB with the given arguments;
        create (and store) a new group if such a group was not present yet.

        :return: (group, created) where group is the group (new or existing,
          in any case already stored) and created is a boolean saying
        """
        res = cls.query(name=kwargs.get('name'), type_string=kwargs.get('type_string'))

        if not res:
            return cls.create(*args, **kwargs), True

        if len(res) > 1:
            raise exceptions.MultipleObjectsError('More than one groups found in the database')

        return res[0], False
Ejemplo n.º 9
0
    def get_node_by_label(self, label):
        """Return the node from list for given label.

        :return: node that corresponds to the given label
        :raises aiida.common.NotExistent: if the label is not present among the link_triples
        """
        matching_entry = None
        for entry in self.link_triples:
            if entry.link_label == label:
                if matching_entry is None:
                    matching_entry = entry.node
                else:
                    raise exceptions.MultipleObjectsError(
                        f'more than one neighbor with the label {label} found'
                    )

        if matching_entry is None:
            raise exceptions.NotExistent(f'no neighbor with the label {label} found')

        return matching_entry
Ejemplo n.º 10
0
        def get_or_create(self, label=None, **kwargs):
            """
            Try to retrieve a group from the DB with the given arguments;
            create (and store) a new group if such a group was not present yet.

            :param label: group label
            :type label: str

            :return: (group, created) where group is the group (new or existing,
              in any case already stored) and created is a boolean saying
            :rtype: (:class:`aiida.orm.Group`, bool)
            """
            if not label:
                raise ValueError('Group label must be provided')

            filters = {'label': label}

            if 'type_string' in kwargs:
                if not isinstance(kwargs['type_string'], six.string_types):
                    raise exceptions.ValidationError(
                        'type_string must be {}, you provided an object of type '
                        '{}'.format(str, type(kwargs['type_string'])))

                filters['type_string'] = kwargs['type_string']

            res = self.find(filters=filters)

            if not res:
                return Group(label, backend=self.backend,
                             **kwargs).store(), True

            if len(res) > 1:
                raise exceptions.MultipleObjectsError(
                    'More than one groups found in the database')

            return res[0], False