【问题标题】:sqlite3.OperationalError: too many SQL variables when deploying on AWS elastic beanstalksqlite3.OperationalError:在 AWS 弹性 beantalk 上部署时 SQL 变量过多
【发布时间】:2020-04-20 22:51:56
【问题描述】:

当使用 Flask / sqlAlchemy 从我的 sqlite 数据库中选择行时:

Restaurants.index.in_(filtered_res_ids))).fetchall())

我在 pycharm 中测试时得到了我想要的结果。 但是,当将它部署到我的 AWS 弹性豆茎时,它给我带来了问题。

这是我的一些错误日志:

[Mon Dec 23 18:23:28.956847 2019] [:error] [pid 3451] WHERE restaurants_image_price_english."index" IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ... )


[2019-12-23 18:23:28,958] ERROR in app: Exception on /restaurantDiscover [POST]
Traceback (most recent call last):
File "/opt/python/run/venv/local/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1244, in _execute_context
cursor, statement, parameters, context
File "/opt/python/run/venv/local/lib64/python3.6/site-packages/sqlalchemy/engine/default.py", line 552, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: too many SQL variables

我应该使用不同的实现吗?

【问题讨论】:

    标签: python sqlite flask sqlalchemy amazon-elastic-beanstalk


    【解决方案1】:

    根据docs sqlite 在一个查询中最多允许 999 个变量

    SQLite 分配空间来保存从 1 到使用的最大主机参数号之间的所有主机参数。因此,包含主机参数(如 ?1000000000)的 SQL 语句将需要千兆字节的存储空间。这很容易使主机的资源不堪重负。为防止内存分配过多,主机参数编号的最大值为 SQLITE_MAX_VARIABLE_NUMBER,默认为 999。

    如果不重新编译sqlite,这个值不能增加。

    filtered_res_ids 可能包含的不止这些。

    您必须将其拆分为 999 个元素的块并使用多个查询。硬编码示例:

    # first 999
    Restaurants.index.in_(filtered_res_ids[:999]))).fetchall())
    
    # last 999
    Restaurants.index.in_(filtered_res_ids[999:]))).fetchall())
    

    当然,如果 filtered_res_ids 包含超过 1998 个元素,则您需要将其动态拆分为最多 999 个元素的块,如对 this question 的回答中所述。

    编辑

    由于您提到相同的代码在本地工作,您部署应用程序的远程服务器很可能运行重新编译的 sqlite 版本,SQLITE_MAX_VARIABLE_NUMBER 的值较低(或者它在运行时降低它作为文档建议有可能)。

    您可能必须深入研究 AWS 文档以找到它们允许的最大值,或者在您的代码中反复尝试,直到找到一个可行的值。

    【讨论】:

    • 很高兴知道,谢谢!仍然很奇怪,仅在部署代码而不是在我的计算机上处​​于调试模式时才会发生此错误
    • @SumakuTension 我添加了一个解释为什么会发生这种情况
    • 一个可能在 SQLA 1.4 中起作用的选项是使用带有 literal_execute 的扩展绑定参数:stackoverflow.com/questions/57829682/…
    猜你喜欢
    • 1970-01-01
    • 2012-08-24
    • 2018-08-17
    • 2014-11-29
    • 2016-11-29
    • 2020-11-25
    • 2018-03-26
    • 2020-12-16
    • 2016-10-11
    相关资源
    最近更新 更多