我有两个实体,一对多关系。有些实体中有一个实体拥有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 (?,?...
我发现sqlite中的maxium sql变量是999,这就是我的问题所在。我在另一个问题中读到了答案,这是一个建模问题(https://stackoverflow.com/a/8433514/931325),但我不知道如何以不同的方式建模数据。
我有什么方法可以解决这个问题?
答案 0 :(得分:4)
尝试删除不同块中的行。您可以使用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()))