diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 814dabf46..63511ef77 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -164,7 +164,7 @@ public struct SQLExpressionUnary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// -/// SQLBinaryOperator is a SQLite binary operator. +/// SQLBinaryOperator is an SQLite binary operator, such as >, =, etc. /// /// :nodoc: public struct SQLBinaryOperator: Hashable { @@ -182,7 +182,7 @@ public struct SQLBinaryOperator: Hashable { /// /// Creates a binary operator /// - /// SQLBinaryOperator("+") + /// SQLBinaryOperator("-") /// SQLBinaryOperator("IS", negated: "IS NOT") public init(_ sql: String, negated: String? = nil) { self.sql = sql @@ -233,7 +233,7 @@ public struct SQLExpressionBinary: SQLExpression { /// binary operator. /// /// // length * width - /// SQLExpressionBinary(.multiply, Column("length"), Column("width")) + /// SQLExpressionBinary(.subtract, Column("score"), Column("malus")) public init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) { self.lhs = lhs.sqlExpression self.op = op @@ -270,87 +270,136 @@ public struct SQLExpressionBinary: SQLExpression { } } -// MARK: - SQLExpressionAnd +// MARK: - SQLExpressionBinaryReduce -struct SQLExpressionAnd: SQLExpression { - let expressions: [SQLExpression] +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// SQLAssociativeBinaryOperator is an SQLite associative binary operator, such +/// as +, *, AND, etc. +/// +/// :nodoc: +public struct SQLAssociativeBinaryOperator: Hashable { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The SQL operator + public let sql: String - init(_ expressions: [SQLExpression]) { - self.expressions = expressions - } + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The neutral value + public let neutralValue: DatabaseValue - func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - guard let first = expressions.first else { - // Ruby [].all? # => true - return true.sqlExpression.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) - } - if expressions.count == 1 { - return first.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) - } - let expressionSQLs = expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: true) } - if wrappedInParenthesis { - return "(\(expressionSQLs.joined(separator: " AND ")))" - } else { - return expressionSQLs.joined(separator: " AND ") - } - } - - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: alias) }) - } - - 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) } + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Creates a binary operator + /// + /// SQLAssociativeBinaryOperator("+") + /// SQLAssociativeBinaryOperator("AND") + public init(_ sql: String, neutralValue: DatabaseValue) { + self.sql = sql + self.neutralValue = neutralValue } } -// MARK: - SQLExpressionOr - -struct SQLExpressionOr: SQLExpression { +/// SQLExpressionBinary is an expression made of two expressions joined with a +/// binary operator. +/// +/// SQLExpressionBinary(.multiply, Column("length"), Column("width")) +struct SQLExpressionBinaryReduce: SQLExpression { let expressions: [SQLExpression] + let op: SQLAssociativeBinaryOperator - init(_ expressions: [SQLExpression]) { + /// Creates an expression made of expressions joined with an associative + /// binary operator. + /// + /// // length * width + /// SQLExpressionBinaryReduce(.multiply, [Column("length"), Column("width")]) + init(_ op: SQLAssociativeBinaryOperator, _ expressions: [SQLExpression]) { + self.op = op self.expressions = expressions } func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { guard let first = expressions.first else { - // Ruby [].any? # => false - return false.sqlExpression.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) + return op.neutralValue.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) } if expressions.count == 1 { return first.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) } let expressionSQLs = expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: true) } + let joiner = " \(op.sql) " if wrappedInParenthesis { - return "(\(expressionSQLs.joined(separator: " OR ")))" + return "(\(expressionSQLs.joined(separator: joiner)))" } else { - return expressionSQLs.joined(separator: " OR ") + return expressionSQLs.joined(separator: joiner) } } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: alias) }) + return SQLExpressionBinaryReduce(op, expressions.map { $0.qualifiedExpression(with: alias) }) } func matchedRowIds(rowIdName: String?) -> Set? { - if expressions.isEmpty { - return [] - } - var result: Set = [] - for expr in expressions { - guard let matchedRowIds = expr.matchedRowIds(rowIdName: rowIdName) else { + switch op { + case .and: + let matchedRowIds = expressions.compactMap { + $0.matchedRowIds(rowIdName: rowIdName) + } + guard let first = matchedRowIds.first else { return nil } - result.formUnion(matchedRowIds) + return matchedRowIds.suffix(from: 1).reduce(into: first) { $0.formIntersection($1) } + case .or: + 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 + default: + return nil } - return result + } +} + +extension Sequence where Element == SQLExpression { + /// Returns an expression by joining all elements with an SQL + /// binary operator. + /// + /// For example: + /// + /// // SELECT * FROM player + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >= 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// + /// When the sequence is empty, `joined(operator:)` returns the neutral + /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, + /// false for `.or`, true for `.and`... + /// and `joined(operator: .or)` returns false: + /// When the sequence is empty, `joined(operator: .and)` returns true, + /// and `joined(operator: .or)` returns false: + /// + /// // SELECT 0 FROM player + /// Player.select([].joined(operator: .add)) + /// + /// // SELECT * FROM player WHERE 1 + /// Player.filter([].joined(operator: .and)) + /// + /// // SELECT * FROM player WHERE 0 + /// Player.filter([].joined(operator: .or)) + public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { + return SQLExpressionBinaryReduce(`operator`, Array(self)) } } diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index ac0ee9c87..b18ae8bc2 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -558,19 +558,21 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { // MARK: - Arithmetic Operators (+, -, *, /) extension SQLBinaryOperator { - /// The `+` binary operator - static let plus = SQLBinaryOperator("+") - /// The `-` binary operator - static let minus = SQLBinaryOperator("-") - - /// The `*` binary operator - static let multiply = SQLBinaryOperator("*") + static let subtract = SQLBinaryOperator("-") /// The `/` binary operator static let divide = SQLBinaryOperator("/") } +extension SQLAssociativeBinaryOperator { + /// The `+` binary operator + public static let add = SQLAssociativeBinaryOperator("+", neutralValue: 0.databaseValue) + + /// The `*` binary operator + public static let multiply = SQLAssociativeBinaryOperator("*", neutralValue: 1.databaseValue) +} + extension SQLUnaryOperator { /// The `-` unary operator static let minus = SQLUnaryOperator("-", needsRightSpace: false) @@ -581,7 +583,7 @@ extension SQLUnaryOperator { /// // width * 2 /// Column("width") * 2 public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.multiply, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -589,7 +591,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 * width /// 2 * Column("width") public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.multiply, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -597,7 +599,7 @@ public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width * height /// Column("width") * Column("height") public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.multiply, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic division. @@ -629,7 +631,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // width + 2 /// Column("width") + 2 public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.plus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -637,7 +639,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 + width /// 2 + Column("width") public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.plus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -645,7 +647,7 @@ public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width + height /// Column("width") + Column("height") public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.plus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated SQL arithmetic expression. @@ -661,7 +663,7 @@ public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { /// // width - 2 /// Column("width") - 2 public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.minus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -669,7 +671,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 - width /// 2 - Column("width") public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.minus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -677,18 +679,26 @@ public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width - height /// Column("width") - Column("height") public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.minus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } // MARK: - Logical Operators (AND, OR, NOT) +extension SQLAssociativeBinaryOperator { + /// The `AND` binary operator + public static let and = SQLAssociativeBinaryOperator("AND", neutralValue: true.databaseValue) + + /// The `OR` binary operator + public static let or = SQLAssociativeBinaryOperator("OR", neutralValue: false.databaseValue) +} + /// A logical SQL expression with the `AND` SQL operator. /// /// // favorite AND 0 /// Column("favorite") && false public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -696,7 +706,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 AND favorite /// false && Column("favorite") public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -704,7 +714,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 SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -712,7 +722,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // favorite OR 1 /// Column("favorite") || true public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -720,7 +730,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 OR favorite /// true || Column("favorite") public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -728,7 +738,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 SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression with the `NOT` SQL operator. @@ -744,44 +754,6 @@ public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { return value.sqlExpression.negated } -public enum SQLLogicalBinaryOperator { - case and, or -} - -extension Sequence where Element == SQLExpression { - /// Returns an expression by joining all elements with an SQL - /// logical operator. - /// - /// For example: - /// - /// // SELECT * FROM player - /// // WHERE (registered - /// // AND (score >= 1000) - /// // AND (name IS NOT NULL)) - /// let conditions = [ - /// Column("registered"), - /// Column("score") >= 1000, - /// Column("name") != nil] - /// Player.filter(conditions.joined(operator: .and)) - /// - /// When the sequence is empty, `joined(operator: .and)` returns true, - /// and `joined(operator: .or)` returns false: - /// - /// // SELECT * FROM player WHERE 1 - /// Player.filter([].joined(operator: .and)) - /// - /// // SELECT * FROM player WHERE 0 - /// Player.filter([].joined(operator: .or)) - 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 extension SQLBinaryOperator { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index cdc09eb11..04ea0b584 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -65,7 +65,7 @@ struct SQLQueryGenerator { let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { sql += " WHERE " - sql += SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) + sql += filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false) } if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { @@ -77,7 +77,7 @@ struct SQLQueryGenerator { if havingExpressions.isEmpty == false { sql += " HAVING " - sql += SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false) + sql += havingExpressions.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false) } let orderings = try relation.ordering.resolve(db) @@ -117,7 +117,7 @@ struct SQLQueryGenerator { // The filters knows better let filters = try relation.filtersPromise.resolve(db) - guard let rowIds = SQLExpressionAnd(filters).matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + guard let rowIds = filters.joined(operator: .and).matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { return databaseRegion } @@ -144,7 +144,7 @@ struct SQLQueryGenerator { let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) + sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false) } if let limit = limit { @@ -238,7 +238,7 @@ struct SQLQueryGenerator { let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) + sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false) } if let limit = limit { @@ -680,7 +680,7 @@ private struct SQLQualifiedJoin { let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias) + relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " ON \(SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false))" + sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))" } for (_, join) in relation.joins {