SQLAlchemy ON DUPLICATE KEY UPDATE

前端 未结 9 1549
死守一世寂寞
死守一世寂寞 2020-11-27 15:53

Is there an elegant way to do an INSERT ... ON DUPLICATE KEY UPDATE in SQLAlchemy? I mean something with a syntax similar to inserter.insert().execute(lis

9条回答
  •  無奈伤痛
    2020-11-27 16:34

    Based on phsource's answer, and for the specific use-case of using MySQL and completely overriding the data for the same key without performing a DELETE statement, one can use the following @compiles decorated insert expression:

    from sqlalchemy.ext.compiler import compiles
    from sqlalchemy.sql.expression import Insert
    
    @compiles(Insert)
    def append_string(insert, compiler, **kw):
        s = compiler.visit_insert(insert, **kw)
        if insert.kwargs.get('on_duplicate_key_update'):
            fields = s[s.find("(") + 1:s.find(")")].replace(" ", "").split(",")
            generated_directive = ["{0}=VALUES({0})".format(field) for field in fields]
            return s + " ON DUPLICATE KEY UPDATE " + ",".join(generated_directive)
        return s
    

提交回复
热议问题