python - SQLite:如何使用 Python API 启用解释计划?
问题描述
我正在使用 Python(和 Peewee)连接到 SQLite 数据库。我的数据访问层 (DAL) 是 peewee ORM 和基于 SQL 的函数的混合体。我想在连接到数据库时为所有查询启用 EXPLAIN PLAN 并通过配置或 CLI 参数切换它......我怎样才能使用 Python API 做到这一点?
from playhouse.db_url import connect
self._logger.info("opening db connection to database, creating cursor and initializing orm model ...")
self.__db = connect(url)
# add support for a REGEXP and POW implementation
# TODO: this should be added only for the SQLite case and doesn't apply to other vendors.
self.__db.connection().create_function("REGEXP", 2, regexp)
self.__db.connection().create_function("POW", 2, pow)
self.__cursor = self.__db.cursor()
self.__cursor.arraysize = 100
# what shall I do here to enable EXPLAIN PLANs?
解决方案
这是 sqlite 交互式 shell 的一个特性。要获取查询计划,您需要明确请求它。这对 Peewee 来说不是很简单,因为它使用参数化查询。您可以通过几种方式让 peewee 执行 SQL。
# Print all queries to stderr.
import logging
logger = logging.getLogger('peewee')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
或者对于单个查询:
query = SomeModel.select()
sql, params = query.sql()
# To get the query plan:
curs = db.execute_sql('EXPLAIN ' + sql, params)
print(curs.fetchall()) # prints query plan
推荐阅读
- r - R - 如何读取每个excel文件的最后一张?
- mysql - Relationship Model between Three Tables in a Fourth Table
- linux - 创建目录和子目录的 Bash 文件
- excel - 打开嵌入的 Excel 文件会使 Excel 崩溃
- node.js - Json 文件从节点脚本中随机损坏
- jquery - The element data-toggle does not run or support in form tag?
- firebase - Firebase Analytics 中的事件未显示在 Big Query 中
- c# - 如何在 MVC Core 2 Razor 3 中为图像位置组合字符串?
- reactjs - React js 将类转换为函数
- php - 如何将文件发送给使用联系表的用户?