I'm trying to upsert using SQLAlchemy. There's no upsert in SQL but SQLAlchemy provides this. The same thing I'm trying to perform with SQLAlchemy ORM session. My code:
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(engine)
with Session() as session:
"""Here upsert functionality"""
session.insert_or_update(company)
session.commit()
session.merge(company) works as I only need to check for primary key and not other unique values. The documentation says:
Session.merge() examines the primary key attributes of the source instance, and attempts to reconcile it with an instance of the same primary key in the session. If not found locally, it attempts to load the object from the database based on primary key, and if none can be located, creates a new instance. The state of each attribute on the source instance is then copied to the target instance. The resulting target instance is then returned by the method; the original source instance is left unmodified, and un-associated with the Session if not already.
How do I perform this for multiple objects?