Feature request: method to persist object and get identifier immediately

Issue #3734 wontfix
Yegor Roganov created an issue

Java's Hibernate has two methods to persist objects:

  • persist() which makes objects pending (in SA terms) and does not guarantee that the identifier value will be assigned to the instance immediately. It corresponds to sqlalchemy's add()

  • save() which does guarantee to assign an identifier. Such a method AFAIK does not exist in sqlalchemy.

The rationale behind this is that even with autoflush=True primary key of pending instances is None before flush(), which can lead to bugs.

I know that the behavior can be emulated with a couple of lines, but it seems that it's generally useful.

def save(obj):
    sess.add(obj)
    if inspect(obj).pending:
        sess.flush()

Comments (3)

  1. Mike Bayer repo owner

    the problem with the above is that it flushes everything in the session, not just this one object. There is a feature where flush() can accept a list of objects to limit the flush towards, however its use is discouraged; this is because it can't guarantee the state of the object graph afterwards. I'm not sure the pattern you suggest is really feasible as something that users wouldn't be surprised by. Meaning, it will lead to many more bug reports - "I did save() and my collections weren't saved, or were saved, etc. Does save() save collections or not ? does it save() all the objects in the collection ? does it cascade? etc. etc. It's very simple to do this on your end, but one it's a SQLA feature it now has a much more formal contract to fill (and what that contract is, can be many things to different people).

  2. Mike Bayer repo owner

    opting not to do this enhancement as it's an easy add-on for someone who needs it locally, not so easy to support a formal usage contract.

  3. Log in to comment