sqlalchemy.exc.StatementError

Here are the examples of the python api sqlalchemy.exc.StatementError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

41 Examples 7

3 Source : test_types.py
with Apache License 2.0
from gethue

    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",
        )

    @testing.requires.mysql_non_strict

3 Source : test_sqlite.py
with Apache License 2.0
from gethue

    def test_string_dates_passed_raise(self):
        assert_raises(
            exc.StatementError,
            testing.db.execute,
            select([1]).where(bindparam("date", type_=Date)),
            date=str(datetime.date(2007, 10, 30)),
        )

    def test_cant_parse_datetime_message(self):

3 Source : test_execute.py
with Apache License 2.0
from gethue

    def _test_alter_disconnect(self, orig_error, evt_value):
        engine = engines.testing_engine()

        @event.listens_for(engine, "handle_error")
        def evt(ctx):
            ctx.is_disconnect = evt_value

        with patch.object(
            engine.dialect, "is_disconnect", Mock(return_value=orig_error)
        ):

            with engine.connect() as c:
                try:
                    c.execute("SELECT x FROM nonexistent")
                    assert False
                except tsa.exc.StatementError as st:
                    eq_(st.connection_invalidated, evt_value)

    def test_alter_disconnect_to_true(self):

3 Source : test_query.py
with Apache License 2.0
from gethue

    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,
        )

    def test_filter_with_transient_given_pk(self):

3 Source : test_defaults.py
with Apache License 2.0
from gethue

    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},
        )

    def test_insert_values(self, connection):

3 Source : test_query.py
with Apache License 2.0
from gethue

    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,
        )

    def test_insert(self):

3 Source : test_types.py
with Apache License 2.0
from gethue

    def test_lookup_failure(self):
        assert_raises(
            exc.StatementError,
            self.tables["non_native_enum_table"].insert().execute,
            {"id": 4, "someotherenum": "four"},
        )

    def test_mock_engine_no_prob(self):

3 Source : test_types.py
with Apache License 2.0
from gethue

    def test_nonnative_processor_coerces_to_onezero(self):
        boolean_table = self.tables.boolean_table
        with testing.db.connect() as conn:
            assert_raises_message(
                exc.StatementError,
                "Value 5 is not None, True, or False",
                conn.execute,
                boolean_table.insert(),
                {"id": 1, "unconstrained_value": 5},
            )

    @testing.requires.non_native_boolean_unconstrained

3 Source : test_TeraService.py
with Apache License 2.0
from introlab

    def test_service_port_integer(self):
        new_service = TeraService()
        new_service.service_uuid = 'uuid'
        new_service.service_name = 'Name'
        new_service.service_key = 'key'
        new_service.service_hostname = 'Hostname'
        new_service.service_port = 3
        new_service.service_endpoint = "Endpoint"
        new_service.service_clientendpoint = 'Clientendpoint'
        new_service.service_enabled = 'not a bool'
        new_service.service_system = True
        new_service.service_editable_config = True
        db.session.add(new_service)
        self.assertRaises(exc.StatementError, db.session.commit)

    def test_service_system_integer(self):

3 Source : test_TeraService.py
with Apache License 2.0
from introlab

    def test_service_system_integer(self):
        new_service = TeraService()
        new_service.service_uuid = 'uuid'
        new_service.service_name = 'Name'
        new_service.service_key = 'key'
        new_service.service_hostname = 'Hostname'
        new_service.service_port = 3
        new_service.service_endpoint = "Endpoint"
        new_service.service_clientendpoint = 'Clientendpoint'
        new_service.service_enabled = False
        new_service.service_system = 'not a bool'
        new_service.service_editable_config = True
        db.session.add(new_service)
        self.assertRaises(exc.StatementError, db.session.commit)

    def test_service_editable_config_integer(self):

3 Source : test_TeraService.py
with Apache License 2.0
from introlab

    def test_service_editable_config_integer(self):
        new_service = TeraService()
        new_service.service_uuid = 'uuid'
        new_service.service_name = 'Name'
        new_service.service_key = 'key'
        new_service.service_hostname = 'Hostname'
        new_service.service_port = 3
        new_service.service_endpoint = "Endpoint"
        new_service.service_clientendpoint = 'Clientendpoint'
        new_service.service_enabled = False
        new_service.service_system = False
        new_service.service_editable_config = 15
        db.session.add(new_service)
        self.assertRaises(exc.StatementError, db.session.commit)

    def test_service_to_json(self):

3 Source : test_sqlite.py
with MIT License
from sqlalchemy

    def test_string_dates_passed_raise(self, connection):
        assert_raises(
            exc.StatementError,
            connection.execute,
            select(1).where(bindparam("date", type_=Date)),
            dict(date=str(datetime.date(2007, 10, 30))),
        )

    def test_cant_parse_datetime_message(self, connection):

3 Source : test_execute.py
with MIT License
from sqlalchemy

    def test_stmt_exception_bytestring_raised(self):
        name = "méil"
        users = self.tables.users
        with testing.db.connect() as conn:
            assert_raises_message(
                tsa.exc.StatementError,
                "A value is required for bind parameter 'uname'\n"
                ".*SELECT users.user_name AS .méil.",
                conn.execute,
                select(users.c.user_name.label(name)).where(
                    users.c.user_name == bindparam("uname")
                ),
                {"uname_incorrect": "foo"},
            )

    def test_stmt_exception_bytestring_utf8(self):

3 Source : test_execute.py
with MIT License
from sqlalchemy

    def _test_alter_disconnect(self, orig_error, evt_value):
        engine = engines.testing_engine()

        @event.listens_for(engine, "handle_error")
        def evt(ctx):
            ctx.is_disconnect = evt_value

        with patch.object(
            engine.dialect, "is_disconnect", Mock(return_value=orig_error)
        ):

            with engine.connect() as c:
                try:
                    c.exec_driver_sql("SELECT x FROM nonexistent")
                    assert False
                except tsa.exc.StatementError as st:
                    eq_(st.connection_invalidated, evt_value)

    def test_alter_disconnect_to_true(self):

3 Source : test_defaults.py
with MIT License
from sqlalchemy

    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},
            ],
        )

    def test_insert_values(self, connection):

3 Source : test_query.py
with MIT License
from sqlalchemy

    def _assert_raises(self, stmt, params):
        with testing.db.connect() as conn:
            assert_raises_message(
                exc.StatementError,
                "A value is required for bind parameter 'x'",
                conn.execute,
                stmt,
                params,
            )

    def test_insert(self):

3 Source : test_types.py
with MIT License
from sqlalchemy

    def test_lookup_failure(self, connection):
        assert_raises(
            exc.StatementError,
            connection.execute,
            self.tables["non_native_enum_table"].insert(),
            {"id": 4, "someotherenum": "four"},
        )

    def test_mock_engine_no_prob(self):

3 Source : session.py
with MIT License
from stac-utils

    def context_session(self) -> Iterator[SqlSession]:
        """Override base method to include exception handling."""
        try:
            yield from self.get_db()
        except sa.exc.StatementError as e:
            if isinstance(e.orig, psycopg2.errors.UniqueViolation):
                raise errors.ConflictError("resource already exists") from e
            elif isinstance(e.orig, psycopg2.errors.ForeignKeyViolation):
                raise errors.ForeignKeyError("collection does not exist") from e
            logger.error(e, exc_info=True)
            raise errors.DatabaseError("unhandled database error")


@attr.s

0 Source : test_concurrency.py
with GNU Affero General Public License v3.0
from closeio

def test_no_logging_until_many_transient_error():
    transient = [
        socket.timeout,
        socket.error,
        _mysql_exceptions.OperationalError(
            "(_mysql_exceptions.OperationalError) (1213, 'Deadlock "
            "found when trying to get lock; try restarting transaction')"
        ),
        _mysql_exceptions.OperationalError(
            "(_mysql_exceptions.OperationalError) Lost connection to MySQL "
            "server during query"
        ),
        _mysql_exceptions.OperationalError(
            "(_mysql_exceptions.OperationalError) MySQL server has gone away."
        ),
        _mysql_exceptions.OperationalError(
            "(_mysql_exceptions.OperationalError) Can't connect to MySQL "
            "server on 127.0.0.1"
        ),
        _mysql_exceptions.OperationalError(
            "(_mysql_exceptions.OperationalError) Max connect timeout reached "
            "while reaching hostgroup 71"
        ),
        StatementError(
            message="?",
            statement="SELECT *",
            params={},
            orig=_mysql_exceptions.OperationalError(
                "(_mysql_exceptions.OperationalError) MySQL server has gone away."
            ),
        ),
    ]

    for transient_exc in transient:
        logger = MockLogger()
        failing_function = FailingFunction(transient_exc, max_executions=2)
        retry_with_logging(failing_function, logger=logger)

        assert logger.call_count == 0, f"{transient_exc} should not be logged"
        assert failing_function.call_count == 2

        failing_function = FailingFunction(socket.error, max_executions=21)
        retry_with_logging(failing_function, logger=logger)

        assert logger.call_count == 1
        assert failing_function.call_count == 21

        failing_function = FailingFunction(socket.error, max_executions=2)


@pytest.mark.usefixtures("mock_gevent_sleep")

0 Source : test_concurrency.py
with GNU Affero General Public License v3.0
from closeio

def test_logging_on_critical_error():
    critical = [
        TypeError("Example TypeError"),
        StatementError(message="?", statement="SELECT *", params={}, orig=None),
        StatementError(
            message="?",
            statement="SELECT *",
            params={},
            orig=_mysql_exceptions.OperationalError(
                "(_mysql_exceptions.OperationalError) Incorrect string value "
                "'\\xE7\\x(a\\x84\\xE5'"
            ),
        ),
        _mysql_exceptions.OperationalError(
            "(_mysql_exceptions.OperationalError) Incorrect string value "
            "'\\xE7\\x(a\\x84\\xE5'"
        ),
        _mysql_exceptions.IntegrityError(
            "(_mysql_exceptions.IntegrityError) Column not found"
        ),
    ]

    for critical_exc in critical:
        logger = MockLogger()
        failing_function = FailingFunction(critical_exc, max_executions=2)
        retry_with_logging(failing_function, logger=logger)

        assert logger.call_count == 1, f"{critical_exc} should be logged"
        assert failing_function.call_count == 2

0 Source : nmap.py
with MIT License
from epi052

    def parse_nmap_output(self):
        """ Read nmap .xml results and add entries into specified database """

        for entry in self.results_subfolder.glob("nmap*.xml"):
            # relying on python-libnmap here
            report = NmapParser.parse_fromfile(entry)

            for host in report.hosts:
                for service in host.services:
                    port = self.db_mgr.get_or_create(Port, protocol=service.protocol, port_number=service.port)

                    if is_ip_address(host.address) and get_ip_address_version(host.address) == "4":
                        ip_address = self.db_mgr.get_or_create(IPAddress, ipv4_address=host.address)
                    else:
                        ip_address = self.db_mgr.get_or_create(IPAddress, ipv6_address=host.address)

                    if ip_address.target is None:
                        # account for ip addresses identified that aren't already tied to a target
                        # almost certainly ipv6 addresses
                        tgt = self.db_mgr.get_or_create(Target)
                        tgt.ip_addresses.append(ip_address)
                    else:
                        tgt = ip_address.target

                    try:
                        nmap_result = self.db_mgr.get_or_create(
                            NmapResult, port=port, ip_address=ip_address, target=tgt
                        )
                    except sqlalchemy.exc.StatementError:
                        # one of the three (port/ip/tgt) didn't exist and we're querying on ids that the db doesn't know
                        self.db_mgr.add(port)
                        self.db_mgr.add(ip_address)
                        self.db_mgr.add(tgt)
                        nmap_result = self.db_mgr.get_or_create(
                            NmapResult, port=port, ip_address=ip_address, target=tgt
                        )

                    for nse_result in service.scripts_results:
                        script_id = nse_result.get("id")
                        script_output = nse_result.get("output")
                        nse_obj = self.db_mgr.get_or_create(NSEResult, script_id=script_id, script_output=script_output)
                        nmap_result.nse_results.append(nse_obj)

                    nmap_result.open = service.open()
                    nmap_result.reason = service.reason
                    nmap_result.service = service.service
                    nmap_result.commandline = report.commandline
                    nmap_result.product = service.service_dict.get("product")
                    nmap_result.product_version = service.service_dict.get("version")
                    nmap_result.target.nmap_results.append(nmap_result)

                    self.db_mgr.add(nmap_result)
                    self.output().get("sqltarget").touch()

        self.db_mgr.close()

    def run(self):

0 Source : test_deprecations.py
with Apache License 2.0
from gethue

    def test_legacy_dbapi_error_no_ad_hoc_context(self):
        engine = engines.testing_engine()

        listener = Mock(return_value=None)
        with testing.expect_deprecated(
            r"The ConnectionEvents.dbapi_error\(\) event is deprecated"
        ):
            event.listen(engine, "dbapi_error", listener)

        nope = SomeException("nope")

        class MyType(TypeDecorator):
            impl = Integer

            def process_bind_param(self, value, dialect):
                raise nope

        with engine.connect() as conn:
            assert_raises_message(
                tsa.exc.StatementError,
                r"\(.*SomeException\) " r"nope\n\[SQL\: u?SELECT 1 ",
                conn.execute,
                select([1]).where(column("foo") == literal("bar", MyType())),
            )
        # no legacy event
        eq_(listener.mock_calls, [])

    def test_legacy_dbapi_error_non_dbapi_error(self):

0 Source : test_execute.py
with Apache License 2.0
from gethue

    def test_exception_wrapping_non_dbapi_statement(self):
        class MyType(TypeDecorator):
            impl = Integer

            def process_bind_param(self, value, dialect):
                raise SomeException("nope")

        def _go(conn):
            assert_raises_message(
                tsa.exc.StatementError,
                r"\(.*.SomeException\) " r"nope\n\[SQL\: u?SELECT 1 ",
                conn.execute,
                select([1]).where(column("foo") == literal("bar", MyType())),
            )

        _go(testing.db)
        conn = testing.db.connect()
        try:
            _go(conn)
        finally:
            conn.close()

    def test_not_an_executable(self):

0 Source : test_execute.py
with Apache License 2.0
from gethue

    def test_stmt_exception_bytestring_raised(self):
        name = util.u("méil")
        with testing.db.connect() as conn:
            assert_raises_message(
                tsa.exc.StatementError,
                util.u(
                    "A value is required for bind parameter 'uname'\n"
                    r".*SELECT users.user_name AS .m\xe9il."
                )
                if util.py2k
                else util.u(
                    "A value is required for bind parameter 'uname'\n"
                    ".*SELECT users.user_name AS .méil."
                ),
                conn.execute,
                select([users.c.user_name.label(name)]).where(
                    users.c.user_name == bindparam("uname")
                ),
                {"uname_incorrect": "foo"},
            )

    def test_stmt_exception_bytestring_utf8(self):

0 Source : test_execute.py
with Apache License 2.0
from gethue

    def test_exception_event_ad_hoc_context(self):
        """test that handle_error is called with a context in
        cases where _handle_dbapi_error() is normally called without
        any context.

        """

        engine = engines.testing_engine()

        listener = Mock(return_value=None)
        event.listen(engine, "handle_error", listener)

        nope = SomeException("nope")

        class MyType(TypeDecorator):
            impl = Integer

            def process_bind_param(self, value, dialect):
                raise nope

        with engine.connect() as conn:
            assert_raises_message(
                tsa.exc.StatementError,
                r"\(.*.SomeException\) " r"nope\n\[SQL\: u?SELECT 1 ",
                conn.execute,
                select([1]).where(column("foo") == literal("bar", MyType())),
            )

        ctx = listener.mock_calls[0][1][0]
        assert ctx.statement.startswith("SELECT 1 ")
        is_(ctx.is_disconnect, False)
        is_(ctx.original_exception, nope)

    def test_exception_event_non_dbapi_error(self):

0 Source : test_execute.py
with Apache License 2.0
from gethue

    def _test_alter_invalidate_pool_to_false(self, set_to_false):
        orig_error = True

        engine = engines.testing_engine()

        @event.listens_for(engine, "handle_error")
        def evt(ctx):
            if set_to_false:
                ctx.invalidate_pool_on_disconnect = False

        c1, c2, c3 = (
            engine.pool.connect(),
            engine.pool.connect(),
            engine.pool.connect(),
        )
        crecs = [conn._connection_record for conn in (c1, c2, c3)]
        c1.close()
        c2.close()
        c3.close()

        with patch.object(
            engine.dialect, "is_disconnect", Mock(return_value=orig_error)
        ):

            with engine.connect() as c:
                target_crec = c.connection._connection_record
                try:
                    c.execute("SELECT x FROM nonexistent")
                    assert False
                except tsa.exc.StatementError as st:
                    eq_(st.connection_invalidated, True)

        for crec in crecs:
            if crec is target_crec or not set_to_false:
                is_not_(crec.connection, crec.get_connection())
            else:
                is_(crec.connection, crec.get_connection())

    def test_alter_invalidate_pool_to_false(self):

0 Source : test_logging.py
with Apache License 2.0
from gethue

    def test_exception_format_hide_parameters_nondbapi_round_trip(self):
        foo = Table("foo", MetaData(), Column("data", String))

        with self.no_param_engine.connect() as conn:
            assert_raises_message(
                tsa.exc.StatementError,
                r"\(sqlalchemy.exc.InvalidRequestError\) A value is required "
                r"for bind parameter 'the_data_2'\n"
                r"\[SQL: SELECT foo.data \nFROM foo \nWHERE "
                r"foo.data = \? OR foo.data = \?\]\n"
                r"\[SQL parameters hidden due to hide_parameters=True\]",
                conn.execute,
                select([foo]).where(
                    or_(
                        foo.c.data == bindparam("the_data_1"),
                        foo.c.data == bindparam("the_data_2"),
                    )
                ),
                {"the_data_1": "some data"},
            )

    def test_exception_format_unexpected_parameter(self):

0 Source : test_reconnect.py
with Apache License 2.0
from gethue

    def test_with_transaction(self):
        conn = self.engine.connect()
        trans = conn.begin()
        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.closed
        self.engine.test_shutdown()
        _assert_invalidated(conn.execute, select([1]))
        assert not conn.closed
        assert conn.invalidated
        assert trans.is_active
        assert_raises_message(
            tsa.exc.StatementError,
            "Can't reconnect until invalid transaction is rolled back",
            conn.execute,
            select([1]),
        )
        assert trans.is_active
        assert_raises_message(
            tsa.exc.InvalidRequestError,
            "Can't reconnect until invalid transaction is rolled back",
            trans.commit,
        )
        assert trans.is_active
        trans.rollback()
        assert not trans.is_active
        assert conn.invalidated
        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.invalidated


class RecycleTest(fixtures.TestBase):

0 Source : test_query.py
with Apache License 2.0
from gethue

    def test_filter_with_detached_non_pk_col_is_default_null(self):
        self._fixture1()
        Dingaling, HasDingaling = (
            self.classes.Dingaling,
            self.classes.HasDingaling,
        )
        s = Session()
        d = Dingaling()
        s.add(d)
        s.flush()
        s.commit()
        d.id
        s.expire(d, ["data"])
        s.expunge(d)
        assert "data" not in d.__dict__
        assert "id" in d.__dict__

        q = s.query(HasDingaling).filter_by(dingaling=d)

        # this case we still can't handle, object is detached so we assume
        # nothing

        assert_raises_message(
            sa_exc.StatementError,
            r"Can't resolve value for column dingalings.data on "
            r"object .*Dingaling.* the object is detached and "
            r"the value was expired",
            q.all,
        )

    def test_filter_with_detached_non_pk_col_has_value(self):

0 Source : test_session.py
with Apache License 2.0
from gethue

    def test_deferred_expression_expired_obj_became_detached_expired(self):
        User, Address = self.classes("User", "Address")

        sess = create_session(
            autoflush=True, autocommit=False, expire_on_commit=True
        )
        u = User(name="ed", addresses=[Address(email_address="foo")])

        sess.add(u)
        sess.commit()

        assert "id" not in u.__dict__  # it's expired

        # should not emit SQL
        def go():
            Address.user == u

        self.assert_sql_count(testing.db, go, 0)

        # create the expression here, but note we weren't tracking 'id'
        # yet so we don't have the old value
        q = sess.query(Address).filter(Address.user == u)

        sess.expunge(u)
        assert_raises_message(
            sa.exc.StatementError,
            "Can't resolve value for column users.id on object "
            ".User.*.; the object is detached and the value was expired",
            q.one,
        )


class SessionStateWFixtureTest(_fixtures.FixtureTest):

0 Source : test_insert_exec.py
with Apache License 2.0
from gethue

    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}
        )

    def _test_lastrow_accessor(self, table_, values, assertvalues):

0 Source : test_query.py
with Apache License 2.0
from gethue

    def test_expanding_in(self):
        testing.db.execute(
            users.insert(),
            [
                dict(user_id=7, user_name="jack"),
                dict(user_id=8, user_name="fred"),
                dict(user_id=9, user_name=None),
            ],
        )

        with testing.db.connect() as conn:
            stmt = (
                select([users])
                .where(
                    users.c.user_name.in_(bindparam("uname", expanding=True))
                )
                .order_by(users.c.user_id)
            )

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

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

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

            assert_raises_message(
                exc.StatementError,
                "'expanding' parameters can't be used with executemany()",
                conn.execute,
                users.update().where(
                    users.c.user_name.in_(bindparam("uname", expanding=True))
                ),
                [{"uname": ["fred"]}, {"uname": ["ed"]}],
            )

    @testing.requires.no_quoting_special_bind_names

0 Source : test_orm.py
with MIT License
from OneGov

def test_utc_datetime_naive(postgres_dsn):
    Base = declarative_base(cls=ModelBase)

    class Test(Base):
        __tablename__ = 'test'

        id = Column(Integer, primary_key=True)
        date = Column(UTCDateTime)

    mgr = SessionManager(postgres_dsn, Base)
    mgr.set_current_schema('testing')

    session = mgr.session()

    with pytest.raises(sqlalchemy.exc.StatementError):
        test = Test(date=datetime.now())
        session.add(test)
        session.flush()

    mgr.dispose()


def test_utc_datetime_aware(postgres_dsn):

0 Source : test_execute.py
with MIT License
from sqlalchemy

    def test_exception_wrapping_non_dbapi_statement(self):
        class MyType(TypeDecorator):
            impl = Integer
            cache_ok = True

            def process_bind_param(self, value, dialect):
                raise SomeException("nope")

        def _go(conn):
            assert_raises_message(
                tsa.exc.StatementError,
                r"\(.*.SomeException\) " r"nope\n\[SQL\: u?SELECT 1 ",
                conn.execute,
                select(1).where(column("foo") == literal("bar", MyType())),
            )

        with testing.db.connect() as conn:
            _go(conn)

    def test_not_an_executable(self):

0 Source : test_execute.py
with MIT License
from sqlalchemy

    def test_exception_event_ad_hoc_context(self):
        """test that handle_error is called with a context in
        cases where _handle_dbapi_error() is normally called without
        any context.

        """

        engine = engines.testing_engine()

        listener = Mock(return_value=None)
        event.listen(engine, "handle_error", listener)

        nope = SomeException("nope")

        class MyType(TypeDecorator):
            impl = Integer
            cache_ok = True

            def process_bind_param(self, value, dialect):
                raise nope

        with engine.connect() as conn:
            assert_raises_message(
                tsa.exc.StatementError,
                r"\(.*.SomeException\) " r"nope\n\[SQL\: u?SELECT 1 ",
                conn.execute,
                select(1).where(column("foo") == literal("bar", MyType())),
            )

        ctx = listener.mock_calls[0][1][0]
        assert ctx.statement.startswith("SELECT 1 ")
        is_(ctx.is_disconnect, False)
        is_(ctx.original_exception, nope)

    def test_exception_event_non_dbapi_error(self):

0 Source : test_execute.py
with MIT License
from sqlalchemy

    def _test_alter_invalidate_pool_to_false(self, set_to_false):
        orig_error = True

        engine = engines.testing_engine()

        @event.listens_for(engine, "handle_error")
        def evt(ctx):
            if set_to_false:
                ctx.invalidate_pool_on_disconnect = False

        c1, c2, c3 = (
            engine.pool.connect(),
            engine.pool.connect(),
            engine.pool.connect(),
        )
        crecs = [conn._connection_record for conn in (c1, c2, c3)]
        c1.close()
        c2.close()
        c3.close()

        with patch.object(
            engine.dialect, "is_disconnect", Mock(return_value=orig_error)
        ):

            with engine.connect() as c:
                target_crec = c.connection._connection_record
                try:
                    c.exec_driver_sql("SELECT x FROM nonexistent")
                    assert False
                except tsa.exc.StatementError as st:
                    eq_(st.connection_invalidated, True)

        for crec in crecs:
            if crec is target_crec or not set_to_false:
                is_not(crec.dbapi_connection, crec.get_connection())
            else:
                is_(crec.dbapi_connection, crec.get_connection())

    def test_alter_invalidate_pool_to_false(self):

0 Source : test_logging.py
with MIT License
from sqlalchemy

    def test_exception_format_hide_parameters_nondbapi_round_trip(self):
        foo = Table("foo", MetaData(), Column("data", String))

        with self.no_param_engine.connect() as conn:
            assert_raises_message(
                tsa.exc.StatementError,
                r"\(sqlalchemy.exc.InvalidRequestError\) A value is required "
                r"for bind parameter 'the_data_2'\n"
                r"\[SQL: SELECT foo.data \nFROM foo \nWHERE "
                r"foo.data = \? OR foo.data = \?\]\n"
                r"\[SQL parameters hidden due to hide_parameters=True\]",
                conn.execute,
                select(foo).where(
                    or_(
                        foo.c.data == bindparam("the_data_1"),
                        foo.c.data == bindparam("the_data_2"),
                    )
                ),
                {"the_data_1": "some data"},
            )

    def test_exception_format_unexpected_parameter(self):

0 Source : test_session_py3k.py
with MIT License
from sqlalchemy

    async def test_new_style_active_history(
        self, async_session, one_to_one_fixture, _legacy_inactive_history_style
    ):

        A, B = await one_to_one_fixture(_legacy_inactive_history_style)

        a1 = A()
        b1 = B()

        a1.b = b1
        async_session.add(a1)

        await async_session.commit()

        b2 = B()

        if _legacy_inactive_history_style:
            # aiomysql dialect having problems here, emitting weird
            # pytest warnings and we might need to just skip for aiomysql
            # here, which is also raising StatementError w/ MissingGreenlet
            # inside of it
            with testing.expect_raises(
                (exc.StatementError, exc.MissingGreenlet)
            ):
                a1.b = b2
        else:
            a1.b = b2

            await async_session.flush()

            await async_session.refresh(b1)

            eq_(
                (
                    await async_session.execute(
                        select(func.count())
                        .where(B.id == b1.id)
                        .where(B.a_id == None)
                    )
                ).scalar(),
                1,
            )


class AsyncEventTest(AsyncFixture):

0 Source : test_session.py
with MIT License
from sqlalchemy

    def test_deferred_expression_expired_obj_became_detached_expired(self):
        User, Address = self.classes("User", "Address")

        sess = fixture_session(autoflush=True, expire_on_commit=True)
        u = User(name="ed", addresses=[Address(email_address="foo")])

        sess.add(u)
        sess.commit()

        assert "id" not in u.__dict__  # it's expired

        # should not emit SQL
        def go():
            Address.user == u

        self.assert_sql_count(testing.db, go, 0)

        # create the expression here, but note we weren't tracking 'id'
        # yet so we don't have the old value
        q = sess.query(Address).filter(Address.user == u)

        sess.expunge(u)
        assert_raises_message(
            sa.exc.StatementError,
            "Can't resolve value for column users.id on object "
            ".User.*.; the object is detached and the value was expired",
            q.one,
        )


class SessionStateWFixtureTest(_fixtures.FixtureTest):

0 Source : test_insert_exec.py
with MIT License
from sqlalchemy

    def test_insert_heterogeneous_params(self, connection):
        """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",
            connection.execute,
            users.insert(),
            [
                {"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.
        connection.execute(
            users.insert(),
            [
                {"user_id": 7},
                {"user_id": 8, "user_name": "ed"},
                {"user_id": 9},
            ],
        )

    def _test_lastrow_accessor(self, connection, table_, values, assertvalues):

0 Source : test_query.py
with MIT License
from sqlalchemy

    def test_expanding_in(self, connection):
        users = self.tables.users
        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"]}],
        )

    @testing.requires.no_quoting_special_bind_names