SQLalchemy:允许“链式”构建查询对象吗?

时间:2019-06-17 07:36:27

标签: python sqlalchemy

我在无法重现的Flask / SQLAlchemy应用程序中收到虚假错误。但是在Apache错误日志中,我看到大型堆栈转储的结尾是这样的:

"Can't reconnect until invalid "
sqlalchemy.exc.InvalidRequestError: Can't reconnect until invalid transaction is rolled back

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

[ .... many lines of stack trace .... ]

"Can't reconnect until invalid "
 sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) Can't reconnect until invalid transaction is rolled back
 [SQL: SELECT chart.id AS chart_id, chart.anltyp AS chart_anltyp, chart.anlnum AS chart_anlnum, chart.przsrt AS chart_przsrt, chart.tst_art_num AS chart_tst_art_num, chart.regel AS chart_regel, chart.name AS chart_name, chart.anl_name AS chart_anl_name, chart.aktiv AS chart_aktiv_
 FROM chart INNER JOIN clientview ON chart.anltyp = clientview.anltyp AND chart.anlnum = clientview.anlnum_
 WHERE clientview.id = %s AND chart.aktiv != %s]
 [parameters: [{}]]

我真的无法弄清楚SQL语句是此错误的原因或结果,但是让我感到奇怪的是“ parameters:[{}]”位。似乎SQL语句需要参数,但是执行不提供任何参数,这不应该发生,因为这是由SQLALchemy ORM生成的。有问题的代码是:

charts = db.query(Chart)
if not new_view:
    charts = charts.join(View).filter(View.id == view_id)
charts = charts.filter(Chart.aktiv != 0).all()
charts.sort(key=key_anlage)

我想知道是否通过将内容重新分配给“图表”来弄乱事情。我可能会反复创建和销毁查询对象。这样的代码当然很容易重构(有一些冗余),像这样:

if not new_view:
    charts = db.query(Chart).join(View).\
        filter(View.id == view_id).\
        filter(Chart.aktiv != 0).all()
else:
    charts = db.query(Chart).\
        filter(Chart.aktiv != 0).all()

charts.sort(key=key_anlage)

我刚刚完成了此操作,到目前为止,该错误没有再发生,但是我可以确定只有一两天。所以我的问题是:

1)SQLAlchemy发出带有空参数的语句的原因可能是什么?

2)如果这是我的代码,那么有条件地将联接添加到语句的更聪明的方法是什么?

也许是“ chart = chart.all()”将查询转换为结果列表,事后看来有点愚蠢。当然,这是whoe只是一个简单的查询而没有可选过滤器和联接的遗留物。

0 个答案:

没有答案