Python sqlalchemy.exc.StatementError() Examples

The following are 30 code examples of sqlalchemy.exc.StatementError(). 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.exc , or try the search function .
Example #1
Source File: test_insert_exec.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_insert_heterogeneous_params(self):
        """test that executemany parameters are asserted to match the
        parameter set of the first."""
        users = self.tables.users

        assert_raises_message(
            exc.StatementError,
            r"\(sqlalchemy.exc.InvalidRequestError\) A value is required for "
            "bind parameter 'user_name', in "
            "parameter group 2\n"
            r"\[SQL: u?INSERT INTO users",
            users.insert().execute,
            {"user_id": 7, "user_name": "jack"},
            {"user_id": 8, "user_name": "ed"},
            {"user_id": 9},
        )

        # this succeeds however.   We aren't yet doing
        # a length check on all subsequent parameters.
        users.insert().execute(
            {"user_id": 7}, {"user_id": 8, "user_name": "ed"}, {"user_id": 9}
        ) 
Example #2
Source File: shots_service.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_episode_raw(episode_id):
    """
    Return given episode as an active record.
    """
    episode_type = get_episode_type()
    if episode_type is None:
        episode_type = get_episode_type()

    try:
        episode = Entity.get_by(
            entity_type_id=episode_type["id"], id=episode_id
        )
    except StatementError:
        raise EpisodeNotFoundException

    if episode is None:
        raise EpisodeNotFoundException
    return episode 
Example #3
Source File: test_except.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_statement_error_w_code(self):
        try:
            raise sa_exceptions.DBAPIError.instance(
                "select * from table",
                [{"x": 1}],
                sa_exceptions.InvalidRequestError("hello", code="abcd"),
                DatabaseError,
            )
        except sa_exceptions.StatementError as err:
            eq_(
                str(err),
                "(sqlalchemy.exc.InvalidRequestError) hello\n"
                "[SQL: select * from table]\n"
                "[parameters: [{'x': 1}]]\n"
                "(Background on this error at: http://sqlalche.me/e/%s/abcd)"
                % sa_exceptions._version_token,
            )
            eq_(err.args, ("(sqlalchemy.exc.InvalidRequestError) hello",)) 
Example #4
Source File: base.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def delete(self, instance_id):
        """
        Delete a model corresponding at given ID and return it as a JSON
        object.
        """
        instance = self.get_model_or_404(instance_id)

        try:
            instance_dict = instance.serialize()
            self.check_delete_permissions(instance_dict)
            self.pre_delete(instance_dict)
            instance.delete()
            self.emit_delete_event(instance_dict)
            self.post_delete(instance_dict)

        except IntegrityError as exception:
            current_app.logger.error(str(exception), exc_info=1)
            return {"message": str(exception)}, 400

        except StatementError as exception:
            current_app.logger.error(str(exception), exc_info=1)
            return {"message": str(exception)}, 400

        return "", 204 
Example #5
Source File: test_transaction_retry.py    From nameko-sqlalchemy with Apache License 2.0 6 votes vote down vote up
def test_raises_error_if_cannot_reconnect(
    toxiproxy_db_session, disconnect, toxiproxy
):
    if not toxiproxy:
        pytest.skip('Toxiproxy not installed')

    toxiproxy_db_session.add(ExampleModel(data='hello1'))
    toxiproxy_db_session.add(ExampleModel(data='hello2'))
    toxiproxy_db_session.commit()

    disconnect(reconnect=False)

    @transaction_retry
    def get_model_count():
        return toxiproxy_db_session.query(ExampleModel).count()

    with pytest.raises(StatementError):
        get_model_count() 
Example #6
Source File: base.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def get(self, instance_id):
        """
        Retrieve a model corresponding at given ID and return it as a JSON
        object.
        """
        try:
            instance = self.get_model_or_404(instance_id)
            result = self.serialize_instance(instance)
            self.check_read_permissions(result)
            result = self.clean_get_result(result)

        except StatementError as exception:
            current_app.logger.error(str(exception), exc_info=1)
            return {"message": str(exception)}, 400

        except ValueError:
            abort(404)

        return result, 200 
Example #7
Source File: shots_service.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_sequence_raw(sequence_id):
    """
    Return given sequence as an active record.
    """
    sequence_type = get_sequence_type()
    try:
        sequence = Entity.get_by(
            entity_type_id=sequence_type["id"], id=sequence_id
        )
    except StatementError:
        raise SequenceNotFoundException

    if sequence is None:
        raise SequenceNotFoundException

    return sequence 
Example #8
Source File: base_service.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_instance(model, instance_id, exception):
    """
    Get instance of any model from its ID and raise given exception if not
    found.
    """
    if instance_id is None:
        raise exception()

    try:
        instance = model.get(instance_id)
    except StatementError:
        raise exception()

    if instance is None:
        raise exception()

    return instance 
Example #9
Source File: test_query.py    From sqlalchemy with MIT License 6 votes vote down vote up
def _assert_raises(self, stmt, params):
        assert_raises_message(
            exc.StatementError,
            "A value is required for bind parameter 'x'",
            testing.db.execute,
            stmt,
            **params
        )

        assert_raises_message(
            exc.StatementError,
            "A value is required for bind parameter 'x'",
            testing.db.execute,
            stmt,
            params,
        ) 
Example #10
Source File: sqla_regex.py    From aardvark with Apache License 2.0 6 votes vote down vote up
def sqlite_regex_match(element, compiler, **kw):
    """Compile the SQL expression representing a regular expression match
    for the SQLite engine.
    """
    # determine the name of a custom SQLite function to use for the operator
    operator = element.operator.opstring
    try:
        func_name, _ = SQLITE_REGEX_FUNCTIONS[operator]
    except (KeyError, ValueError) as e:
        would_be_sql_string = ' '.join((compiler.process(element.left),
                                        operator,
                                        compiler.process(element.right)))
        raise exc.StatementError(
            "unknown regular expression match operator: %s" % operator,
            would_be_sql_string, None, e)

    # compile the expression as an invocation of the custom function
    regex_func = getattr(func, func_name)
    regex_func_call = regex_func(element.left, element.right)
    return compiler.process(regex_func_call) 
Example #11
Source File: rule.py    From rucio with Apache License 2.0 6 votes vote down vote up
def list_associated_rules_for_file(scope, name, session=None):
    """
    List replication rules a file is affected from.

    :param scope:   Scope of the file.
    :param name:    Name of the file.
    :param session: The database session in use.
    :raises:        RucioException
    """

    rucio.core.did.get_did(scope=scope, name=name, session=session)  # Check if the did acually exists
    query = session.query(models.ReplicationRule).\
        with_hint(models.ReplicaLock, "INDEX(LOCKS LOCKS_PK)", 'oracle').\
        join(models.ReplicaLock, models.ReplicationRule.id == models.ReplicaLock.rule_id).\
        filter(models.ReplicaLock.scope == scope, models.ReplicaLock.name == name).distinct()
    try:
        for rule in query.yield_per(5):
            d = {}
            for column in rule.__table__.columns:
                d[column.name] = getattr(rule, column.name)
            yield d
    except StatementError:
        raise RucioException('Badly formatted input (IDs?)') 
Example #12
Source File: rule.py    From rucio with Apache License 2.0 6 votes vote down vote up
def list_rule_history(rule_id, session=None):
    """
    List the rule history of a rule.

    :param rule_id: The id of the rule.
    :param session: The database session in use.
    :raises:        RucioException
    """

    query = session.query(models.ReplicationRuleHistoryRecent.updated_at,
                          models.ReplicationRuleHistoryRecent.state,
                          models.ReplicationRuleHistoryRecent.locks_ok_cnt,
                          models.ReplicationRuleHistoryRecent.locks_stuck_cnt,
                          models.ReplicationRuleHistoryRecent.locks_replicating_cnt).filter_by(id=rule_id).order_by(models.ReplicationRuleHistoryRecent.updated_at)

    try:
        for rule in query.yield_per(5):
            yield {'updated_at': rule[0], 'state': rule[1], 'locks_ok_cnt': rule[2], 'locks_stuck_cnt': rule[3], 'locks_replicating_cnt': rule[4]}
    except StatementError:
        raise RucioException('Badly formatted input (IDs?)') 
Example #13
Source File: test_sqlalchemy.py    From airflow with Apache License 2.0 6 votes vote down vote up
def test_process_bind_param_naive(self):
        """
        Check if naive datetimes are prevented from saving to the db
        """
        dag_id = 'test_process_bind_param_naive'

        # naive
        start_date = datetime.datetime.now()
        dag = DAG(dag_id=dag_id, start_date=start_date)
        dag.clear()

        with self.assertRaises((ValueError, StatementError)):
            dag.create_dagrun(
                run_id=start_date.isoformat,
                state=State.NONE,
                execution_date=start_date,
                start_date=start_date,
                session=self.session
            )
        dag.clear() 
Example #14
Source File: subscription.py    From rucio with Apache License 2.0 6 votes vote down vote up
def get_subscription_by_id(subscription_id, session=None):
    """
    Get a specific subscription by id.

    :param subscription_id: The subscription_id to select.
    :param session: The database session in use.
    :raises: SubscriptionNotFound if no Subscription can be found.
    """

    try:
        subscription = session.query(models.Subscription).filter_by(id=subscription_id).one()
        result = {}
        for column in subscription.__table__.columns:
            result[column.name] = getattr(subscription, column.name)
        return result

    except NoResultFound:
        raise SubscriptionNotFound('No subscription with the id %s found' % (subscription_id))
    except StatementError:
        raise RucioException('Badly formatted subscription id (%s)' % (subscription_id)) 
Example #15
Source File: utils.py    From designate with Apache License 2.0 6 votes vote down vote up
def check_marker(table, marker, session):

    marker_query = select([table]).where(table.c.id == marker)

    try:
        marker_resultproxy = session.execute(marker_query)
        marker = marker_resultproxy.fetchone()
        if marker is None:
            raise exceptions.MarkerNotFound(
                'Marker %s could not be found' % marker)
    except oslo_db_exception.DBError as e:
        # Malformed UUIDs return StatementError wrapped in a
        # DBError
        if isinstance(e.inner_exception,
                      sqlalchemy_exc.StatementError):
            raise exceptions.InvalidMarker()
        else:
            raise

    return marker 
Example #16
Source File: backend.py    From lux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_token(self, request, key):
        odm = request.app.odm()
        token = odm.token
        with odm.begin() as session:
            query = session.query(token).options(joinedload(token.user))
            try:
                token = query.get(key)
            except StatementError:
                raise BadRequest from None
        return token 
Example #17
Source File: test_sqlite.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_string_dates_passed_raise(self, connection):
        assert_raises(
            exc.StatementError,
            connection.execute,
            select([1]).where(bindparam("date", type_=Date)),
            date=str(datetime.date(2007, 10, 30)),
        ) 
Example #18
Source File: test_orm.py    From nativeauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_wrong_pwd_type(tmpdir, app):
    with pytest.raises(StatementError):
        user = UserInfo(username='john', password='pwd', email='john@john.com')
        app.db.add(user)
        UserInfo.find(app.db, 'john') 
Example #19
Source File: _manage_api.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def commit_wrapper(self, session):
        with super(ManageAPIAuthDBConnector, self).commit_wrapper(session):
            try:
                yield
            except StatementError as exc:
                raise ManageAPIError("Execution of the SQL statement: {!r} caused "
                                     "an error: {!r}".format(exc.statement, exc.message))
            except Exception as exc:
                raise ManageAPIError("Fatal error: {}".format(ascii_str(exc))) 
Example #20
Source File: test_column.py    From AnyBlok with Mozilla Public License 2.0 5 votes vote down vote up
def test_selection_change_by_query(self):
        SELECTIONS = [
            ('admin', 'Admin'),
            ('regular-user', 'Regular user')
        ]

        registry = self.init_registry(
            simple_column, ColumnType=Selection, selections=SELECTIONS)
        registry.Test.insert(col=SELECTIONS[0][0])
        with pytest.raises(StatementError):
            registry.Test.query().update({'col': 'bad value'}) 
Example #21
Source File: tasks_service.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_comment_raw(comment_id):
    """
    Return comment matching give id as an active record.
    """
    try:
        comment = Comment.get(comment_id)
    except StatementError:
        raise CommentNotFoundException()

    if comment is None:
        raise CommentNotFoundException()
    return comment 
Example #22
Source File: util.py    From dokomoforms with GNU General Public License v3.0 5 votes vote down vote up
def current_user_model(self):
        """Return the current logged in User, or None."""
        current_user_id = self._current_user_cookie()
        if current_user_id:
            cuid = to_unicode(current_user_id)
            try:
                return self.session.query(User).get(cuid)
            except StatementError:
                self.clear_cookie('user')
        return None 
Example #23
Source File: test_except.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_statement_error_no_code(self):
        try:
            raise sa_exceptions.DBAPIError.instance(
                "select * from table",
                [{"x": 1}],
                sa_exceptions.InvalidRequestError("hello"),
                DatabaseError,
            )
        except sa_exceptions.StatementError as err:
            eq_(
                str(err),
                "(sqlalchemy.exc.InvalidRequestError) hello\n"
                "[SQL: select * from table]\n[parameters: [{'x': 1}]]",
            )
            eq_(err.args, ("(sqlalchemy.exc.InvalidRequestError) hello",)) 
Example #24
Source File: test_model.py    From grimoirelab-sortinghat with GNU General Public License v3.0 5 votes vote down vote up
def test_is_bot_invalid_type(self):
        """Check invalid values on is_bot bool column"""

        with self.assertRaisesRegex(StatementError, INVALID_DATATYPE_ERROR):
            uid = UniqueIdentity(uuid='John Smith')
            self.session.add(uid)

            prf = Profile(uuid='John Smith', name='John Smith', is_bot='True')

            self.session.add(prf)
            self.session.commit() 
Example #25
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_oursql_error_one(self):
        set_table = self._set_fixture_one()
        set_table.create()
        assert_raises(
            exc.StatementError,
            set_table.insert().execute,
            e1="c",
            e2="c",
            e3="c",
            e4="c",
        ) 
Example #26
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_lookup_failure(self, connection):
        assert_raises(
            exc.StatementError,
            connection.execute,
            self.tables["non_native_enum_table"].insert(),
            {"id": 4, "someotherenum": "four"},
        ) 
Example #27
Source File: test_defaults.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_missing_many_param(self, connection):
        t = self.tables.default_test
        assert_raises_message(
            exc.StatementError,
            "A value is required for bind parameter 'col7', in parameter "
            "group 1",
            connection.execute,
            t.insert(),
            [
                {"col4": 7, "col7": 12, "col8": 19},
                {"col4": 7, "col8": 19},
                {"col4": 7, "col7": 12, "col8": 19},
            ],
        ) 
Example #28
Source File: test_query.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_expanding_in(self, connection):
        connection.execute(
            users.insert(),
            [
                dict(user_id=7, user_name="jack"),
                dict(user_id=8, user_name="fred"),
                dict(user_id=9, user_name=None),
            ],
        )

        stmt = (
            select([users])
            .where(users.c.user_name.in_(bindparam("uname", expanding=True)))
            .order_by(users.c.user_id)
        )

        eq_(
            connection.execute(stmt, {"uname": ["jack"]}).fetchall(),
            [(7, "jack")],
        )

        eq_(
            connection.execute(stmt, {"uname": ["jack", "fred"]}).fetchall(),
            [(7, "jack"), (8, "fred")],
        )

        eq_(connection.execute(stmt, {"uname": []}).fetchall(), [])

        assert_raises_message(
            exc.StatementError,
            "'expanding' parameters can't be used with executemany()",
            connection.execute,
            users.update().where(
                users.c.user_name.in_(bindparam("uname", expanding=True))
            ),
            [{"uname": ["fred"]}, {"uname": ["ed"]}],
        ) 
Example #29
Source File: test_query.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_filter_with_transient_dont_assume_pk(self):
        self._fixture1()
        User, Address = self.classes.User, self.classes.Address

        sess = Session()

        q = sess.query(Address).filter(Address.user == User())
        assert_raises_message(
            sa_exc.StatementError,
            "Can't resolve value for column users.id on object "
            ".User at .*; no value has been set for this column",
            q.all,
        ) 
Example #30
Source File: test_fields_sqlalchemy.py    From depot with MIT License 5 votes vote down vote up
def test_check_assigned_type(self):
        doc = Document(name=u_('Foo'))
        doc.photo = UploadedFile(open(self.fake_file.name, 'rb'))
        DBSession.add(doc)

        try:
            DBSession.flush()
        except StatementError as e:
            assert 'ValueError' in str(e)
            return

        assert False, 'FLUSH did not raise exception'