Answer the question
In order to leave comments, you need to log in
How to do an upsert in SQLAlchemy?
It seems to be a common task, but I can’t find a normal solution in the English-speaking Internet.
Suppose we have a standard ETL task run through Apache Airflow.
She writes to the "Statistic" table. The table has uniqueness by (user, date), but we do not want data duplication, why do we need this?
The process is simple:
1) create an orm object
Statistic(user='Олег', date='2022-03-31', value='145')
session.add()
session.commit()
insert into...on conflict do update set value = EXTENDED.value
from sqlalchemy.dialects.postgresql import insert
Answer the question
In order to leave comments, you need to log in
disappears immediately plus alchemy in easy code migration to other databasesWell, here's an easy ORM migration from different DBMS, it's kind of a myth. Each base has its own characteristics that help a lot, as a result they become attached to one. And the bases are not changed so often, and rather this is a more global process than just switching. All the same, ORM is more about working with data at the application code level, and not at the lower level, SQL. And the tests are also better on the base used, otherwise you can get different results. Point 2 is hard to say.
memory sqlite? there these constructions I suppose will not work?the construct itself is available in SQLite , and sqlalchemy.dialects.sqlite is supported . To what extent its behavior is identical to postgresql, I can’t tell you, but for simple cases, most likely, yes.
3) disappears immediately plus alchemy in easy code migration to other databases, say mysql (the problem is similar to point 1)
In general, please explain what I'm doing wrong?You want to use both non-standard SQL syntax at the same time and maintain compatibility between different implementations.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question