diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 469c845bf..691889cb3 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -636,7 +636,7 @@ extension SQLRelation { } // - guard selection.allSatisfy(\.isTriviallyCountable) else { + if selection.contains(where: \.requiresTrivialCount) { return try fetchTrivialCount(db) } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index a0f29120d..c616c701b 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -245,15 +245,25 @@ extension SQLSelection { } } + /// Returns whether this selection MUST be counted with a "trivial" + /// count: `SELECT COUNT(*) FROM (SELECT ...)`. + /// /// Supports SQLRelation.fetchCount. /// /// See - var isTriviallyCountable: Bool { + var requiresTrivialCount: Bool { switch impl { case .aliasedExpression, .literal: - return false - case .allColumns, .qualifiedAllColumns, .expression: + // Trivial count is required. + // + // For example, the WHERE clause here requires the aliased + // column to be preserved in the counting request: + // SELECT *, column AS alt FROM player WHERE alt return true + case .allColumns, .qualifiedAllColumns: + return false + case .expression: + return false } } }