diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 5a470c64f..7dcf92b75 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -980,26 +980,6 @@ extension SQLExpression { } } -extension SQLExpression { - /// Returns true iff the expression is trivially true. - /// - /// When in doubt, returns false. - /// - /// This property helps clearing up the JOIN clauses. - var isTrue: Bool { - switch impl { - case .databaseValue(true.databaseValue): - return true - - case let .collated(expression, _): - return expression.isTrue - - default: - return false - } - } -} - extension SQLExpression { /// Returns a qualified expression func qualified(with alias: TableAlias) -> SQLExpression { diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index ba461f740..8a2915ab1 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -5,10 +5,7 @@ struct SQLQuery { var relation: SQLRelation var isDistinct: Bool = false var groupPromise: DatabasePromise<[SQLExpression]>? - // Having clause is an array of expressions that we'll join with - // the AND operator. This gives nicer output in generated SQL: - // `(a AND b AND c)` instead of `((a AND b) AND c)`. - var havingExpressionsPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: []) + var havingExpressionPromise: DatabasePromise = DatabasePromise(value: nil) var limit: SQLLimit? var ctes: OrderedDictionary = [:] } @@ -65,9 +62,13 @@ extension SQLQuery: AggregatingRequest { } func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - map(\.havingExpressionsPromise) { havingExpressionsPromise in + map(\.havingExpressionPromise) { promise in DatabasePromise { db in - try havingExpressionsPromise.resolve(db) + [predicate(db).sqlExpression] + if let filter = try promise.resolve(db) { + return try filter && predicate(db) + } else { + return try predicate(db).sqlExpression + } } } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 50459e48a..2a724ec05 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -13,21 +13,19 @@ /// • selection /// /// Other SQL clauses such as GROUP BY, LIMIT are defined one level up, in the -/// SQLQuery type. +/// `SQLQuery` type. /// /// ## Promises /// -/// Filter and ordering are actually "promises", which are only resolved -/// when a database connection is available. This is how we can implement -/// requests such as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`: -/// both need a database connection in order to introspect the primary key. +/// Selection, filter, and ordering are "promises" which are resolved when a +/// database connection is available. This is how we can implement requests such +/// as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`: both need a +/// database connection in order to introspect the primary key. For example: /// -/// // SELECT * FROM player -/// // WHERE continent = 'EU' -/// // ORDER BY code -- primary key infered from the database schema -/// Country -/// .filter(Column("continent") == "EU") -/// .orderByPrimaryKey() +/// // SELECT * FROM country ORDER BY code +/// // ~~~~~~~~~~~~~ +/// // primary key infered from the database schema +/// Country.orderByPrimaryKey() /// /// ## Children /// @@ -159,13 +157,11 @@ struct SQLRelation { var source: SQLSource var selectionPromise: DatabasePromise<[SQLSelection]> = DatabasePromise(value: []) - // Filter is an array of expressions that we'll join with the AND operator. - // This gives nicer output in generated SQL: `(a AND b AND c)` instead of - // `((a AND b) AND c)`. - var filtersPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: []) + var filterPromise: DatabasePromise = DatabasePromise(value: nil) var ordering: SQLRelation.Ordering = SQLRelation.Ordering() var children: OrderedDictionary = [:] + /// All prefetched associations (`including(all:)`), recursively var prefetchedAssociations: [_SQLAssociation] { children.flatMap { key, child -> [_SQLAssociation] in switch child.kind { @@ -247,9 +243,13 @@ extension SQLRelation: Refinable { extension SQLRelation: FilteredRequest { func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - map(\.filtersPromise) { filtersPromise in + map(\.filterPromise) { promise in DatabasePromise { db in - try filtersPromise.resolve(db) + [predicate(db).sqlExpression] + if let filter = try promise.resolve(db) { + return try filter && predicate(db) + } else { + return try predicate(db).sqlExpression + } } } } @@ -555,11 +555,11 @@ enum SQLAssociationCondition { /// player[Column("id")] == bonus[Column("playerID")] /// }) /// Player.with(bonus).joining(required: association) - case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression) + case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression?) /// The condition that does not constrain the two associated tables /// in any way. - static let none = expression({ _, _ in true.sqlExpression }) + static let none = expression({ _, _ in nil }) func reversed(to destinationTable: String) -> SQLAssociationCondition { switch self { @@ -570,19 +570,19 @@ enum SQLAssociationCondition { } } - func joinExpressions( + func joinExpression( _ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) - throws -> [SQLExpression] + throws -> SQLExpression? { switch self { case let .expression(condition): - return [condition(leftAlias, rightAlias)] + return condition(leftAlias, rightAlias) case let .foreignKey(foreignKey): return try foreignKey .joinMapping(db, from: leftAlias.tableName) - .joinExpressions(leftAlias: leftAlias, rightAlias: rightAlias) + .joinExpression(leftAlias: leftAlias, rightAlias: rightAlias) } } } @@ -718,7 +718,7 @@ extension JoinMapping { } } - /// Resolves the condition into SQL expressions which involve both left + /// Resolves the condition into an SQL expression which involve both left /// and right tables. /// /// SELECT * FROM left JOIN right ON (right.a = left.b) @@ -728,10 +728,8 @@ extension JoinMapping { /// JOIN operator. /// - parameter rightAlias: A TableAlias for the table on the right of the /// JOIN operator. - /// - Returns: An array of SQL expression that should be joined with - /// the AND operator and qualified with the right table. - func joinExpressions(leftAlias: TableAlias, rightAlias: TableAlias) -> [SQLExpression] { - map { rightAlias[$0.right] == leftAlias[$0.left] } + func joinExpression(leftAlias: TableAlias, rightAlias: TableAlias) -> SQLExpression { + map { rightAlias[$0.right] == leftAlias[$0.left] }.joined(operator: .and) } } @@ -791,8 +789,12 @@ extension SQLRelation { return nil } - let mergedFiltersPromise = DatabasePromise<[SQLExpression]> { db in - try self.filtersPromise.resolve(db) + other.filtersPromise.resolve(db) + let mergedFilterPromise = DatabasePromise { db in + switch try (self.filterPromise.resolve(db), other.filterPromise.resolve(db)) { + case let (lhs?, rhs?): return lhs && rhs + case let (nil, expr?), let (expr?, nil): return expr + case (nil, nil): return nil + } } var mergedChildren: OrderedDictionary = [:] @@ -827,7 +829,7 @@ extension SQLRelation { return SQLRelation( source: mergedSource, selectionPromise: mergedSelectionPromise, - filtersPromise: mergedFiltersPromise, + filterPromise: mergedFilterPromise, ordering: mergedOrdering, children: mergedChildren) } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 5df7d302a..58f203e82 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -3,7 +3,7 @@ struct SQLQueryGenerator: Refinable { fileprivate private(set) var relation: SQLQualifiedRelation private let isDistinct: Bool private let groupPromise: DatabasePromise<[SQLExpression]>? - private let havingExpressionsPromise: DatabasePromise<[SQLExpression]> + private let havingExpressionPromise: DatabasePromise private let limit: SQLLimit? private let singleResult: Bool private let ctes: OrderedDictionary @@ -49,7 +49,7 @@ struct SQLQueryGenerator: Refinable { groupPromise = query.groupPromise?.map { $0.map { $0.qualified(with: sourceAlias) } } - havingExpressionsPromise = query.havingExpressionsPromise.map { + havingExpressionPromise = query.havingExpressionPromise.map { $0.map { $0.qualified(with: sourceAlias) } } @@ -88,12 +88,10 @@ struct SQLQueryGenerator: Refinable { } } - let filters = try relation.filtersPromise.resolve(context.db) - if filters.isEmpty == false { + let filter = try relation.filterPromise.resolve(context.db) + if let filter = filter { sql += " WHERE " - sql += try filters - .joined(operator: .and) - .sql(context) + sql += try filter.sql(context) } let groupExpressions = try groupPromise?.resolve(context.db) ?? [] @@ -104,12 +102,9 @@ struct SQLQueryGenerator: Refinable { .joined(separator: ", ") } - let havingExpressions = try havingExpressionsPromise.resolve(context.db) - if havingExpressions.isEmpty == false { + if let havingExpression = try havingExpressionPromise.resolve(context.db) { sql += " HAVING " - sql += try havingExpressions - .joined(operator: .and) - .sql(context) + sql += try havingExpression.sql(context) } let orderings = try relation.ordering.resolve(context.db) @@ -124,7 +119,7 @@ struct SQLQueryGenerator: Refinable { if try singleResult && !expectsSingleResult( context.db, selection: selection, - filters: filters, + filter: filter, groupExpressions: groupExpressions) { limit = SQLLimit(limit: 1, offset: limit?.offset) @@ -204,8 +199,9 @@ struct SQLQueryGenerator: Refinable { } // The filter knows better - let filter = try relation.filtersPromise.resolve(db).joined(operator: .and) - guard let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias) else { + guard let filter = try relation.filterPromise.resolve(db), + let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias) + else { return selectedRegion } @@ -219,7 +215,7 @@ struct SQLQueryGenerator: Refinable { private func expectsSingleResult( _ db: Database, selection: [SQLSelection], - filters: [SQLExpression], + filter: SQLExpression?, groupExpressions: [SQLExpression]) throws -> Bool { @@ -230,14 +226,12 @@ struct SQLQueryGenerator: Refinable { // Do we filter on a unique key? let tableName = relation.source.tableName - if try db.tableExists(tableName) { // skip views - let identifyingColums = try filters - .joined(operator: .and) - .identifyingColums(db, for: relation.source.alias) - if try db.table(tableName, hasUniqueKey: identifyingColums) { - // Filter by unique key: guaranteed single row! - return true - } + if try db.tableExists(tableName), // skip views + let identifyingColums = try filter?.identifyingColums(db, for: relation.source.alias), + try db.table(tableName, hasUniqueKey: identifyingColums) + { + // Filter by unique key: guaranteed single row! + return true } // Do we aggregate without grouping? @@ -261,12 +255,9 @@ struct SQLQueryGenerator: Refinable { var sql = try commonTableExpressionsPrefix(context) sql += try "DELETE FROM " + relation.source.sql(context) - let filters = try relation.filtersPromise.resolve(db) - if filters.isEmpty == false { + if let filter = try relation.filterPromise.resolve(db) { sql += " WHERE " - sql += try filters - .joined(operator: .and) - .sql(context) + sql += try filter.sql(context) } if let limit = limit { @@ -350,12 +341,9 @@ struct SQLQueryGenerator: Refinable { .map { try $0.sql(context) } .joined(separator: ", ") - let filters = try relation.filtersPromise.resolve(db) - if filters.isEmpty == false { + if let filter = try relation.filterPromise.resolve(db) { sql += " WHERE " - sql += try filters - .joined(operator: .and) - .sql(context) + sql += try filter.sql(context) } if let limit = limit { @@ -576,8 +564,8 @@ private struct SQLQualifiedRelation { /// /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... /// | - /// • filtersPromise - let filtersPromise: DatabasePromise<[SQLExpression]> + /// • filterPromise + let filterPromise: DatabasePromise /// The ordering of source, not including ordering of joined relations private let sourceOrdering: SQLRelation.Ordering @@ -615,7 +603,7 @@ private struct SQLQualifiedRelation { sourceSelectionPromise = relation.selectionPromise.map { $0.map { $0.qualified(with: sourceAlias) } } - filtersPromise = relation.filtersPromise.map { + filterPromise = relation.filterPromise.map { $0.map { $0.qualified(with: sourceAlias) } } sourceOrdering = relation.ordering.qualified(with: sourceAlias) @@ -780,19 +768,20 @@ private struct SQLQualifiedJoin: Refinable { // JOIN table... var sql = try "\(kind.rawValue) \(relation.source.sql(context))" - // ... ON + // ... ON AND let rightAlias = relation.source.alias - var conditions = try condition.joinExpressions(context.db, - leftAlias: leftAlias, - rightAlias: rightAlias) + var conditions: [SQLExpression] = [] - // ... AND - conditions += try relation.filtersPromise - .resolve(context.db) - .map { $0.qualified(with: rightAlias) } + if let expression = try condition.joinExpression(context.db, + leftAlias: leftAlias, + rightAlias: rightAlias) + { + conditions.append(expression) + } - // Avoid generating on ON clause for trivially true conditions - conditions = conditions.filter { !$0.isTrue } + if let filter = try relation.filterPromise.resolve(context.db) { + conditions.append(filter.qualified(with: rightAlias)) + } if conditions.isEmpty == false { sql += " ON "