首页 > 解决方案 > 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?

标签: pythondatabasesqlitesql-execution-planpeewee

解决方案


这是 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

推荐阅读