Question: Im writing an sqlalchemy upsert statement and I wondered if theres a way I could get the Id's back from the db?
Heres my code so far:

```
def handle_events(self, events):
    agg = []
    agg.extend(self._get_dicts(events))
    if not agg:
        return
    with DB.session(writable=True) as session:
        response = session.execute(self._generate_upsert_stmnt(agg))

def _generate_upsert_stmnt(self, items):
    model_class = models.MyModel
    table = model_class.__table__
    insert_statement = sa.dialects.postgresql.insert(table, items)
    upsert_statement = insert_statement.on_conflict_do_update(
        index_elements=[table.c['id']],
        set_={c.name: c for c in insert_statement.excluded if c.name != ["id", "my_model", "my_model_id"]}
    )
    return upsert_statement

```

Session in this code snippet is the returned object from the sessionmaker call from the sqlalchemy's api(wrapped in a context manager). is there a way to make this upsert statment return all the id's back(both inserted and updated)? if so how would that code look like?
Thanks in advance. p.s. if it matters the DB is postgres.

Answer: 
Eventually Ive used the `.returning(<column>)` inside my upsert statement like the following:

```
def _generate_upsert_stmnt(self, items):
    model_class = models.MyModel
    table = model_class.__table__
    insert_statement = sa.dialects.postgresql.insert(table, items)
    upsert_statement = insert_statement.on_conflict_do_update(
        index_elements=[table.c['id']],
        set_={c.name: c for c in insert_statement.excluded if c.name != 
        ["id", "my_model", "my_model_id"]}).returning(table.c['id'])
    return upsert_statement

```

and extraced the data like so:

```
    def _extract_ids_from_resultproxy(self, result):
        table = models.MyModel.__table__
        return [row[table.c.id] for row in result]

```
You can use `RETURNING` statement to see which id's where affected

Reference: <https://kite.com/python/docs/sqlalchemy.sql.Delete.returning>