From a3351513cef2bfc37fd93457e5b6adc49e882076 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 5 Dec 2020 19:50:47 +0100 Subject: [PATCH] Optimize inclusion of CTE association In order to count the selected columns of a CTE, we do not need to have SQLite compile the whole CTE request when we have information about the selected columns. --- .../Request/CommonTableExpression.swift | 9 ++---- .../SQLGeneration/SQLQueryGenerator.swift | 32 +++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index cfe0db37b..48383d8c2 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -179,12 +179,9 @@ struct SQLCTE { return columns.count } - // Compile request. We can freely use the statement cache because we - // do not execute the statement or modify its arguments. - let context = SQLGenerationContext(db) - let sql = try request.requestSQL(context, forSingleResult: false) - let statement = try db.cachedSelectStatement(sql: sql) - return statement.columnCount + var counter = SelectedColumnsCounter(db: db) + try request._accept(&counter) + return counter.columnCount } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 30516fba8..98b87c0df 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -500,6 +500,38 @@ struct SQLQueryGenerator: Refinable { } } +/// A FetchRequest visitor that counts the selected columns +struct SelectedColumnsCounter: _FetchRequestVisitor { + let db: Database + var columnCount = 0 + + mutating func visit(_ request: AdaptedFetchRequest) throws { + try request.base._accept(&self) + } + + mutating func visit(_ request: QueryInterfaceRequest) throws { + // We need a qualified relation so that the selected columns are + // qualified with a table name: naked `SELECT *` are replaced + // with `SELECT player.*`, which we can count. + let qualifiedRelation = SQLQualifiedRelation(request.query.relation) + columnCount = try qualifiedRelation + .selectionPromise + .resolve(db) + .reduce(0) { + try $0 + $1._columnCount(db) + } + } + + mutating func visit(_ request: SQLRequest) throws { + // Compile request. We can freely use the statement cache because we + // do not execute the statement or modify its arguments. + let context = SQLGenerationContext(db) + let sql = try request.requestSQL(context, forSingleResult: false) + let statement = try db.cachedSelectStatement(sql: sql) + columnCount = statement.columnCount + } +} + /// A "qualified" relation, where all tables are identified with a table alias. /// /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...