How to do an upsert with SqlAlchemy?

前端 未结 7 1524
别跟我提以往
别跟我提以往 2020-12-08 01:37

I have a record that I want to exist in the database if it is not there, and if it is there already (primary key exists) I want the fields to be updated to the current state

7条回答
  •  一生所求
    2020-12-08 02:10

    This works for me with sqlite3 and postgres. Albeit it might fail with combined primary key constraints and will most likely fail with additional unique constraints.

        try:
            t = self._meta.tables[data['table']]
        except KeyError:
            self._log.error('table "%s" unknown', data['table'])
            return
    
        try:
            q = insert(t, values=data['values'])
            self._log.debug(q)
            self._db.execute(q)
        except IntegrityError:
            self._log.warning('integrity error')
            where_clause = [c.__eq__(data['values'][c.name]) for c in t.c if c.primary_key]
            update_dict = {c.name: data['values'][c.name] for c in t.c if not c.primary_key}
            q = update(t, values=update_dict).where(*where_clause)
            self._log.debug(q)
            self._db.execute(q)
        except Exception as e:
            self._log.error('%s: %s', t.name, e)
    

提交回复
热议问题