How to use the asyncpg.exceptions.UniqueViolationError 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 python-gino / gino / tests / test_declarative.py View on Github external
async def test_inline_constraints_and_indexes(bind, engine):
    u = await User.create(nickname="test")
    us1 = await UserSetting.create(user_id=u.id, setting="skin", value="blue")

    # PrimaryKeyConstraint
    with pytest.raises(UniqueViolationError):
        await UserSetting.create(id=us1.id, user_id=u.id, setting="key1", value="val1")

    # ForeignKeyConstraint
    with pytest.raises(ForeignKeyViolationError):
        await UserSetting.create(user_id=42, setting="key2", value="val2")

    # UniqueConstraint
    with pytest.raises(UniqueViolationError):
        await UserSetting.create(
            user_id=u.id, setting="skin", value="duplicate-setting"
        )

    # CheckConstraint
    with pytest.raises(CheckViolationError):
        await UserSetting.create(user_id=u.id, setting="key3", value="val3", col1=42)

    # Index
    status, result = await engine.status(
        "SELECT * FROM pg_indexes WHERE indexname = 'col2_idx'"
    )
    assert status == "SELECT 1"
github pyslackers / sirbot-pyslackers / sirbot_pyslackers / endpoints / slack / messages.py View on Github external
if message["ts"]:  # We sometimes receive message without a timestamp. See #45
            try:
                async with app["plugins"]["pg"].connection() as pg_con:
                    await pg_con.execute(
                        """INSERT INTO slack.messages (id, text, "user", channel, raw, time)
                        VALUES ($1, $2, $3, $4, $5, $6)""",
                        message["ts"],
                        message.get("text"),
                        message.get("user"),
                        message.get("channel"),
                        dict(message),
                        datetime.datetime.fromtimestamp(
                            int(message["ts"].split(".")[0])
                        ),
                    )
            except UniqueViolationError:
                LOG.debug('Message "%s" already in database.', message["ts"])
github dashwav / nano-chan / cogs / channels.py View on Github external
Creates a channel_message message in the current channel with the target of the designated channel.
        """
        if not isinstance(target_channel, discord.TextChannel):
            await ctx.send("that is not a valid channel fam", delete_after=4)
            return
        local_embed = discord.Embed(
            title=f'#{target_channel.name}',
            description=f'{description[:2046]}',
            type="rich"
        )
        message = await ctx.send(embed=local_embed)
        await message.add_reaction(self.reaction_emojis[0])
        try:
            await self.bot.pg_controller.add_channel_message(message.id, target_channel.id, ctx.channel.id)
            self.bot.chanreact.append({'target_channel': target_channel.id, 'message_id': message.id, 'host_channel': ctx.channel.id})
        except UniqueViolationError:
            await message.delete()
            await ctx.send(
                f"There already exists a link to {target_channel.name} here.")
        await ctx.message.delete()
github plone / guillotina / guillotina / db / storages / cockroach.py View on Github external
try:
                result = await conn.fetch(
                    statement_sql,
                    oid,  # The OID of the object
                    txn._tid,  # Our TID
                    len(pickled),  # Len of the object
                    part,  # Partition indicator
                    writer.resource,  # Is a resource ?
                    writer.of,  # It belogs to a main
                    old_serial,  # Old serial
                    writer.parent_id,  # Parent OID
                    writer.id,  # Traversal ID
                    writer.type,  # Guillotina type
                    pickled,  # Pickle state)
                )
            except asyncpg.exceptions.UniqueViolationError as ex:
                if "duplicate key value (parent_id,id)" in ex.detail:
                    raise ConflictIdOnContainer(ex)
                raise
            except asyncpg.exceptions._base.InterfaceError as ex:
                if "another operation is in progress" in ex.args[0]:
                    raise ConflictError(
                        f"asyncpg error, another operation in progress.", oid, txn, old_serial, writer
                    )
                raise
            if update and len(result) != 1:
                # raise tid conflict error
                raise TIDConflictError(
                    f"Mismatch of tid of object being updated. This is likely "
                    f"caused by a cache invalidation race condition and should "
                    f"be an edge case. This should resolve on request retry.",
                    oid,
github Run1e / AceBot / migrate_data.py View on Github external
row.get('guild_id'), row.get('channel_id'), row.get('content')
			)
			print('welcome: guild {} channel {}'.format(row.get('guild_id'), row.get('channel_id')))
		except UniqueViolationError:
			pass

	print('seen...')

	# seen
	for row in await origin.fetch('SELECT * FROM seen'):
		try:
			await target.execute(
				'INSERT INTO seen (guild_id, user_id, seen) VALUES ($1, $2, $3)',
				row.get('guild_id'), row.get('user_id'), row.get('seen')
			)
		except UniqueViolationError:
			pass

	print('logs...')

	# logs
	for row in await origin.fetch('SELECT * FROM log'):
		try:
			await target.execute(
				'INSERT INTO log (guild_id, channel_id, user_id, timestamp, command) VALUES ($1, $2, $3, $4, $5)',
				row.get('guild_id'), row.get('channel_id'), row.get('author_id'), row.get('date'), row.get('command')
			)
		except UniqueViolationError:
			pass

	print('finished!')
github quantmind / aio-openapi / openapi / db / path.py View on Github external
) -> StrDict:
        """Create a new database model

        :param data: input data, if not given it loads it via :meth:`.json_data`
        :param table: sqlalchemy table, if not given it uses the
            default :attr:`db_table`
        """
        if data is None:
            data = self.insert_data(await self.json_data(), body_schema=body_schema)
        table = table if table is not None else self.db_table
        statement, args = self.db.get_insert(table, data)

        async with self.db.ensure_connection(conn) as conn:
            try:
                values = await conn.fetch(statement, *args)
            except UniqueViolationError as exc:
                self.handle_unique_violation(exc)

        return cast(StrDict, self.dump(dump_schema, values[0]))
github MrNaif2018 / bitcart / api / views.py View on Github external
raise HTTPException(422, e.errors())
    item = await get_product_noauth(model_id)
    if image:
        filename = utils.get_image_filename(image, False, item)
        model.image = filename
        await utils.save_image(filename, image)
    else:
        utils.safe_remove(item.image)
        model.image = None
    try:
        if patch:
            await item.update(**model.dict(exclude_unset=True)).apply()  # type: ignore
        else:
            await item.update(**model.dict()).apply()
    except (  # pragma: no cover
        asyncpg.exceptions.UniqueViolationError,
        asyncpg.exceptions.NotNullViolationError,
        asyncpg.exceptions.ForeignKeyViolationError,
    ) as e:
        raise HTTPException(422, e.message)  # pragma: no cover
    return item
github MrNaif2018 / bitcart / api / utils.py View on Github external
async def put(
        model_id: int,
        model: pydantic_model,
        user: Union[None, schemes.User] = Security(
            auth_dependency, scopes=scopes["put"]
        ),
    ):  # type: ignore
        item = await _get_one(model_id, user, True)
        try:
            if custom_methods.get("put"):
                await custom_methods["put"](item, model, user)  # pragma: no cover
            else:
                await item.update(**model.dict()).apply()  # type: ignore
        except (
            asyncpg.exceptions.UniqueViolationError,
            asyncpg.exceptions.NotNullViolationError,
            asyncpg.exceptions.ForeignKeyViolationError,
        ) as e:
            raise HTTPException(422, e.message)
        return item
github monobot / asyncorm / asyncorm / manager / model_manager.py View on Github external
fields.append(field_name)
                    field_data.append(data)

        db_request = [
            {
                "action": getattr(instanced_model, instanced_model.orm_pk) and "_db__update" or "_db__insert",
                "id_data": "{}={}".format(instanced_model.db_pk, getattr(instanced_model, instanced_model.orm_pk)),
                "field_names": ", ".join(fields),
                "field_values": field_data,
                "field_schema": ", ".join(["${}".format(value + 1) for value in range(len(field_data))]),
                "condition": "{}={}".format(instanced_model.db_pk, getattr(instanced_model, instanced_model.orm_pk)),
            }
        ]
        try:
            response = await self.db_request(db_request)
        except UniqueViolationError:
            raise AsyncOrmModelError("The model violates a unique constraint")

        self.modelconstructor(response, instanced_model)

        # now we have to save the m2m relations: m2m_data
        fields, field_data = [], []
        for k, data in instanced_model.m2m_data.items():
            # for each of the m2m fields in the model, we have to check
            # if the table register already exists in the table otherwise
            # and delete the ones that are not in the list
            # first get the table_name
            cls_field = getattr(instanced_model.__class__, k)
            table_name = cls_field.table_name
            foreign_column = cls_field.foreign_key

            model_column = instanced_model.cls_tablename()