代码之家  ›  专栏  ›  技术社区  ›  SkyWalker

SQLite:如何使用pythonapi启用explain计划?

  •  0
  • SkyWalker  · 技术社区  · 4 年前

    我使用Python(和Peewee)连接到SQLite数据库。我的数据访问层(DAL)是peeweeorm和基于SQL的函数的混合体。我想在连接到数据库时为所有查询启用解释计划,并通过配置或CLI参数进行切换。。。如何使用pythonapi实现这一点?

    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?
    
    0 回复  |  直到 4 年前
        1
  •  2
  •   coleifer    4 年前

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