How to use the asyncpg.PostgresError function in asyncpg

To help you get started, weā€™ve selected a few asyncpg examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MagicStack / asyncpg / tests / test_transaction.py View on Github external
# We don't return the transaction object from __aenter__,
                # to make it harder for people to use '.rollback()' and
                # '.commit()' from within an 'async with' block.
                self.assertIsNone(with_tr)

                await self.con.execute('''
                    CREATE TABLE mytab (a int);
                ''')

                1 / 0

        self.assertIsNone(self.con._top_xact)
        self.assertFalse(self.con.is_in_transaction())

        with self.assertRaisesRegex(asyncpg.PostgresError,
                                    '"mytab" does not exist'):
            await self.con.prepare('''
                SELECT * FROM mytab
github MagicStack / asyncpg / tests / test_transaction.py View on Github external
async for rec in st.cursor():
                    recs.append(rec)

                self.assertEqual(len(recs), 2)
                self.assertEqual(recs[0][0], 1)
                self.assertEqual(recs[1][0], 2)

                self.assertIs(self.con._top_xact, tr)
                self.assertTrue(self.con.is_in_transaction())

                1 / 0

        self.assertIs(self.con._top_xact, None)
        self.assertFalse(self.con.is_in_transaction())

        with self.assertRaisesRegex(asyncpg.PostgresError,
                                    '"mytab" does not exist'):
            await self.con.prepare('''
                SELECT * FROM mytab
github MagicStack / asyncpg / tests / test_execute.py View on Github external
async def test_execute_script_check_transactionality(self):
        with self.assertRaises(asyncpg.PostgresError):
            await self.con.execute('''
                CREATE TABLE mytab (a int);
                SELECT * FROM mytab WHERE 1 / 0 = 1;
            ''')

        with self.assertRaisesRegex(asyncpg.PostgresError,
                                    '"mytab" does not exist'):

            await self.con.prepare('''
                SELECT * FROM mytab
github MagicStack / asyncpg / tests / test_execute.py View on Github external
async def test_execute_script_check_transactionality(self):
        with self.assertRaises(asyncpg.PostgresError):
            await self.con.execute('''
                CREATE TABLE mytab (a int);
                SELECT * FROM mytab WHERE 1 / 0 = 1;
            ''')

        with self.assertRaisesRegex(asyncpg.PostgresError,
                                    '"mytab" does not exist'):

            await self.con.prepare('''
                SELECT * FROM mytab
github FoglyOgly / Meowth / meowth / core / logger.py View on Github external
async def on_raw_message_delete(self, payload):
        try:
            table = self.bot.dbi.table('discord_messages')
            table.update(deleted=True)
            table.update.where(message_id=payload.message_id)
            await table.update.commit()
        except asyncpg.PostgresError as e:
            self.logger.exception(type(e).__name__, exc_info=e)
github suned / pfun / pfun / sql.py View on Github external
async def _fetch(connection: asyncpg.Connection
                         ) -> Try[asyncpg.PostgresError, Results]:
            try:
                result = await connection.fetch(query, *args, timeout=timeout)
                result = List(Dict(record) for record in result)
                return success(result)
            except asyncpg.PostgresError as e:
                return error(e)
github python-gino / gino / src / gino / dialects / asyncpg.py View on Github external
PGExecutionContext,
)
from sqlalchemy.sql import sqltypes

from . import base

try:
    import click
except ImportError:
    click = None
JSON_COLTYPE = 114
JSONB_COLTYPE = 3802


class AsyncpgDBAPI(base.BaseDBAPI):
    Error = asyncpg.PostgresError, asyncpg.InterfaceError


class AsyncpgCompiler(PGCompiler):
    @property
    def bindtemplate(self):
        return self._bindtemplate

    @bindtemplate.setter
    def bindtemplate(self, val):
        # noinspection PyAttributeOutsideInit
        self._bindtemplate = val.replace(":", "$")

    def _apply_numbered_params(self):
        if hasattr(self, "string"):
            return super()._apply_numbered_params()
github python-gino / gino / src / gino / dialects / asyncpg.py View on Github external
def __init__(self):
        import asyncpg

        self.connect = asyncpg.connect
        self.Error = asyncpg.PostgresError, asyncpg.InterfaceError
        self.connection_error_cls = asyncpg.PostgresConnectionError
github samuelcolvin / nosht / py / web / middleware.py View on Github external
text=lenient_json(request_text),
        ),
        response=dict(
            status=getattr(response, 'status', None),
            headers=dict(getattr(response, 'headers', {})),
            text=response_text,
        ),
        **more,
    )

    tags = dict()
    user = dict(ip_address=get_ip(request))
    session = await get_session(request)
    user_id = session.get('user_id')
    if user_id:
        with contextlib.suppress(PostgresError):  # eg. InFailedSQLTransactionError
            async with request.app['main_app']['pg'].acquire() as conn:
                user_info = await conn.fetchrow(
                    """
                    SELECT u.email, c.name AS company_name, c.id AS company_id, role, status,
                    full_name(u.first_name, u.last_name) as username
                    FROM users AS u
                    JOIN companies AS c ON u.company = c.id
                    WHERE u.id=$1
                    """,
                    user_id,
                )
                if user_info:
                    tags.update(
                        user_status=user_info['status'], user_role=user_info['role'], company=user_info['company_id'],
                    )
                    user.update(user_info)
github edgedb / edgedb / edb / server / executor.py View on Github external
'unexpected transaction statement: {!r}'.format(plan))

        elif isinstance(plan, edgedb_query.Query):
            ps = await backend.connection.prepare(plan.text)
            return [r[0] for r in await ps.fetch()]

        elif isinstance(plan, irast.SessionStateCmd):
            # SET command

            await backend.exec_session_state_cmd(plan)

        else:
            raise errors.InternalServerError(
                'unexpected plan: {!r}'.format(plan))

    except asyncpg.PostgresError as e:
        _error = await backend.translate_pg_error(plan, e)
        if _error is not None:
            raise _error from e
        else:
            raise