2

我想使用 json_extract, json_tree, json_each 的 JSON1 Extension 特性,使用 flask-sqlalchemy 启用 sqlite3 数据库。

参考此处的链接,我正在进行 ORM 查询,如下所示:

模型

 class EventHistory(db.Model):

    timestamp = db.Column(db.Text(), nullable=False, primary_key=True)
    event = db.Column(JSON, nullable=False)

控制器

 @mod_home.route("/dummyHist/", methods=['GET'])
def get_events():
    filter = request.args.get('filter')
    response_obj = {}
    query = db.session.query(EventHistory).select_from(
        EventHistory,
        alias(func.json_each(
            EventHistory.event,
            text('\'$.about\'')), 'b')).filter(text('b.value =\'' + filter + '\'')).order_by(
        desc(EventHistory.timestamp))
    query_result = query.limit(3)

SQLALCHEMY_ECHO = True

查询回显到日志如下:

2019-08-20 20:12:10,208 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-08-20 20:12:10,209 INFO sqlalchemy.engine.base.Engine SELECT event_history_table.timestamp AS event_history_table_timestamp, event_history_table.event AS event_history_table_event 
FROM event_history_table, json_each(event_history_table.event, '$.about') AS b 
WHERE b.value ='connection' ORDER BY event_history_table.timestamp DESC
 LIMIT ? OFFSET ?
2019-08-20 20:12:10,209 INFO sqlalchemy.engine.base.Engine (3, 0)

低于 sqlalchemy.exc.OperationalErr:没有这样的表 json_each

Traceback (most recent call last):
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\base.py", line 1244, in _execute_context
    cursor, statement, parameters, context
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\default.py", line 552, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: json_each

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

Traceback (most recent call last):
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Integrated Satellite Module\onewebism\src-flalsk\app\home\controllers.py", line 100, in get_events
    for result in query_result:
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\orm\query.py", line 3330, in __iter__
    return self._execute_and_instances(context)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\orm\query.py", line 3355, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\base.py", line 988, in execute
    return meth(self, multiparams, params)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\sql\elements.py", line 287, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\base.py", line 1107, in _execute_clauseelement
    distilled_params,
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\base.py", line 1248, in _execute_context
    e, statement, parameters, cursor, context
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\base.py", line 1466, in _handle_dbapi_exception
    util.raise_from_cause(sqlalchemy_exception, exc_info)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\util\compat.py", line 398, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\util\compat.py", line 152, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\base.py", line 1244, in _execute_context
    cursor, statement, parameters, context
  File "C:\Users\e01703\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\default.py", line 552, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: json_each
[SQL: SELECT event_history_table.timestamp AS event_history_table_timestamp, event_history_table.event AS event_history_table_event 
FROM event_history_table, json_each(event_history_table.event, '$.about') AS b 
WHERE b.value ='connection' ORDER BY event_history_table.timestamp DESC
 LIMIT ? OFFSET ?]
[parameters: (3, 0)]
(Background on this error at: http://sqlalche.me/e/e3q8)

使用 sqlite3 shell 运行时生成的相同查询给出以下输出:

2019-08-20T10:02:12.692802|{"id": 936699609, "text": "Sample text for event", "severity": "critical", "about": ["antenna", "connection", "modem", "network"]}
2019-08-20T09:56:58.656774|{"id": 164654307, "text": "Sample text for event", "severity": "info", "about": ["connection", "network"]}
2019-08-20T09:54:11.646938|{"id": 266579356, "text": "Sample text for event", "severity": "critical", "about": ["connection", "network", "antenna", "modem", "signal"]}
4

1 回答 1

0

我想知道如何自己使用 json_each 和 sqlalchemy,我做了几个测试。您编写的代码在 sqlachemy 1.4 中有效,但它会发出有关笛卡尔积的警告。如果然后尝试多种方法来编写使用更多 sqlalchemy 的上述语句: https ://gist.github.com/PiotrCzapla/579f76bdf95a485eaaaafed1492d9a70e

最后一个似乎是最好的方法,并且由于以下原因,它不会发出警告join(...,true())

from sqlalchemy import true
   
about = func.json_each(EventHistory.event, '$.about').table_valued('value')
events = s.query(EventHistory).join(about, true()).filter(about.c.value == 'connection')
于 2021-08-31T11:52:03.513 回答