diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 12d847823..fb137e7c4 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -107,6 +107,18 @@ public final class DatabaseFunction: Hashable { self.kind = .aggregate { Aggregate() } } + /// Returns an SQL expression that applies the function. + /// + /// See https://github.com/groue/GRDB.swift/#sql-functions + public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { + switch kind { + case .aggregate: + return .function(name, arguments.map(\.sqlExpression)) + case .function: + return .aggregate(name, arguments.map(\.sqlExpression)) + } + } + /// Calls sqlite3_create_function_v2 /// See https://sqlite.org/c3ref/create_function.html func install(in db: Database) { diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index fde5a0685..6163a2cf2 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -38,8 +38,8 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { - let expression = SQLExpression.countDistinct(.fastPrimaryKey) - return makeAggregate(expression).forKey("\(key.singularizedName)Count") + makeAggregate(.countDistinct(.fastPrimaryKey)) + .forKey("\(key.singularizedName)Count") } /// Creates an aggregate that is true if there exists no associated records. @@ -58,8 +58,8 @@ extension AssociationToMany { /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { - let expression = SQLExpression.isEmpty(.countDistinct(.fastPrimaryKey)) - return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") + makeAggregate(.isEmpty(.countDistinct(.fastPrimaryKey))) + .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } /// Creates an aggregate which evaluate to the average value of the given @@ -80,7 +80,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) public func average(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.function("AVG", [expression.sqlExpression])) + let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -107,7 +107,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) public func max(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.function("MAX", [expression.sqlExpression])) + let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -134,7 +134,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) public func min(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.function("MIN", [expression.sqlExpression])) + let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -161,7 +161,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) public func sum(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.function("SUM", [expression.sqlExpression])) + let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 582181cde..203e604d8 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -95,21 +95,14 @@ public struct SQLExpression { /// COLLATE indirect case collated(SQLExpression, Database.CollationName) - /// The `COUNT` function. - /// - /// COUNT(*) - /// COUNT() - indirect case count(SQLSelection) - - /// The `COUNT(DISTINCT)` function. - /// - /// COUNT(DISTINCT ) - indirect case countDistinct(SQLExpression) + /// The `COUNT(*)` expression. + case countAll /// A function call. /// /// (, ...) - case function(String, [SQLExpression]) + /// (DISTINCT ) + case function(String, aggregate: Bool, distinct: Bool, arguments: [SQLExpression]) /// An expression that checks for zero or positive values. /// @@ -148,7 +141,7 @@ public struct SQLExpression { /// Fuels `!expression` case falsey } - + /// `AssociativeBinaryOperator` is an associative binary operator, /// such as `+`, `*`, `AND`, etc. /// @@ -251,7 +244,7 @@ public struct SQLExpression { strictlyAssociative: true, bijective: true) } - + /// `BinaryOperator` is an SQLite binary operator, such as `>`, `=`, etc. /// /// See also `AssociativeBinaryOperator` and `EqualityOperator`. @@ -323,7 +316,7 @@ public struct SQLExpression { } } } - + /// `UnaryOperator` is a SQLite unary operator. struct UnaryOperator: Hashable { /// The SQL operator @@ -546,26 +539,48 @@ extension SQLExpression { // MARK: Functions + /// The `COUNT(*)` expression. + static let countAll = SQLExpression(impl: .countAll) + /// The `COUNT` function. /// - /// COUNT(*) - /// COUNT() - static func count(_ selection: SQLSelection) -> Self { - self.init(impl: .count(selection)) + /// COUNT() + static func count(_ expression: SQLExpression) -> Self { + .aggregate("COUNT", [expression]) } /// The `COUNT(DISTINCT)` function. /// /// COUNT(DISTINCT ) static func countDistinct(_ expression: SQLExpression) -> Self { - self.init(impl: .countDistinct(expression)) + .distinctAggregate("COUNT", expression) } /// A function call. /// /// (, ...) - static func function(_ name: String, _ expressions: [SQLExpression]) -> Self { - self.init(impl: .function(name, expressions)) + /// + /// - warning: for aggregate functions, call one of: + /// - `SQLExpression.aggregate(_:_:)`, + /// - `SQLExpression.distinctAggregate(_:_:)`, + /// - `SQLExpression.countDistinct(_:)` + /// - `SQLExpression.countAll`. + static func function(_ name: String, _ arguments: [SQLExpression]) -> Self { + self.init(impl: .function(name, aggregate: false, distinct: false, arguments: arguments)) + } + + /// An aggregate function call. + /// + /// (, ...) + static func aggregate(_ name: String, _ arguments: [SQLExpression]) -> Self { + self.init(impl: .function(name, aggregate: true, distinct: false, arguments: arguments)) + } + + /// A distinct aggregate function call. + /// + /// (DISTINCT ) + static func distinctAggregate(_ name: String, _ argument: SQLExpression) -> Self { + self.init(impl: .function(name, aggregate: true, distinct: true, arguments: [argument])) } /// An expression that checks for zero or positive values. @@ -674,15 +689,15 @@ extension SQLExpression { case let .collated(expression, _): return try expression.column(db, for: alias, acceptsBijection: acceptsBijection) - case let .function(name, expressions): + case let .function(name, aggregate: false, distinct: false, arguments: arguments): guard acceptsBijection else { return nil } let name = name.uppercased() - if ["HEX", "QUOTE"].contains(name) && expressions.count == 1 { - return try expressions[0].column(db, for: alias, acceptsBijection: acceptsBijection) - } else if name == "IFNULL" && expressions.count == 2 && expressions[1].isConstantInRequest { - return try expressions[0].column(db, for: alias, acceptsBijection: acceptsBijection) + if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 { + return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection) + } else if name == "IFNULL" && arguments.count == 2 && arguments[1].isConstantInRequest { + return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection) } else { return nil } @@ -844,16 +859,15 @@ extension SQLExpression { } return resultSQL - case let .count(selection): - return try "COUNT(\(selection.countedSQL(context)))" + case .countAll: + return "COUNT(*)" - case let .countDistinct(expression): - return try "COUNT(DISTINCT \(expression.sql(context)))" - - case let .function(name, expressions): + case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments): + assert(!distinct || aggregate, "distinct requires aggregate") + assert(!distinct || arguments.count == 1, "distinct requires a single argument") return try name - + "(" - + expressions.map { try $0.sql(context) }.joined(separator: ", ") + + (distinct ? "(DISTINCT " : "(") + + arguments.map { try $0.sql(context) }.joined(separator: ", ") + ")" case let .isEmpty(expression, isNegated: isNegated): @@ -1279,15 +1293,15 @@ extension SQLExpression { let .collated(expression, _): return expression.isConstantInRequest - case let .function(name, expressions): + case let .function(name, aggregate: false, distinct: false, arguments: arguments): let name = name.uppercased() - guard ((name == "MAX" || name == "MIN") && expressions.count > 1) + guard ((name == "MAX" || name == "MIN") && arguments.count > 1) || Self.knownPureFunctions.contains(name) else { return false // Don't know - assume not constant } - return expressions.allSatisfy(\.isConstantInRequest) + return arguments.allSatisfy(\.isConstantInRequest) default: return false @@ -1348,14 +1362,12 @@ extension SQLExpression { case let .collated(expression, collationName): return .collated(expression.qualified(with: alias), collationName) - case let .count(selection): - return .count(selection.qualified(with: alias)) + case .countAll: + return .countAll - case let .countDistinct(expression): - return .countDistinct(expression.qualified(with: alias)) - - case let .function(name, expressions): - return .function(name, expressions.map { $0.qualified(with: alias) }) + case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments): + return SQLExpression(impl: .function(name, aggregate: aggregate, distinct: distinct, + arguments: arguments.map { $0.qualified(with: alias) })) case let .isEmpty(expression, isNegated: isNegated): return .isEmpty(expression.qualified(with: alias), isNegated: isNegated) @@ -1414,23 +1426,10 @@ extension SQLExpression { return false - case .count, - .countDistinct: + case .countAll, + .function(_, aggregate: true, distinct: _, arguments: _): return true - case let .function(name, expressions): - let name = name.uppercased() - if ["MIN", "MAX"].contains(name) && expressions.count == 1 { - return true - } else if ["AVG", "COUNT", "SUM", "TOTAL"].contains(name) && expressions.count == 1 { - return true - } else if name == "GROUP_CONCAT" && (expressions.count == 1 || expressions.count == 2) { - return true - } else { - // Return true if all arguments are aggregates? - return false - } - default: return false } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index f350abeef..7c39dd23a 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -1,15 +1,3 @@ -// MARK: - Custom Functions - -extension DatabaseFunction { - /// Returns an SQL expression that applies the function. - /// - /// See https://github.com/groue/GRDB.swift/#sql-functions - public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { - .function(name, arguments.map(\.sqlExpression)) - } -} - - // MARK: - ABS(...) /// Returns an expression that evaluates the `ABS` SQL function. @@ -28,18 +16,19 @@ public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { /// // AVG(length) /// average(Column("length")) public func average(_ value: SQLSpecificExpressible) -> SQLExpression { - .function("AVG", [value.sqlExpression]) + .aggregate("AVG", [value.sqlExpression]) } // MARK: - COUNT(...) +// TODO: deprecate, replace with count(expression) /// Returns an expression that evaluates the `COUNT` SQL function. /// /// // COUNT(email) /// count(Column("email")) public func count(_ counted: SQLSelectable) -> SQLExpression { - .count(counted.sqlSelection) + counted.sqlSelection.countExpression } @@ -83,7 +72,7 @@ public func length(_ value: SQLSpecificExpressible) -> SQLExpression { /// // MAX(score) /// max(Column("score")) public func max(_ value: SQLSpecificExpressible) -> SQLExpression { - .function("MAX", [value.sqlExpression]) + .aggregate("MAX", [value.sqlExpression]) } @@ -94,7 +83,7 @@ public func max(_ value: SQLSpecificExpressible) -> SQLExpression { /// // MIN(score) /// min(Column("score")) public func min(_ value: SQLSpecificExpressible) -> SQLExpression { - .function("MIN", [value.sqlExpression]) + .aggregate("MIN", [value.sqlExpression]) } @@ -105,7 +94,7 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression { /// // SUM(amount) /// sum(Column("amount")) public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { - .function("SUM", [value.sqlExpression]) + .aggregate("SUM", [value.sqlExpression]) } diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index c069475b9..83fe3a7b3 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -123,7 +123,7 @@ extension SQLQuery { countQuery.isDistinct = false switch count { case .all: - countQuery = countQuery.select(.count(.allColumns)) + countQuery = countQuery.select(.countAll) case .distinct(let expression): countQuery = countQuery.select(.countDistinct(expression)) } @@ -138,7 +138,7 @@ extension SQLQuery { // SELECT expr1, expr2, ... FROM tableName ... // -> // SELECT COUNT(*) FROM tableName ... - let countQuery = unordered().select(SQLExpression.count(.allColumns)) + let countQuery = unordered().select(.countAll) return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! } } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index f919460d9..e4bbfb781 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -3,15 +3,12 @@ public struct SQLSelection { private var impl: Impl + /// The private implementation of the public `SQLSelection`. private enum Impl { - /// All columns - /// - /// SELECT * + /// All columns: `*` case allColumns - /// All columns from a table - /// - /// SELECT player.* + /// All columns, qualified: `player.*` case qualifiedAllColumns(TableAlias) // As long as the CTE is embedded here, the following request will fail @@ -28,48 +25,55 @@ public struct SQLSelection { // - prefer `annotated(with:)` when she wants to extend the selection. // // TODO: Make `cteRequestOrAssociation.select(AllColumns())` possible. - /// All columns from a common table expression + /// All columns of a common table expression case allCTEColumns(SQLCTE) + /// All columns of a common table expression, qualified case qualifiedAllCTEColumns(SQLCTE, TableAlias) /// An expression - /// - /// SELECT id - /// SELECT LENGTH(name) case expression(SQLExpression) /// An aliased expression /// - /// SELECT score + bonud AS totalScore + /// AS name case aliasedExpression(SQLExpression, String) /// A literal SQL selection case literal(SQLLiteral) } + /// All columns: `*` static let allColumns = SQLSelection(impl: .allColumns) + /// All columns, qualified: `player.*` static func qualifiedAllColumns(_ alias: TableAlias) -> Self { self.init(impl: .qualifiedAllColumns(alias)) } + /// All columns of a common table expression static func allCTEColumns(_ cte: SQLCTE) -> Self { self.init(impl: .allCTEColumns(cte)) } + /// All columns of a common table expression, qualified static func qualifiedAllCTEColumns(_ cte: SQLCTE, _ alias: TableAlias) -> Self { self.init(impl: .qualifiedAllCTEColumns(cte, alias)) } + /// An expression static func expression(_ expression: SQLExpression) -> Self { self.init(impl: .expression(expression)) } + /// An aliased expression + /// + /// AS name static func aliasedExpression(_ expression: SQLExpression, _ name: String) -> Self { self.init(impl: .aliasedExpression(expression, name)) } + /// A literal SQL selection static func literal(_ sqlLiteral: SQLLiteral) -> Self { self.init(impl: .literal(sqlLiteral)) } @@ -104,9 +108,29 @@ extension SQLSelection { """) } } -} - -extension SQLSelection { + + /// Support for `count(selection)`. + /// TODO: deprecate `count(selection)`, and get rid of this property. + var countExpression: SQLExpression { + switch impl { + case .allColumns, + .allCTEColumns: + return .countAll + + case .qualifiedAllColumns, + .qualifiedAllCTEColumns: + // COUNT(player.*) is not valid SQL + fatalError("Uncountable selection") + + case let .expression(expression), + let .aliasedExpression(expression, _): + return .count(expression) + + case let .literal(sqlLiteral): + return .count(sqlLiteral.sqlExpression) + } + } + /// If the selection can be counted, return how to count it. func count(distinct: Bool) -> SQLCount? { switch impl { @@ -182,9 +206,7 @@ extension SQLSelection { """) } } -} - -extension SQLSelection { + /// Returns the SQL that feeds the selection of a `SELECT` statement. /// /// For example: @@ -221,9 +243,7 @@ extension SQLSelection { return try sqlLiteral.sql(context) } } -} - -extension SQLSelection { + /// Returns true if the selection is an aggregate. /// /// When in doubt, returns false. @@ -252,9 +272,7 @@ extension SQLSelection { return false } } -} - -extension SQLSelection { + /// Returns a qualified selection func qualified(with alias: TableAlias) -> SQLSelection { switch impl {