SQLite:如何使用 Python API 启用解释计划?

SQLite: How to enable explain plan with the 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