Python sqlalchemy.orm.exc.MultipleResultsFound() Examples

The following are 30 code examples of sqlalchemy.orm.exc.MultipleResultsFound(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.orm.exc , or try the search function .
Example #1
Source File: folder.py    From sync-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
def find_or_create(cls, session, account, name, role=None):
        q = session.query(cls).filter(cls.account_id == account.id)\
            .filter(cls.name == name)

        role = role or ''
        try:
            obj = q.one()
        except NoResultFound:
            obj = cls(account=account, name=name, canonical_name=role)
            obj.category = Category.find_or_create(
                session, namespace_id=account.namespace.id, name=role,
                display_name=name, type_='folder')
            session.add(obj)
        except MultipleResultsFound:
            log.info('Duplicate folder rows for name {}, account_id {}'
                     .format(name, account.id))
            raise

        return obj 
Example #2
Source File: profiles.py    From commandment with MIT License 6 votes vote down vote up
def ssl_trust_payload_from_configuration() -> PEMCertificatePayload:
    """Generate a PEM certificate payload in order to trust this host.

    """
    try:
        org = db.session.query(Organization).one()
    except NoResultFound:
        abort(500, 'No organization is configured, cannot generate enrollment profile.')
    except MultipleResultsFound:
        abort(500, 'Multiple organizations, backup your database and start again')

    basepath = os.path.dirname(__file__)
    certpath = os.path.join(basepath, current_app.config['SSL_CERTIFICATE'])

    with open(certpath, 'rb') as fd:
        pem_payload = PEMCertificatePayload(
            uuid=uuid4(),
            identifier=org.payload_prefix + '.ssl',
            payload_content=fd.read(),
            display_name='Web Server Certificate',
            description='Required for your device to trust the server',
            type='com.apple.security.pkcs1',
            version=1
        )
        return pem_payload 
Example #3
Source File: profiles.py    From commandment with MIT License 6 votes vote down vote up
def ca_trust_payload_from_configuration() -> PEMCertificatePayload:
    """Create a CA payload with the PEM representation of the Certificate Authority used by this instance.

    You need to check whether the app config contains 'CA_CERTIFICATE' before invoking this.
    """
    try:
        org = db.session.query(Organization).one()
    except NoResultFound:
        abort(500, 'No organization is configured, cannot generate enrollment profile.')
    except MultipleResultsFound:
        abort(500, 'Multiple organizations, backup your database and start again')

    with open(current_app.config['CA_CERTIFICATE'], 'rb') as fd:
        pem_data = fd.read()
        pem_payload = PEMCertificatePayload(
            uuid=uuid4(),
            identifier=org.payload_prefix + '.ca',
            payload_content=pem_data,
            display_name='Certificate Authority',
            description='Required for your device to trust the server',
            type='com.apple.security.root',
            version=1
        )

        return pem_payload 
Example #4
Source File: models.py    From GeoHealthCheck with MIT License 6 votes vote down vote up
def get_or_create(cls, channel, location):
        try:
            cls.validate(channel, location)
        except ValidationError as err:
            raise ValueError("invalid value {}: {}".format(location, err))

        try:
            r = DB.session.query(cls) \
                .filter(and_(cls.channel == channel,
                             cls.location == location)) \
                .one()
        except (MultipleResultsFound, NoResultFound,):
            r = cls(channel=channel, location=location)
            DB.session.add(r)
            DB.session.flush()
        return r 
Example #5
Source File: session.py    From FeatureHub with MIT License 6 votes vote down vote up
def __init__(self, problem, database = "featurehub"):
        self.__database            = database
        self.__orm                 = ORMManager(database)
        self.__username            = None

        with self.__orm.session_scope() as session:
            try:
                problem = session.query(Problem)\
                                 .filter(Problem.name == problem)\
                                 .one()
                self.__problem_id = problem.id
            except NoResultFound:
                raise ValueError("Invalid problem name: {}".format(problem))
            except MultipleResultsFound:
                raise ValueError("Unexpected issue talking to database. " +
                                 TRY_AGAIN_LATER)

        # "log in" to the system
        self._login()

        # initialize evaluation client
        self.__evaluation_client = EvaluatorClient(self.__problem_id,
                self.__username, self.__orm) 
Example #6
Source File: session.py    From FeatureHub with MIT License 6 votes vote down vote up
def _login(self):
        name = os.environ.get("USER")
        if not name:
            raise ValueError("Missing environment variable 'USER'. FeatureHub"
                             " session not initialized.")

        with self.__orm.session_scope() as session:
            try:
                user = session.query(User)\
                              .filter(User.name == name)\
                              .one()
                self.__username = user.name
            except NoResultFound:
                data = { "database" : self.__orm.database }
                response = Session._eval_server_post("create-user", data)
                if response.ok:
                    self.__username = name
                else:
                    raise ValueError("Couldn't log in to FeatureHub. " \
                                     + TRY_AGAIN_LATER) 

            except MultipleResultsFound as e:
                raise ValueError("Unexpected error logging in to FeatureHub. " \
                                 + TRY_AGAIN_LATER) 
Example #7
Source File: postgres_database.py    From open-raadsinformatie with MIT License 6 votes vote down vote up
def get_ori_identifier(self, iri):
        """
        Retrieves a Resource-based ORI identifier from the database. If no corresponding Resource exists,
        a new one is created.
        """

        session = self.Session()
        try:
            resource = session.query(Resource).join(Source).filter(Source.iri == iri).first()
            if not resource:
                raise NoResultFound
            return Uri(Ori, resource.ori_id)
        except MultipleResultsFound:
            raise MultipleResultsFound('Multiple resources found for IRI %s' % iri)
        except NoResultFound:
            return self.generate_ori_identifier(iri=iri)
        finally:
            session.close() 
Example #8
Source File: __init__.py    From build-relengapi with Mozilla Public License 2.0 6 votes vote down vote up
def _get_project(session, project):
    """Helper method to return Project class for a project with the given name.

    Args:
        session: SQLAlchemy ORM Session object
        project: Name of the project (e.g. 'build-tools')

    Returns:
        the corresponding python Project object

    Exceptions:
        HTTP 404: Project could not be found
        HTTP 500: Multiple projects with same name found
    """
    try:
        return Project.query.filter_by(name=project).one()
    except MultipleResultsFound:
        abort(500, "Multiple projects with name %s found in database" %
              project)
    except NoResultFound:
        abort(404, "Could not find project %s in database" % project) 
Example #9
Source File: __init__.py    From build-relengapi with Mozilla Public License 2.0 6 votes vote down vote up
def get_rev(projects, vcs_type, commit):
    # (documentation in relengapi/docs/usage/mapper.rst)
    _check_well_formed_sha(vcs_type, commit, exact_length=None)  # can raise http 400
    q = Hash.query.join(Project).filter(_project_filter(projects))
    if vcs_type == "git":
        q = q.filter(sa.text("git_commit like :cspatttern")).params(
            cspatttern=commit + "%")
    elif vcs_type == "hg":
        q = q.filter(sa.text("hg_changeset like :cspatttern")).params(
            cspatttern=commit + "%")
    try:
        row = q.one()
        return "%s %s" % (row.git_commit, row.hg_changeset)
    except NoResultFound:
        if vcs_type == "git":
            abort(404, "No hg changeset found for git commit id %s in project(s) %s"
                  % (commit, projects))
        elif vcs_type == "hg":
            abort(404, "No git commit found for hg changeset %s in project(s) %s"
                  % (commit, projects))
    except MultipleResultsFound:
        abort(500, "Internal error - multiple results returned for %s commit %s"
              "in project %s - this should not be possible in database"
              % (vcs_type, commit, projects)) 
Example #10
Source File: connection_command.py    From airflow with Apache License 2.0 6 votes vote down vote up
def connections_delete(args):
    """Deletes connection from DB"""
    with create_session() as session:
        try:
            to_delete = (session
                         .query(Connection)
                         .filter(Connection.conn_id == args.conn_id)
                         .one())
        except exc.NoResultFound:
            msg = '\n\tDid not find a connection with `conn_id`={conn_id}\n'
            msg = msg.format(conn_id=args.conn_id)
            print(msg)
            return
        except exc.MultipleResultsFound:
            msg = ('\n\tFound more than one connection with ' +
                   '`conn_id`={conn_id}\n')
            msg = msg.format(conn_id=args.conn_id)
            print(msg)
            return
        else:
            deleted_conn_id = to_delete.conn_id
            session.delete(to_delete)
            msg = '\n\tSuccessfully deleted `conn_id`={conn_id}\n'
            msg = msg.format(conn_id=deleted_conn_id)
            print(msg) 
Example #11
Source File: sqlalchemy_scheduler_models.py    From celery_sqlalchemy_scheduler with MIT License 6 votes vote down vote up
def from_schedule(cls, dbsession, schedule):
        spec = {'minute': schedule._orig_minute,
                'hour': schedule._orig_hour,
                'day_of_week': schedule._orig_day_of_week,
                'day_of_month': schedule._orig_day_of_month,
                'month_of_year': schedule._orig_month_of_year}
        try:
            query = dbsession.query(CrontabSchedule)
            query = query.filter_by(**spec)
            existing = query.one()
            return existing
        except NoResultFound:
            return cls(**spec)
        except MultipleResultsFound:
            query = dbsession.query(CrontabSchedule)
            query = query.filter_by(**spec)
            query.delete()
            dbsession.commit()
            return cls(**spec) 
Example #12
Source File: manager.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def has_tracking_record(
        self, upstream_application_name: str, pipeline_id: int, notification_id: int
    ) -> bool:
        query = self.session.query(self.tracking_record_class)
        application_name_field = (
            self.tracking_record_class.application_name  # type: ignore
        )
        upstream_name_field = (
            self.tracking_record_class.upstream_application_name  # type: ignore
        )
        pipeline_id_field = self.tracking_record_class.pipeline_id  # type: ignore
        notification_id_field = (
            self.tracking_record_class.notification_id  # type: ignore
        )

        query = query.filter(application_name_field == self.application_name)
        query = query.filter(upstream_name_field == upstream_application_name)
        query = query.filter(pipeline_id_field == pipeline_id)
        query = query.filter(notification_id_field == notification_id)
        try:
            query.one()
        except (MultipleResultsFound, NoResultFound):
            return False
        else:
            return True 
Example #13
Source File: utils.py    From fabric8-analytics-server with Apache License 2.0 6 votes vote down vote up
def retrieve_worker_result(rdb, external_request_id, worker):
    """Retrieve results for selected worker from RDB."""
    start = datetime.datetime.now()
    try:
        query = rdb.session.query(WorkerResult) \
                           .filter(WorkerResult.external_request_id == external_request_id,
                                   WorkerResult.worker == worker)
        result = query.one()
    except (NoResultFound, MultipleResultsFound):
        return None
    except SQLAlchemyError:
        rdb.session.rollback()
        raise
    result_dict = result.to_dict()

    # compute elapsed time
    elapsed_seconds = (datetime.datetime.now() - start).total_seconds()
    msg = "It took {t} seconds to retrieve {w} " \
          "worker results for {r}.".format(t=elapsed_seconds, w=worker, r=external_request_id)
    current_app.logger.debug(msg)

    return result_dict 
Example #14
Source File: __init__.py    From build-relengapi with Mozilla Public License 2.0 6 votes vote down vote up
def insert_one(project, git_commit, hg_changeset):
    # (documentation in relengapi/docs/usage/mapper.rst)
    session = g.db.session(DB_DECLARATIVE_BASE)
    proj = _get_project(session, project)  # can raise HTTP 404 or HTTP 500
    _add_hash(session, git_commit, hg_changeset, proj)  # can raise HTTP 400
    try:
        session.commit()
        q = Hash.query.join(Project).filter(_project_filter(project))
        q = q.filter(sa.text("git_commit == :commit")).params(commit=git_commit)
        return q.one().as_json()
    except sa.exc.IntegrityError:
        abort(409, "Provided mapping %s %s for project %s already exists and "
              "cannot be reinserted" % (git_commit, hg_changeset, project))
    except NoResultFound:
        abort(500, "Provided mapping %s %s for project %s could not be inserted "
              "into the database" % (git_commit, hg_changeset, project))
    except MultipleResultsFound:
        abort(500, "Provided mapping %s %s for project %s has been inserted into "
              "the database multiple times" % (git_commit, hg_changeset, project)) 
Example #15
Source File: utils.py    From fabric8-analytics-server with Apache License 2.0 6 votes vote down vote up
def retrieve_worker_results(rdb, external_request_id):
    """Retrieve results for all workers from RDB."""
    start = datetime.datetime.now()
    try:
        query = rdb.session.query(WorkerResult) \
                           .filter(WorkerResult.external_request_id == external_request_id)
        results = query.all()
    except (NoResultFound, MultipleResultsFound):
        return None
    except SQLAlchemyError:
        rdb.session.rollback()
        raise

    # compute elapsed time
    elapsed_seconds = (datetime.datetime.now() - start).total_seconds()
    msg = "It took {t} seconds to retrieve " \
          "all worker results for {r}.".format(t=elapsed_seconds, r=external_request_id)
    current_app.logger.debug(msg)

    return results 
Example #16
Source File: manager.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_record(self, sequence_id: UUID, position: int) -> Any:
        """
        Gets record at position in sequence.
        """
        try:
            filter_args = {self.field_names.sequence_id: sequence_id}

            query = self.filter_by(**filter_args)

            query = self.filter_for_application_name(query)

            position_field = getattr(self.record_class, self.field_names.position)
            query = query.filter(position_field == position)
            return query.one()
        except (NoResultFound, MultipleResultsFound):
            raise IndexError(self.application_name, sequence_id, position) 
Example #17
Source File: db.py    From gitlab with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_login(self, mxid: UserID, url: str, token: str) -> None:
        token_row = Token(user_id=mxid, gitlab_server=url, api_token=token)
        default = Default(user_id=mxid, gitlab_server=url)
        s = self.Session()
        try:
            s.add(token_row)
            s.query(Default).filter(Default.user_id == mxid).one()
        except NoResultFound:
            s.add(default)
        except MultipleResultsFound as e:
            log.warning("Multiple default servers found.")
            log.warning(e)
            raise e
        s.commit() 
Example #18
Source File: api.py    From zun with Apache License 2.0 5 votes vote down vote up
def _get_resource_provider_by_name(self, context, provider_name):
        query = model_query(models.ResourceProvider)
        query = query.filter_by(name=provider_name)
        try:
            return query.one()
        except NoResultFound:
            raise exception.ResourceProviderNotFound(
                resource_provider=provider_name)
        except MultipleResultsFound:
            raise exception.Conflict('Multiple resource providers exist with '
                                     'same name. Please use the uuid instead.') 
Example #19
Source File: category.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def find_or_create(cls, session, namespace_id, name, display_name, type_):
        name = name or ''

        objects = session.query(cls).filter(
            cls.namespace_id == namespace_id,
            cls.display_name == display_name).all()

        if not objects:
            obj = cls(namespace_id=namespace_id, name=name,
                      display_name=display_name, type_=type_,
                      deleted_at=EPOCH)
            session.add(obj)
        elif len(objects) == 1:
            obj = objects[0]
            if not obj.name:
                # There is an existing category with this `display_name` and no
                # `name`, so update it's `name` as needed.
                # This is needed because the first time we sync generic IMAP
                # folders, they may initially have `name` == '' but later they may
                # get a `name`. At this point, it *is* the same folder so we
                # merely want to update its `name`, not create a new one.
                obj.name = name
        else:
            log.error('Duplicate category rows for namespace_id {}, '
                      'name {}, display_name: {}'.
                      format(namespace_id, name, display_name))
            raise MultipleResultsFound(
                'Duplicate category rows for namespace_id {}, name {}, '
                'display_name: {}'.format(namespace_id, name, display_name))

        return obj 
Example #20
Source File: app.py    From commandment with MIT License 5 votes vote down vote up
def ota_enroll():
    """Over-The-Air Profile Delivery Phase 1.5.

    This endpoint represents the delivery of the `Profile Service` profile that should be delivered AFTER the user has
    successfully authenticated.
    """
    try:
        org = db.session.query(Organization).one()
    except NoResultFound:
        abort(500, 'No organization is configured, cannot generate enrollment profile.')
    except MultipleResultsFound:
        abort(500, 'Multiple organizations, backup your database and start again')

    profile = {
        'PayloadType': 'Profile Service',
        'PayloadIdentifier': org.payload_prefix + '.ota.enroll',
        'PayloadUUID': 'FACC45E7-CB0E-4F8B-AA3E-E22DC161E25E', #str(uuid4()),
        'PayloadVersion': 1,
        'PayloadDisplayName': 'Commandment Profile Service',
        'PayloadDescription': 'Enrolls your device with Commandment',
        'PayloadOrganization': org.name,
        'PayloadContent': {
            'URL': 'https://{}:{}/enroll/ota_authenticate'.format(
                current_app.config['PUBLIC_HOSTNAME'], current_app.config['PORT']
            ),
            'DeviceAttributes': list(AllDeviceAttributes),
            'Challenge': 'TODO',
        },
    }
    plist_data = dumps_none(profile)

    return plist_data, 200, {'Content-Type': PROFILE_CONTENT_TYPE} 
Example #21
Source File: test_model_manager.py    From flask-unchained with MIT License 5 votes vote down vote up
def test_get_by(self, db: SQLAlchemyUnchained):
        Foo, foo_manager = setup(db)

        foo1 = foo_manager.create(name='one')
        foo_1 = foo_manager.create(name='one')
        foo2 = foo_manager.create(name='two')
        foo_manager.commit()

        assert foo_manager.get_by(name='fail') is None
        with pytest.raises(MultipleResultsFound):
            foo_manager.get_by(name='one')

        assert foo_manager.get_by(name='two') == foo2 
Example #22
Source File: diary.py    From choochoo with GNU General Public License v2.0 5 votes vote down vote up
def copy_diary_topic_fields(record, old_s, old, old_diary_topic, new):
    log.debug(f'Trying to copy diary_topic_fields for diary_topic {old_diary_topic}')
    diary_topic_field = old.meta.tables['diary_topic_field']
    for old_diary_topic_field in old_s.query(diary_topic_field). \
            filter(diary_topic_field.c.diary_topic_id ==
                   (old_diary_topic.id if old_diary_topic else None)).all():
        log.debug(f'Found old diary_topic_field {old_diary_topic_field}')
        try:
            statistic_name = old.meta.tables['statistic_name']
            old_statistic_name = old_s.query(statistic_name). \
                filter(statistic_name.c.id == old_diary_topic_field.statistic_name_id).one()
            log.debug(f'Found old statistic_name {old_statistic_name}')
            # changes for acooke config 0.31 - 0.32
            if old_statistic_name.name == 'Notes':
                if old_diary_topic.name == 'Multiple Sclerosis':
                    record.warning('Renaming Notes to MS Notes')
                    old_statistic_name = clone_with(old_statistic_name, name='MS Notes')
                elif old_diary_topic.name == 'Broken Femur LHS':
                    record.warning('Renaming Notes to Leg Notes')
                    old_statistic_name = clone_with(old_statistic_name, name='Leg Notes')
            with new.session_context() as new_s:
                try:
                    new_statistic_name = match_statistic_name(record, old_statistic_name, new_s, DiaryTopic)
                    copy_diary_topic_journal_entries(record, old_s, old, old_statistic_name, new_s, new_statistic_name)
                except MultipleResultsFound:
                    record.warning(f'Multiple statistics for {old_statistic_name} - '
                                   f'skipping field under topic {old_diary_topic}')
        except:
            log_current_exception()
    parent_id = old_diary_topic.id
    diary_topic = old.meta.tables['diary_topic']
    for old_diary_topic in old_s.query(diary_topic).filter(diary_topic.c.parent_id == parent_id).all():
        log.info(f'Found old diary_topic {old_diary_topic}')
        copy_diary_topic_fields(record, old_s, old, old_diary_topic, new) 
Example #23
Source File: CRUDModel.py    From TensorHive with Apache License 2.0 5 votes vote down vote up
def get(cls, id):
        try:
            result = db_session.query(cls).filter_by(id=id).one()
        except MultipleResultsFound:
            msg = 'There are multiple {} records with the same id={}!'.format(cls.__name__, id)
            log.critical(msg)
            raise MultipleResultsFound(msg)
        except NoResultFound:
            msg = 'There is no record {} with id={}!'.format(cls.__name__, id)
            log.debug(msg)
            raise NoResultFound(msg)
        else:
            return result 
Example #24
Source File: User.py    From TensorHive with Apache License 2.0 5 votes vote down vote up
def find_by_username(cls, username):
        try:
            result = db_session.query(cls).filter_by(username=username).one()
        except MultipleResultsFound:
            # Theoretically cannot happen because of model built-in constraints
            msg = 'Multiple users with identical usernames has been found!'
            log.critical(msg)
            raise MultipleResultsFound(msg)
        except NoResultFound:
            msg = 'There is no user with username={}!'.format(username)
            log.warning(msg)
            raise NoResultFound(msg)
        else:
            return result 
Example #25
Source File: test_baked.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_one_or_none_multiple_result(self):
        User = self.classes.User

        bq = self.bakery(lambda s: s.query(User))
        bq += lambda q: q.filter(User.name.like("%ed%"))

        assert_raises_message(
            orm_exc.MultipleResultsFound,
            "Multiple rows were found when one or none was required",
            bq(Session()).one_or_none,
        ) 
Example #26
Source File: test_baked.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_one_multiple_result(self):
        User = self.classes.User

        bq = self.bakery(lambda s: s.query(User))
        bq += lambda q: q.filter(User.name.like("%ed%"))

        assert_raises_message(
            orm_exc.MultipleResultsFound,
            "Multiple rows were found when exactly one was required",
            bq(Session()).one,
        ) 
Example #27
Source File: test_mapper.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def hash_pair_exists(app, git, hg):
    session = app.db.session(DB_DECLARATIVE_BASE)
    try:
        session.query(Hash).filter(Hash.hg_changeset == hg).filter(
            Hash.git_commit == git).one()
        return True
    except (MultipleResultsFound, NoResultFound):
        return False 
Example #28
Source File: model.py    From open-raadsinformatie with MIT License 5 votes vote down vote up
def _merge(self, predicate, column, value):
        """Tries to set the ORI identifier of an existing Resource on the model. It tries to find the Resource by
        filtering on a Property with the given predicate and value in the specified column."""
        try:
            self.ori_identifier = self.db.get_mergeable_resource_identifier(self, predicate, column, value)
        except (NoResultFound, MultipleResultsFound, ValueError) as e:
            log.warning(f'Unable to merge: {str(e)}') 
Example #29
Source File: api.py    From zun with Apache License 2.0 5 votes vote down vote up
def get_container_by_name(self, context, container_type, container_name):
        query = model_query(models.Container)
        query = self._add_project_filters(context, query)
        query = self._add_container_type_filter(container_type, query)
        query = query.filter_by(name=container_name)
        try:
            return query.one()
        except NoResultFound:
            raise exception.ContainerNotFound(container=container_name)
        except MultipleResultsFound:
            raise exception.Conflict('Multiple containers exist with same '
                                     'name. Please use the container uuid '
                                     'instead.') 
Example #30
Source File: api.py    From zun with Apache License 2.0 5 votes vote down vote up
def get_compute_node_by_hostname(self, context, hostname):
        query = model_query(models.ComputeNode)
        query = query.filter_by(hostname=hostname)
        try:
            return query.one()
        except NoResultFound:
            raise exception.ComputeNodeNotFound(
                compute_node=hostname)
        except MultipleResultsFound:
            raise exception.Conflict('Multiple compute nodes exist with same '
                                     'hostname. Please use the uuid instead.')