peewee.OperationalError:只有150行*8列的upsert上有太多的SQL变量

Ian*_*des 2 python sqlite peewee

使用下面的示例,在我的机器上,设置range(150)会导致错误,而range(100)不是:

from peewee import *

database = SqliteDatabase(None)

class Base(Model):
    class Meta:
        database = database


colnames = ["A", "B", "C", "D", "E", "F", "G", "H"]
cols = {x: TextField() for x in colnames}

table = type('mytable', (Base,), cols)
database.init('test.db')
database.create_tables([table])

data = []
for x in range(150):
    data.append({x: 1 for x in colnames})


with database.atomic() as txn:
    table.insert_many(data).upsert().execute()
Run Code Online (Sandbox Code Playgroud)

导致:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/cluster/home/ifiddes/python2.7/lib/python2.7/site-packages/peewee.py", line 3213, in execute
    cursor = self._execute()
  File "/cluster/home/ifiddes/python2.7/lib/python2.7/site-packages/peewee.py", line 2628, in _execute
    return self.database.execute_sql(sql, params, self.require_commit)
  File "/cluster/home/ifiddes/python2.7/lib/python2.7/site-packages/peewee.py", line 3461, in execute_sql
    self.commit()
  File "/cluster/home/ifiddes/python2.7/lib/python2.7/site-packages/peewee.py", line 3285, in __exit__
    reraise(new_type, new_type(*exc_args), traceback)
  File "/cluster/home/ifiddes/python2.7/lib/python2.7/site-packages/peewee.py", line 3454, in execute_sql
    cursor.execute(sql, params or ())
peewee.OperationalError: too many SQL variables
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎很低落.我试图用来peewee替换现有的pandas基于SQL的构造,因为pandas缺少对主键的支持.只能在每个循环中插入~100条记录非常低,如果列数在某一天上升,则非常脆弱.

我怎样才能让这项工作变得更好?可能吗?

Fra*_*ano 11

经过一些调查后,问题似乎与sql查询可以拥有的最大参数数量有关:SQLITE_MAX_VARIABLE_NUMBER.

为了能够进行大量批量插入,我首先估计SQLITE_MAX_VARIABLE_NUMBER,然后使用它在我想要插入的字典列表中创建块.

为了估计值,我使用此功能的灵感来自这个答案:


def max_sql_variables():
    """Get the maximum number of arguments allowed in a query by the current
    sqlite3 implementation. Based on `this question
    `_

    Returns
    -------
    int
        inferred SQLITE_MAX_VARIABLE_NUMBER
    """
    import sqlite3
    db = sqlite3.connect(':memory:')
    cur = db.cursor()
    cur.execute('CREATE TABLE t (test)')
    low, high = 0, 100000
    while (high - 1) > low: 
        guess = (high + low) // 2
        query = 'INSERT INTO t VALUES ' + ','.join(['(?)' for _ in
                                                    range(guess)])
        args = [str(i) for i in range(guess)]
        try:
            cur.execute(query, args)
        except sqlite3.OperationalError as e:
            if "too many SQL variables" in str(e):
                high = guess
            else:
                raise
        else:
            low = guess
    cur.close()
    db.close()
    return low

SQLITE_MAX_VARIABLE_NUMBER = max_sql_variables()
Run Code Online (Sandbox Code Playgroud)

然后我使用上面的变量来切片 data


with database.atomic() as txn:
    size = (SQLITE_MAX_VARIABLE_NUMBER // len(data[0])) -1
    # remove one to avoid issue if peewee adds some variable
    for i in range(0, len(data), size):
        table.insert_many(data[i:i+size]).upsert().execute()
Run Code Online (Sandbox Code Playgroud)

关于执行速度的更新max_sql_variables.

在具有4核和4 Gb RAM的3年历史的Intel机器上运行OpenSUSE风滚草,SQLITE_MAX_VARIABLE_NUMBER设置为999,该功能运行时间不到100毫秒.如果我设置high = 1000000,执行时间变为300ms的量级.

在具有8核和8Gb RAM的年轻英特尔机器上运行Kubuntu,SQLITE_MAX_VARIABLE_NUMBER设置为250000,该功能在大约2.6秒内运行并返回99999.如果我设置high = 1000000,则执行时间变为4.5秒的量级.