gpt4 book ai didi

python - 找出要删除的内容

转载 作者:太空狗 更新时间:2023-10-30 00:19:43 25 4
gpt4 key购买 nike

当使用具有不同设置的级联删除处理方式的更复杂的分层模型时,很难事先弄清楚 delete() 将对数据库执行什么操作。

我找不到任何方法从 SQLAlchemy 获取这条信息(“嘿,SQLAlchemy,如果我删除那里的那个对象,将会删除什么?”)。自己实现这个似乎不是一个选择,因为在我的预测和 delete() 的实际结果不同的情况下,这迟早会导致,这对用户。

最佳答案

我在 SQLAlchemy 邮件列表上问了这个问题
Michael Bayer explained the possible options (再次非常感谢!:-):

The only deletes that aren't present in session.deleted before the flush are those that will occur because a particular object is an "orphan", and the objects which would be deleted as a result of a cascade on that orphan.

So without orphans taken into account, session.deleted tells you everything that is to be deleted.

To take orphans into account requires traversing through all the relationships as the unit of work does, looking for objects that are currently orphans (there's an API function that will tell you this - if the object is considered an "orphan" by any attribute that refers to it with delete-orphan cascade, it's considered an "orphan"), and then traversing through the relationships of those orphans, considering them to be marked as "deleted", and then doing all the rules again for those newly-deleted objects.

The system right now is implemented by orm/dependency.py. It is probably not hard to literally run a unit of work process across the session normally, but just not emit the SQL, this would give you the final flush plan. But this is an expensive process that I wouldn't want to be calling all the time.

A feature add is difficult here because the use case is not clear. Knowing what will be deleted basically requires half the flush process actually proceed. But you can already implement events inside the flush process itself, most directly the before_delete() and after_delete() events that will guaranteed catch everything. So the rationale for a new feature that basically runs half the flush, before you just do the flush anyway and could just put events inside of it, isn't clear.

I guess the big question is, "when are you calling this".

An easy system would be to add a new event "flush_plan_complete" which will put you into a flush() right as the full plan has been assembled, but before any SQL occurs. It could allow you to register more objects for activity, and it would then rerun the flush plan to consider any new changes (since that's how it works right now anyway). How this registration would proceed is tricky, since it would be nice to use the Session normally there, but that makes this more complicated to implement. But then it could iterate again through the new changes and find any remaining steps to take before proceeding normally.

关于python - 找出要删除的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16875605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com