Похожие чаты

How to properly use UUID for making quries with SQLAlchemy

to not get error from postgres like "cannot cast type record to uuid"

I have Cards Repository, that has delete method, which uses squence of uuid, if uuid in that sequnce they must be deleted from db.

method:
`def delete(self, cardsids: Sequence[UUID5]) -> Sequence[UUID5]:
stmt = (
delete(Card)
.where(Card.id.in_([cardsids]))
.returning(Card.id)
)

with self.ss.begin():
return self.ss.execute(stmt) # type:ignore`

Then I am trying to delete values:
`Cards.delete(
cardsids=(
UUID("ffbbd142-c9bf-4c66-8b9d-6ebc4806a8cc"),
UUID("5cce0583-f506-4d0b-8fa9-f5604dfddde6"),
)
)`

but unfortunately get error from postgres:
`sqlalchemy.exc.ProgrammingError: (psycopg2.errors.CannotCoerce) cannot cast type record to uuid
LINE 1: ...6ebc4806a8cc', '5cce0583f5064d0b8fa9f5604dfddde6')::UUID) RE...
^

[SQL: DELETE FROM cards WHERE cards.id IN (%(id_1_1)s::UUID) RETURNING cards.id]
[parameters: {'id_1_1': ('ffbbd142c9bf4c668b9d6ebc4806a8cc', '5cce0583f5064d0b8fa9f5604dfddde6')}]`


As you can see SQLAlchemy have made syntax erros for casting simlpe string to uuid.
So instead of:
LINE 1: ...6ebc4806a8cc', '5cce0583f5064d0b8fa9f5604dfddde6')::UUID) RE...
As I think must be::
`LINE 1: ...6ebc4806a8cc':UUID, '5cce0583f5064d0b8fa9f5604dfddde6':UUID)) RE...

Model and his types:
`class Card(BaseModel):
tablename = "cards"

id: Mapped[pkuuid4]
user_id: Mapped[pkuuid4]
origin: Mapped[str64]
interpretation: Mapped[str512]
example: Mapped[str512]
curtt: Mapped[timestamp]
nextt: Mapped[timestamp]
last_rotate: Mapped[numeric]

str64 = Annotated[str, mapped_column(String(64))]
str512 = Annotated[str, mapped_column(String(512))]

pkuuid4 = Annotated[UUID, mapped_column(Uuid(as_uuid=True), primary_key=True)]

numeric = Annotated[
float, mapped_column(Numeric(precision=4, scale=2, asdecimal=False))
]

timestamp = Annotated[datetime, mapped_column(DateTime(timezone=True))]`


**So I assume that i'm passing incorrectly UUID to SQlAlchemy statment in body part of delete method in Cards repository. Perhaps somone knows how correctky use python UUID to make queries?

P.S. I tried to pass uuids as string as it was, instead of pasing them to uuid.UUID() but with just strings i have the same error**

5 ответов

95 просмотров

https://github.com/sqlalchemy/sqlalchemy/discussions/10666

⛧🇮🇱 Shennaz Martinez 🇺🇸🗽
Какой я нахуй слепой даун

Ох, такая мелочь, а сколько часов дебага стоила? Кстати, а почему mypy не ругнулся? Хотя формально он получил Sequence[Any] и на том его полномочия по идее всё

⛧🇮🇱 Shennaz Martinez 🇺🇸🗽
2 часа.

Просто оставил зайвые [], и сижу с мудрым лицом, думаю как же решить эту проблему, "это же не моя, это же проблема в сукулеалхимии, я же не могу быть слепым"

Похожие вопросы

Обсуждают сегодня

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?
Rꙮman Yankꙮvsky
29
А вообще, что может смущать в самой Julia - бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как "хаки" и произвол. Короче говоря, с...
Viktor G.
2
@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Гайс, вопрос для разносторонее развитых: читаю стрим с юарта, нада выделять с него фреймы с определенной структурой, если ли чо готовое, или долбаться с ринг буффером? нада у...
Vitaly
9
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Карта сайта