def test_render_explain_analyze(self, session, Article): assert str( explain_analyze(session.query(Article)) .compile( dialect=postgresql.dialect() ) ).startswith('EXPLAIN (ANALYZE true) SELECT')
def analyze(conn, query): """ Analyze query using given connection and return :class:`QueryAnalysis` object. Analysis is performed using database specific EXPLAIN ANALYZE construct and then examining the results into structured format. Currently only PostgreSQL is supported. Getting query runtime (in database level) :: from sqlalchemy_utils import analyze analysis = analyze(conn, 'SELECT * FROM article') analysis.runtime # runtime as milliseconds Analyze can be very useful when testing that query doesn't issue a sequential scan (scanning all rows in table). You can for example write simple performance tests this way.:: query = ( session.query(Article.name) .order_by(Article.name) .limit(10) ) analysis = analyze(self.connection, query) analysis.node_types # [u'Limit', u'Index Only Scan'] assert 'Seq Scan' not in analysis.node_types .. versionadded: 0.26.17 :param conn: SQLAlchemy Connection object :param query: SQLAlchemy Query object or query as a string """ return QueryAnalysis( conn.execute( explain_analyze(query, buffers=True, format='json') ).scalar() )