我有一对多关系中的两个实体。在某些情况下,其中一个实体拥有999个以上的子实体。我想删除实体及其子实体,但遇到sqlite最大sql变量问题:
connection.execute(child.delete().where(child.c.parent_id == parent_id))
connection.execute(parent.delete().where(parent.c.id == parent_id))
sqlalchemy.exc.OperationalError:
OperationalError: (OperationalError) too many SQL variables u'DELETE FROM child WHERE child.parent_id IN (?,?...
Run Code Online (Sandbox Code Playgroud)
我发现sqlite中的maxium sql变量是999,这就是我的问题所在。我读了另一个问题的答案,即这是一个建模问题(/sf/answers/590346011/),但我看不到如何以其他方式对数据建模。
我有什么解决这个问题的选择?
尝试删除不同块中的行。您可以使用limit(999)最大值SQLITE_LIMIT_VARIABLE_NUMBER等于 999。这是您需要做的事情
from sqlalchemy import func, in_
# getting the amount of total rows
stmt = select([func.count(child.c.parent_id).label('num_rows_childs')]).where(child.c.parent_id == parent_id)
number_of_rows = conn.execute(stmt).fetchall()
# Getting quotient and reminder of all rows on 999
# This gives you the number of times that delete() should run
# div_mod[0] is the quotient
# div_mod[1] is the reminder
div_mod = divmod(number_of_rows[0], 999)
for x in xrange(div_mod[0]):
child.delete().where(child.c.parent_id.in_(select([child.c.parent_id]).where(child.c.parent_id == parent_id).limit(999).all()))
else:
child.delete().where(child.c.parent_id.in_(select([child.c.parent_id]).where(child.c.parent_id == parent_id).limit(div_mod[1]).all()))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4305 次 |
| 最近记录: |