Created
August 16, 2019 11:56
-
-
Save afonasev/eebf251aebeed6de67e74dc647d23562 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.dialects import postgresql | |
def upsert(session, model, fields, returning=False, return_columns=None): | |
table = model.__table__ | |
stmt = postgresql.insert(table).values(**fields) | |
pk_columns = table.primary_key.columns.keys() | |
update_cols = {col: val for col, val in fields.items() if col not in pk_columns} | |
if update_cols: | |
stmt = stmt.on_conflict_do_update( | |
constraint=table.primary_key, | |
set_=update_cols, | |
) | |
else: | |
stmt = stmt.on_conflict_do_nothing() | |
if returning: | |
if not return_columns: | |
return_columns = table.columns | |
stmt = stmt.returning(*return_columns) | |
result = session.execute(stmt) | |
if returning: | |
return model(**result.fetchone()) | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment