Python sqlalchemy.exc.InvalidRequestError() Examples

The following are 30 code examples of sqlalchemy.exc.InvalidRequestError(). 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_deprecations.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_ambiguous_column_case_sensitive(self):
        with testing.expect_deprecated(
            "The create_engine.case_sensitive parameter is deprecated"
        ):
            eng = engines.testing_engine(options=dict(case_sensitive=False))

        with eng.connect() as conn:
            row = conn.execute(
                select(
                    [
                        literal_column("1").label("SOMECOL"),
                        literal_column("1").label("SOMECOL"),
                    ]
                )
            ).first()

            assert_raises_message(
                exc.InvalidRequestError,
                "Ambiguous column name",
                lambda: row._mapping["somecol"],
            ) 
Example #2
Source File: test_import_fence.py    From fence with Apache License 2.0 6 votes vote down vote up
def reload_modules(module_name):
    """
    Reload all of fence's submodules.

    Use this after patching ``local_settings.py`` not existing, to make sure
    that nothing will remember that it existed.
    """
    # First we have to convince fence that ``local_settings.py`` does not
    # actually exist, even if it does. To do this, patch-delete the attribute
    # and reload all the fence modules.
    fence_submodules = [
        module for module in list(sys.modules.keys()) if module.startswith(module_name)
    ]
    for module in fence_submodules:
        if sys.modules[module]:
            # SQLAlchemy gets upset when a table is loaded twice, so ignore
            # that.
            try:
                importlib.reload(sys.modules[module])
            except InvalidRequestError:
                pass 
Example #3
Source File: LogOperate.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def page_select_attack(self, page_index):
        try:
            page_size = 10
            # num = 10*int(page) - 10
            logselect = self.session.query(OpencanaryLog).filter(
                OpencanaryLog.white == 2).order_by(
                    desc(OpencanaryLog.local_time),
                    OpencanaryLog.id).limit(page_size).offset(
                        (page_index - 1) * page_size)
            return logselect
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print(e)
        finally:
            self.session.close()

    # 查询日志表白名单数据 
Example #4
Source File: LogOperate.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def page_select_white(self, page_index):
        try:
            page_size = 10
            # num = 10*int(page) - 10
            logselect = self.session.query(OpencanaryLog).filter(
                OpencanaryLog.white == 1).order_by(
                    desc(OpencanaryLog.local_time),
                    OpencanaryLog.id).limit(page_size).offset(
                        (page_index - 1) * page_size)
            return logselect
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print(e)
        finally:
            self.session.close()

    # 查询当年每月攻击数量 
Example #5
Source File: LogOperate.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def white_select_num(self, months):
        try:
            white_num = self.session.query(
                extract('month', OpencanaryLog.local_time).label('month'),
                func.count('*').label('count')).filter(
                    extract('year', OpencanaryLog.local_time) == months,
                    OpencanaryLog.white == 1).group_by('month').all()
            return white_num
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print(e)
        finally:
            self.session.close()

    # 查询各类攻击数量 
Example #6
Source File: LogOperate.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pie_select_num(self, years):
        try:
            pie_num = self.session.query(
                func.count(OpencanaryLog.logtype),
                OpencanaryLog.logtype).group_by(OpencanaryLog.logtype).filter(
                    extract('year', OpencanaryLog.local_time) == years,
                    OpencanaryLog.white == 2).all()
            return pie_num
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print(e)
        finally:
            self.session.close()

    # 查询攻击数据总量 
Example #7
Source File: test_db.py    From hobbit-core with MIT License 6 votes vote down vote up
def test_nested_self_raise(self, session, assert_session):
        @transaction(session)
        def create_user():
            user = User(username='test1', email='1@b.com', password='1')
            db.session.add(user)

        @transaction(session)
        def view_func():
            user = User(username='test2', email='2@b.com', password='1')
            db.session.add(user)
            create_user()

        if session.autocommit is False:
            msg = 'This transaction is closed'
            with pytest.raises(ResourceClosedError, match=msg):
                view_func()
        else:
            msg = r'A transaction is already begun.*'
            with pytest.raises(InvalidRequestError, match=msg):
                view_func()
        assert len(assert_session.query(User).all()) == 0 
Example #8
Source File: base.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def init_services(self):
        path_services = [self.path / "eNMS" / "services"]
        if self.settings["paths"]["custom_services"]:
            path_services.append(Path(self.settings["paths"]["custom_services"]))
        for path in path_services:
            for file in path.glob("**/*.py"):
                if "init" in str(file):
                    continue
                if not self.settings["app"]["create_examples"] and "examples" in str(
                    file
                ):
                    continue
                info(f"Loading service: {file}")
                spec = spec_from_file_location(str(file).split("/")[-1][:-3], str(file))
                try:
                    spec.loader.exec_module(module_from_spec(spec))
                except InvalidRequestError as exc:
                    error(f"Error loading custom service '{file}' ({str(exc)})") 
Example #9
Source File: __init__.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def create(cls, message, object, stage=u'Fetch', line=None):
        '''
        Helper function to create an error object and save it.
        '''
        err = cls(message=message, object=object,
                  stage=stage, line=line)
        try:
            err.save()
        except InvalidRequestError, e:
            # Clear any in-progress sqlalchemy transactions
            try:
                Session.rollback()
            except:
                pass
            try:
                Session.remove()
            except:
                pass
            err.save() 
Example #10
Source File: test_events.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_remove_not_listened(self):
        Target = self._fixture()

        m1 = Mock()

        t1 = Target()

        event.listen(t1, "event_one", m1, propagate=True)
        event.listen(t1, "event_three", m1)

        event.remove(t1, "event_one", m1)
        assert_raises_message(
            exc.InvalidRequestError,
            r"No listeners found for event <.*Target.*> / "
            r"'event_two' / <Mock.*> ",
            event.remove,
            t1,
            "event_two",
            m1,
        )

        event.remove(t1, "event_three", m1) 
Example #11
Source File: cx_oracle.py    From planespotter with MIT License 6 votes vote down vote up
def _handle_out_parameters(self):
        # if a single execute, check for outparams
        if len(self.compiled_parameters) == 1:
            quoted_bind_names = self.compiled._quoted_bind_names
            for bindparam in self.compiled.binds.values():
                if bindparam.isoutparam:
                    name = self.compiled.bind_names[bindparam]
                    type_impl = bindparam.type.dialect_impl(self.dialect)
                    if hasattr(type_impl, '_cx_oracle_var'):
                        self.out_parameters[name] = type_impl._cx_oracle_var(
                            self.dialect, self.cursor)
                    else:
                        dbtype = type_impl.get_dbapi_type(self.dialect.dbapi)
                        if dbtype is None:
                            raise exc.InvalidRequestError(
                                "Cannot create out parameter for parameter "
                                "%r - its type %r is not supported by"
                                " cx_oracle" %
                                (bindparam.key, bindparam.type)
                            )
                        self.out_parameters[name] = self.cursor.var(dbtype)
                    self.parameters[0][quoted_bind_names.get(name, name)] = \
                        self.out_parameters[name] 
Example #12
Source File: t_raiseload_col_test.py    From py-mongosql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def assertRaiseloadWorked(self, entity, loaded, raiseloaded, unloaded):
        """ Test columns and their load state

            :param entity: the entity
            :param loaded: column names that are loaded and may be accessed without emitting any sql queries
            :param raiseloaded: column names that will raise an InvalidRequestError when accessed
            :param unloaded: column names that will emit 1 query when accessed
        """
        # loaded
        for name in loaded:
            with ExpectedQueryCounter(self.engine, 0,
                                      'Unexpected query while accessing column {}'.format(name)):
                getattr(entity, name)

        # raiseloaded
        for name in raiseloaded:
            with self.assertRaises(sa_exc.InvalidRequestError, msg='Exception was not raised when accessing attr `{}`'.format(name)):
                getattr(entity, name)

        # unloaded
        for name in unloaded:
            with ExpectedQueryCounter(self.engine, 1,
                                      'Expected one query while accessing column {}'.format(name)):
                getattr(entity, name) 
Example #13
Source File: base.py    From ws-backend-community with GNU General Public License v3.0 6 votes vote down vote up
def tearDown(self):
        """
        Tear down this test case by closing any existing database connection and deleting all of the
        objects that were marked for deletion.
        :return: None
        """
        if len(self.to_delete) > 0:
            for cur_delete in self.to_delete:
                try:
                    self.db_session.delete(cur_delete)
                except InvalidRequestError:
                    continue
            self.db_session.commit()
        if self._db_session is not None:
            self._db_session.close()
        if self._transaction is not None:
            self._transaction.rollback()
        if self._connection is not None:
            self._connection.close()
        super(BaseSqlalchemyTestCase, self).tearDown()

    # Protected Methods

    # Private Methods 
Example #14
Source File: test_transaction.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_inactive_due_to_subtransaction_no_commit(self, local_connection):
        connection = local_connection
        trans = connection.begin()
        trans2 = connection.begin()
        trans2.rollback()
        assert_raises_message(
            exc.InvalidRequestError,
            "This connection is on an inactive transaction.  Please rollback",
            trans.commit,
        )

        trans.rollback()

        assert_raises_message(
            exc.InvalidRequestError,
            "This transaction is inactive",
            trans.commit,
        ) 
Example #15
Source File: test_transaction.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_inactive_due_to_subtransaction_on_nested_no_commit(
        self, local_connection
    ):
        connection = local_connection
        trans = connection.begin()

        nested = connection.begin_nested()

        trans2 = connection.begin()
        trans2.rollback()

        assert_raises_message(
            exc.InvalidRequestError,
            "This connection is on an inactive savepoint transaction.  "
            "Please rollback",
            nested.commit,
        )
        trans.commit()

        assert_raises_message(
            exc.InvalidRequestError,
            "This nested transaction is inactive",
            nested.commit,
        ) 
Example #16
Source File: test_transaction.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_no_autocommit_w_autobegin(self):

        with testing.db.connect() as conn:
            conn.execute(future_select(1))

            assert_raises_message(
                exc.InvalidRequestError,
                "This connection has already begun a transaction; "
                "isolation level may not be altered until transaction end",
                conn.execution_options,
                isolation_level="AUTOCOMMIT",
            )

            conn.rollback()

            conn.execution_options(isolation_level="AUTOCOMMIT") 
Example #17
Source File: test_transaction.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_branch_nested_rollback(self, local_connection):
        connection = local_connection
        connection.begin()
        branched = connection.connect()
        assert branched.in_transaction()
        branched.execute(users.insert(), user_id=1, user_name="user1")
        nested = branched.begin()
        branched.execute(users.insert(), user_id=2, user_name="user2")
        nested.rollback()
        assert not connection.in_transaction()

        assert_raises_message(
            exc.InvalidRequestError,
            "This connection is on an inactive transaction.  Please",
            connection.exec_driver_sql,
            "select 1",
        ) 
Example #18
Source File: test_dialect.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_minimum_version(self):
        with mock.patch(
            "sqlalchemy.dialects.oracle.cx_oracle.OracleDialect_cx_oracle."
            "_parse_cx_oracle_ver",
            lambda self, vers: (5, 1, 5),
        ):
            assert_raises_message(
                exc.InvalidRequestError,
                "cx_Oracle version 5.2 and above are supported",
                cx_oracle.OracleDialect_cx_oracle,
                dbapi=Mock(),
            )

        with mock.patch(
            "sqlalchemy.dialects.oracle.cx_oracle.OracleDialect_cx_oracle."
            "_parse_cx_oracle_ver",
            lambda self, vers: (5, 3, 1),
        ):
            cx_oracle.OracleDialect_cx_oracle(dbapi=Mock()) 
Example #19
Source File: Whiteip.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def white_ip(self):
        try:
            white_ip_res = self.session.query(Whiteip.src_host).all()
            return white_ip_res
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print (e)
        finally:
            self.session.close()
    
    # 增加白名单 
Example #20
Source File: test_transaction.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_no_marker_on_inactive_trans(self, local_connection):
        conn = local_connection
        conn.begin()

        mk1 = conn.begin()

        mk1.rollback()

        assert_raises_message(
            exc.InvalidRequestError,
            "the current transaction on this connection is inactive.",
            conn.begin,
        ) 
Example #21
Source File: Host.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def select_data(self):
        """查询在线主机"""
        try:
            host_online = self.session.query(Host).filter(
                Host.status == "online").order_by(desc(Host.last_time)).all()
            # print host_online
            return host_online
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print(e)
        finally:
            self.session.close() 
Example #22
Source File: base.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def pre_exec(self):
        if self.isinsert:
            tbl = self.compiled.statement.table
            seq_column = tbl._autoincrement_column
            insert_has_sequence = seq_column is not None

            if insert_has_sequence:
                self._enable_identity_insert = \
                    seq_column.key in self.compiled_parameters[0]
            else:
                self._enable_identity_insert = False

            if self._enable_identity_insert:
                self.cursor.execute(
                    "SET IDENTITY_INSERT %s ON" %
                    self.dialect.identifier_preparer.format_table(tbl))

        if self.isddl:
            # TODO: to enhance this, we can detect "ddl in tran" on the
            # database settings.  this error message should be improved to
            # include a note about that.
            if not self.should_autocommit:
                raise exc.InvalidRequestError(
                    "The Sybase dialect only supports "
                    "DDL in 'autocommit' mode at this time.")

            self.root_connection.engine.logger.info(
                "AUTOCOMMIT (Assuming no Sybase 'ddl in tran')")

            self.set_ddl_autocommit(
                self.root_connection.connection.connection,
                True) 
Example #23
Source File: Whiteip.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def insert_white_ip(self, src_host):
        try:
            wip_insert = Whiteip(src_host=src_host)
            self.session.merge(wip_insert)
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print (e)
        finally:
            self.session.close() 
Example #24
Source File: test_cache.py    From huskar with MIT License 5 votes vote down vote up
def test_make_transient_to_detached_error():
    t = Team(id=0, team_name='233')
    with pytest.raises(sa_exc.InvalidRequestError):
        DBSession.add(t)
        make_transient_to_detached(t) 
Example #25
Source File: cli.py    From alchemydumps with MIT License 5 votes vote down vote up
def restore(date_id):
    """Restore a backup based on the date part of the backup files"""

    alchemy = AlchemyDumpsDatabase()
    backup = Backup()

    # loop through mapped classes
    for mapped_class in alchemy.get_mapped_classes():
        class_name = mapped_class.__name__
        name = backup.get_name(class_name, date_id)
        path = backup.target.path / name

        if path.exists():

            # read file contents
            contents = backup.target.read_file(name)
            fails = list()

            # restore to the db
            db = alchemy.db()
            for row in alchemy.parse_data(contents):
                try:
                    db.session.merge(row)
                    db.session.commit()
                except (IntegrityError, InvalidRequestError):
                    db.session.rollback()
                    fails.append(row)

            # print summary
            status = "partially" if len(fails) else "totally"
            success(f"==> {name} {status} restored.")
            for f in fails:
                error(f"    Restore of {f} failed.")
        else:
            os.system("ls alchemydumps-backups")
            msg = (
                f"==> No file found for {class_name} "
                f"({backup.target.path}{name} does not exist)."
            )
            error(msg) 
Example #26
Source File: base.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def pre_exec(self):
        if self.isinsert:
            tbl = self.compiled.statement.table
            seq_column = tbl._autoincrement_column
            insert_has_sequence = seq_column is not None

            if insert_has_sequence:
                self._enable_identity_insert = \
                    seq_column.key in self.compiled_parameters[0]
            else:
                self._enable_identity_insert = False

            if self._enable_identity_insert:
                self.cursor.execute(
                    "SET IDENTITY_INSERT %s ON" %
                    self.dialect.identifier_preparer.format_table(tbl))

        if self.isddl:
            # TODO: to enhance this, we can detect "ddl in tran" on the
            # database settings.  this error message should be improved to
            # include a note about that.
            if not self.should_autocommit:
                raise exc.InvalidRequestError(
                    "The Sybase dialect only supports "
                    "DDL in 'autocommit' mode at this time.")

            self.root_connection.engine.logger.info(
                "AUTOCOMMIT (Assuming no Sybase 'ddl in tran')")

            self.set_ddl_autocommit(
                self.root_connection.connection.connection,
                True) 
Example #27
Source File: Whiteport.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_white_port(self):
        try:
            self.session.query(Whiteport).delete()
            self.session.commit()
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print(e)
        finally:
            self.session.close() 
Example #28
Source File: Whiteport.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def insert_white_port(self, dst_port):
        try:
            wip_insert = Whiteport(dst_port=dst_port)
            self.session.merge(wip_insert)
            self.session.commit()
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print(e)
        finally:
            self.session.close()

    # 删除白名单端口表数据 
Example #29
Source File: sql_storage.py    From Fox-V3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def _session_finish(self, session, statement_text=None):
        from sqlalchemy.exc import InvalidRequestError
        try:
            if not self.read_only:
                session.commit()
            else:
                session.rollback()
        except InvalidRequestError:
            # Log the statement text and the exception
            self.logger.exception(statement_text)
        finally:
            session.close() 
Example #30
Source File: Whiteport.py    From opencanary_web with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def select_white_port(self):
        try:
            white_port_res = self.session.query(Whiteport.dst_port).all()
            return white_port_res
        except InvalidRequestError:
            self.session.rollback()
        except Exception as e:
            print(e)
        finally:
            self.session.close()
    
    # 增加白名单