diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index f04147f6c..833a2b7f5 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -259,9 +259,6 @@ extension QueryInterfaceRequest where T: TableRecord { return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in let keyPredicates: [SQLExpression] = try keys.map { key in - // Prevent filter(db, keys: [[:]]) - GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary") - // Prevent filter(keys: [["foo": 1, "bar": 2]]) where // ("foo", "bar") is not a unique key (primary key or columns of a // unique index) @@ -274,10 +271,10 @@ extension QueryInterfaceRequest where T: TableRecord { // Sort key columns in the same order as the unique index .sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! } .map { (column, value) in Column(column) == value } - return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty + return columnPredicates.joined(operator: .and) } - let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keyPredicates is not empty + let keysPredicate = keyPredicates.joined(operator: .or) if let expression = expression { return expression && keysPredicate diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index ee48475f6..35d993cc3 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -227,20 +227,6 @@ public struct SQLBinaryOperator : Hashable { public static func == (lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool { return lhs.sql == rhs.sql } - - // TODO: make it an extension of Sequence (like joined(separator:)) when Swift can better handle existentials - // TODO: make it public eventually - /// Return nil if expressions is empty. - func join(_ expressions: [SQLExpression]) -> SQLExpression? { - switch expressions.count { - case 0: - return nil - case 1: - return expressions[0] - default: - return SQLExpressionBinaryOperatorChain(op: self, expressions: expressions) - } - } } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -325,23 +311,6 @@ public struct SQLExpressionBinary : SQLExpression { return nil } - case .and: - let lids = lhs.matchedRowIds(rowIdName: rowIdName) - let rids = rhs.matchedRowIds(rowIdName: rowIdName) - switch (lids, rids) { - case (nil, nil): return nil - case let (ids?, nil), let (nil, ids?): return ids - case let (lids?, rids?): return lids.intersection(rids) - } - - case .or: - let lids = lhs.matchedRowIds(rowIdName: rowIdName) - let rids = rhs.matchedRowIds(rowIdName: rowIdName) - switch (lids, rids) { - case let (lids?, rids?): return lids.union(rids) - default: return nil - } - default: return nil } @@ -354,29 +323,79 @@ public struct SQLExpressionBinary : SQLExpression { } } -// MARK: - SQLExpressionBinaryOperatorChain +// MARK: - SQLExpressionAnd -struct SQLExpressionBinaryOperatorChain : SQLExpression { - let op: SQLBinaryOperator +struct SQLExpressionAnd : SQLExpression { let expressions: [SQLExpression] - // Exposed to SQLBinaryOperator.join - fileprivate init(op: SQLBinaryOperator, expressions: [SQLExpression]) { - assert(expressions.count >= 2) - self.op = op + init(_ expressions: [SQLExpression]) { self.expressions = expressions } func expressionSQL(_ arguments: inout StatementArguments?) -> String { + guard let expression = expressions.first else { + // Ruby [].all? # => true + return true.sqlExpression.expressionSQL(&arguments) + } + if expressions.count == 1 { + return expression.expressionSQL(&arguments) + } let expressionSQLs = expressions.map { $0.expressionSQL(&arguments) } - let joiner = " \(op.sql) " - return "(" + expressionSQLs.joined(separator: joiner) + ")" + return "(" + expressionSQLs.joined(separator: " AND ") + ")" } func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionBinaryOperatorChain( - op: op, - expressions: expressions.map { $0.qualifiedExpression(with: qualifier) }) + return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: qualifier) }) + } + + func matchedRowIds(rowIdName: String?) -> Set? { + let matchedRowIds = expressions.compactMap { + $0.matchedRowIds(rowIdName: rowIdName) + } + guard let first = matchedRowIds.first else { + return nil + } + return matchedRowIds.suffix(from: 1).reduce(into: first) { $0.formIntersection($1) } + } +} + +// MARK: - SQLExpressionOr + +struct SQLExpressionOr : SQLExpression { + let expressions: [SQLExpression] + + init(_ expressions: [SQLExpression]) { + self.expressions = expressions + } + + func expressionSQL(_ arguments: inout StatementArguments?) -> String { + guard let expression = expressions.first else { + // Ruby [].any? # => false + return false.sqlExpression.expressionSQL(&arguments) + } + if expressions.count == 1 { + return expression.expressionSQL(&arguments) + } + let expressionSQLs = expressions.map { $0.expressionSQL(&arguments) } + return "(" + expressionSQLs.joined(separator: " OR ") + ")" + } + + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: qualifier) }) + } + + func matchedRowIds(rowIdName: String?) -> Set? { + if expressions.isEmpty { + return [] + } + var result: Set = [] + for expr in expressions { + guard let matchedRowIds = expr.matchedRowIds(rowIdName: rowIdName) else { + return nil + } + result.formUnion(matchedRowIds) + } + return result } } diff --git a/GRDB/QueryInterface/Support/SQLOperators.swift b/GRDB/QueryInterface/Support/SQLOperators.swift index 4dde080e2..b7734489d 100644 --- a/GRDB/QueryInterface/Support/SQLOperators.swift +++ b/GRDB/QueryInterface/Support/SQLOperators.swift @@ -697,20 +697,12 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE // MARK: - Logical Operators (AND, OR, NOT) -extension SQLBinaryOperator { - /// The `AND` binary operator - static let and = SQLBinaryOperator("AND") - - /// The `OR` binary operator - static let or = SQLBinaryOperator("OR") -} - /// A logical SQL expression with the `AND` SQL operator. /// /// // favorite AND 0 /// Column("favorite") && false public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -718,7 +710,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 AND favorite /// false && Column("favorite") public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -726,7 +718,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NOT NULL AND favorite /// Column("email") != nil && Column("favorite") public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -734,7 +726,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // favorite OR 1 /// Column("favorite") || true public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -742,7 +734,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 OR favorite /// true || Column("favorite") public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -750,7 +742,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NULL OR hidden /// Column("email") == nil || Column("hidden") public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression with the `NOT` SQL operator. @@ -766,6 +758,34 @@ public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { return value.sqlExpression.negated } +public enum SQLLogicalBinaryOperator { + case and, or +} + +extension Sequence where Element: SQLExpressible { + /// Return an expression by joining all elements with an SQL logical + /// operator + public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { + let expressions: [SQLExpression] = map { $0.sqlExpression } + switch `operator` { + case .and: return SQLExpressionAnd(expressions) + case .or: return SQLExpressionOr(expressions) + } + } +} + +extension Sequence where Element == SQLExpression { + /// Return an expression by joining all elements with an SQL logical + /// operator + public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { + let expressions = Array(self) + switch `operator` { + case .and: return SQLExpressionAnd(expressions) + case .or: return SQLExpressionOr(expressions) + } + } +} + // MARK: - Like Operator