SQLAlchemy - INSERT OR REPLACE equivalent

前端 未结 4 536
再見小時候
再見小時候 2021-01-04 09:37

does anybody know what is the equivalent to SQL \"INSERT OR REPLACE\" clause in SQLAlchemy and its SQL expression language?

Many thanks -- honzas

相关标签:
4条回答
  • 2021-01-04 09:53

    You can use OR REPLACE as a so-called prefix in your SQLAlchemy Insert -- the documentation for how to place OR REPLACE between INSERT and INTO in your SQL statement is here

    0 讨论(0)
  • 2021-01-04 09:54

    I don't think (correct me if I'm wrong) INSERT OR REPLACE is in any of the SQL standards; it's an SQLite-specific thing. There is MERGE, but that isn't supported by all dialects either. So it's not available in SQLAlchemy's general dialect.

    The cleanest solution is to use Session, as suggested by M. Utku. You could also use SAVEPOINTs to save, try: an insert, except IntegrityError: then rollback and do an update instead. A third solution is to write your INSERT with an OUTER JOIN and a WHERE clause that filters on the rows with nulls.

    0 讨论(0)
  • 2021-01-04 10:06
    Session.save_or_update(model)
    
    0 讨论(0)
  • 2021-01-04 10:14

    What about Session.merge?

    Session.merge(instance, load=True, **kw)
    

    Copy the state an instance onto the persistent instance with the same identifier.

    If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade="merge".

    from http://www.sqlalchemy.org/docs/reference/orm/sessions.html

    0 讨论(0)
提交回复
热议问题