From 32a40b18fdfa6daf9cc45c7540ed66d184acbd77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:01:48 +0100 Subject: [PATCH 1/8] Introduce associative binary operators --- .../SQL/SQLExpression+QueryInterface.swift | 157 ++++++++++++------ GRDB/QueryInterface/SQL/SQLOperators.swift | 92 ++++------ .../SQLGeneration/SQLQueryGenerator.swift | 12 +- 3 files changed, 141 insertions(+), 120 deletions(-) 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 { From a398c6dc9913b70f3e3797447162aa625944793c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:17:11 +0100 Subject: [PATCH 2/8] Flattten stricly associative operators --- .../SQL/SQLExpression+QueryInterface.swift | 30 +++++++++++++++---- GRDB/QueryInterface/SQL/SQLOperators.swift | 20 ++++++++++--- .../AssociationTableAliasTestsSQLTests.swift | 6 ++-- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 63511ef77..5d4842d03 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -291,13 +291,21 @@ public struct SQLAssociativeBinaryOperator: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// - /// Creates a binary operator + /// if true, (a • b) • c is strictly equal to a • (b • c). /// - /// SQLAssociativeBinaryOperator("+") - /// SQLAssociativeBinaryOperator("AND") - public init(_ sql: String, neutralValue: DatabaseValue) { + /// `AND`, `OR`, `||` (concat) are stricly associative. + /// + /// + and * are not stricly associative when applied to floating + /// point values. + public let strictlyAssociative: Bool + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Creates a binary operator + public init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool) { self.sql = sql self.neutralValue = neutralValue + self.strictlyAssociative = strictlyAssociative } } @@ -316,7 +324,19 @@ struct SQLExpressionBinaryReduce: SQLExpression { /// SQLExpressionBinaryReduce(.multiply, [Column("length"), Column("width")]) init(_ op: SQLAssociativeBinaryOperator, _ expressions: [SQLExpression]) { self.op = op - self.expressions = expressions + + // flatten when possible: a • (b • c) = a • b • c + if op.strictlyAssociative { + self.expressions = expressions.flatMap { expression -> [SQLExpression] in + if let reduce = expression as? SQLExpressionBinaryReduce, reduce.op == op { + return reduce.expressions + } else { + return [expression] + } + } + } else { + self.expressions = expressions + } } func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index b18ae8bc2..e32b06896 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -567,10 +567,16 @@ extension SQLBinaryOperator { extension SQLAssociativeBinaryOperator { /// The `+` binary operator - public static let add = SQLAssociativeBinaryOperator("+", neutralValue: 0.databaseValue) + public static let add = SQLAssociativeBinaryOperator( + sql: "+", + neutralValue: 0.databaseValue, + strictlyAssociative: false) /// The `*` binary operator - public static let multiply = SQLAssociativeBinaryOperator("*", neutralValue: 1.databaseValue) + public static let multiply = SQLAssociativeBinaryOperator( + sql: "*", + neutralValue: 1.databaseValue, + strictlyAssociative: false) } extension SQLUnaryOperator { @@ -687,10 +693,16 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE extension SQLAssociativeBinaryOperator { /// The `AND` binary operator - public static let and = SQLAssociativeBinaryOperator("AND", neutralValue: true.databaseValue) + public static let and = SQLAssociativeBinaryOperator( + sql: "AND", + neutralValue: true.databaseValue, + strictlyAssociative: true) /// The `OR` binary operator - public static let or = SQLAssociativeBinaryOperator("OR", neutralValue: false.databaseValue) + public static let or = SQLAssociativeBinaryOperator( + sql: "OR", + neutralValue: false.databaseValue, + strictlyAssociative: true) } /// A logical SQL expression with the `AND` SQL operator. diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift index 994ba938c..dc18cf213 100644 --- a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -53,7 +53,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase { let expectedSQL = """ SELECT "name" \ FROM "a" \ - WHERE ("id" = 1) AND (("name" IS NOT NULL) AND ("name" = 'foo')) \ + WHERE ("id" = 1) AND ("name" IS NOT NULL) AND ("name" = 'foo') \ GROUP BY "name" \ HAVING "name" \ ORDER BY "name" @@ -90,7 +90,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase { let expectedSQL = """ SELECT "customA"."name" \ FROM "a" "customA" \ - WHERE ("customA"."id" = 1) AND (("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo')) \ + WHERE ("customA"."id" = 1) AND ("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo') \ GROUP BY "customA"."name" \ HAVING "customA"."name" \ ORDER BY "customA"."name" @@ -307,7 +307,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase { JOIN "a" "a2" ON "a2"."bid2" = "b1"."id" \ JOIN "b" "b2" ON "b2"."id" = "a1"."bid2" \ JOIN "a" "a3" ON "a3"."bid1" = "b2"."id" \ - WHERE (("a1"."name" IS NOT NULL) AND ("a1"."name" > "a3"."name")) AND ("a2"."name" = 'foo') + WHERE ("a1"."name" IS NOT NULL) AND ("a1"."name" > "a3"."name") AND ("a2"."name" = 'foo') """ do { From 01b47a833ac624ab6bebb326ea46d33c4a92a980 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:38:17 +0100 Subject: [PATCH 3/8] Introduce the || string concatenation operator --- GRDB/QueryInterface/SQL/SQLOperators.swift | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index e32b06896..ea8085bd9 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -567,12 +567,22 @@ extension SQLBinaryOperator { extension SQLAssociativeBinaryOperator { /// The `+` binary operator + /// + /// For example: + /// + /// // score + bonus + /// [Column("score"), Column("bonus")].joined(operator: .add) public static let add = SQLAssociativeBinaryOperator( sql: "+", neutralValue: 0.databaseValue, strictlyAssociative: false) /// The `*` binary operator + /// + /// For example: + /// + /// // score * factor + /// [Column("score"), Column("factor")].joined(operator: .multiply) public static let multiply = SQLAssociativeBinaryOperator( sql: "*", neutralValue: 1.databaseValue, @@ -693,12 +703,22 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE extension SQLAssociativeBinaryOperator { /// The `AND` binary operator + /// + /// For example: + /// + /// // isBlue AND isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .and) public static let and = SQLAssociativeBinaryOperator( sql: "AND", neutralValue: true.databaseValue, strictlyAssociative: true) /// The `OR` binary operator + /// + /// For example: + /// + /// // isBlue OR isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .or) public static let or = SQLAssociativeBinaryOperator( sql: "OR", neutralValue: false.databaseValue, @@ -785,6 +805,20 @@ extension SQLSpecificExpressible { } } +// MARK: - Concat Operator + +extension SQLAssociativeBinaryOperator { + /// The `||` string concatenation operator + /// + /// For example: + /// + /// // firstName || ' ' || lastName + /// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat) + public static let concat = SQLAssociativeBinaryOperator( + sql: "||", + neutralValue: "".databaseValue, + strictlyAssociative: true) +} // MARK: - Match Operator From c9373929ca3be43d073f9c4139034da2e3742630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:38:26 +0100 Subject: [PATCH 4/8] Documentation for the || string concatenation operator --- README.md | 15 ++++++++++- .../QueryInterfaceExpressionsTests.swift | 25 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 25db069ea..4054600f6 100644 --- a/README.md +++ b/README.md @@ -4282,7 +4282,20 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Planet.select((temperatureColumn * 1.8 + 32).forKey("farenheit")) ``` - > :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. + > :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. See the `concat` operator below. + +- `||` + + Concatenate several strings: + + ```swift + // SELECT firstName || ' ' || lastName FROM player + Player.select([firstNameColumn, " ".databaseValue, lastNameColumn].joined(operator: .concat)) + ``` + + Note in the example above how you concatenate raw strings: `" ".databaseValue`. A plain `" "` would not compile. + + When the sequence is empty, `joined(operator: .concat)` returns the empty string. - `AND`, `OR`, `NOT` diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 2023a0d78..dd33b276e 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1079,6 +1079,31 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { } + // MARK: - || concat operator + + func testConcatOperator() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.name, Col.name].joined(operator: .concat))), + """ + SELECT "name" || "name" FROM "readers" + """) + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.name, Col.name].joined(operator: .concat) == "foo")), + """ + SELECT * FROM "readers" WHERE ("name" || "name") = 'foo' + """) + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.name, " ".databaseValue, Col.name].joined(operator: .concat))), + """ + SELECT "name" || ' ' || "name" FROM "readers" + """) + } + + // MARK: - Function func testCustomFunction() throws { From 62fad30af5cdb09948c4db0d998e275452d4a454 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:57:07 +0100 Subject: [PATCH 5/8] Documentation associative operator joining for add and multiply operations --- README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4054600f6..d8944f60e 100644 --- a/README.md +++ b/README.md @@ -4283,6 +4283,21 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ``` > :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. See the `concat` operator below. + + When you want to join a sequence of expressions with the `+` or `*` operator, use `joined(operator:)`: + + ```swift + // SELECT score + bonus + 1000 FROM player + let values = [ + scoreColumn, + bonusColumn, + 1000.databaseValue] + Player.select(values.joined(operator: .add)) + ``` + + Note in the example above how you concatenate raw values: `1000.databaseValue`. A plain `1000` would not compile. + + When the sequence is empty, `joined(operator: .add)` returns 0, and `joined(operator: .multiply)` returns 1. - `||` @@ -4306,7 +4321,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Player.filter(!verifiedColumn || scoreColumn < 1000) ``` - When you want to join a sequence of expressions with `AND` or `OR` operators, use `joined(operator:)`: + When you want to join a sequence of expressions with the `AND` or `OR` operator, use `joined(operator:)`: ```swift // SELECT * FROM player WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) From 95ddae7968b7b95265059dbd7ca84c8e1ed7c58f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 09:08:30 +0100 Subject: [PATCH 6/8] More tests for associative operators --- .../QueryInterfaceExpressionsTests.swift | 62 ++++++++++++++++++- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index dd33b276e..e721c2194 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -868,7 +868,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE -((-\"age\") + 1)") } - func testInfixMinusOperator() throws { + func testInfixSubtractOperator() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( @@ -891,7 +891,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE 1 - ((\"age\" > 1) AND (\"age\" IS NULL))") } - func testInfixPlusOperator() throws { + func testInfixAddOperator() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( @@ -914,6 +914,30 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE 1 + ((\"age\" > 1) AND (\"age\" IS NULL))") } + func testJoinedAddOperator() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([].joined(operator: .add))), + "SELECT 0 FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .add))), + "SELECT \"age\" + \"age\" FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .add))), + "SELECT \"age\" + 2 + \"age\" FROM \"readers\"") + + // Not flattened + XCTAssertEqual( + sql(dbQueue, tableRequest.select([ + [Col.age, 1.databaseValue].joined(operator: .add), + [2.databaseValue, Col.age].joined(operator: .add), + ].joined(operator: .add))), + "SELECT (\"age\" + 1) + (2 + \"age\") FROM \"readers\"") + } + func testInfixMultiplyOperator() throws { let dbQueue = try makeDatabaseQueue() @@ -934,6 +958,30 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE 2 * (\"age\" * \"age\")") } + func testJoinedMultiplyOperator() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([].joined(operator: .multiply))), + "SELECT 1 FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .multiply))), + "SELECT \"age\" * \"age\" FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .multiply))), + "SELECT \"age\" * 2 * \"age\" FROM \"readers\"") + + // Not flattened + XCTAssertEqual( + sql(dbQueue, tableRequest.select([ + [Col.age, 1.databaseValue].joined(operator: .multiply), + [2.databaseValue, Col.age].joined(operator: .multiply), + ].joined(operator: .multiply))), + "SELECT (\"age\" * 1) * (2 * \"age\") FROM \"readers\"") + } + func testInfixDivideOperator() throws { let dbQueue = try makeDatabaseQueue() @@ -1101,6 +1149,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { """ SELECT "name" || ' ' || "name" FROM "readers" """) + + // Flattened + XCTAssertEqual( + sql(dbQueue, tableRequest.select([ + [Col.name, "a".databaseValue].joined(operator: .concat), + ["b".databaseValue, Col.name].joined(operator: .concat), + ].joined(operator: .concat))), + """ + SELECT "name" || 'a' || 'b' || "name" FROM "readers" + """) } From 4bfab90750db5af9e2bbd06e4ff75d4c92a6d063 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 18:50:48 +0100 Subject: [PATCH 7/8] Restore and deprecate SQLLogicalBinaryOperator --- GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 5d4842d03..f772d78cb 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -309,6 +309,9 @@ public struct SQLAssociativeBinaryOperator: Hashable { } } +@available(*, deprecated, renamed: "SQLAssociativeBinaryOperator") +typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator + /// SQLExpressionBinary is an expression made of two expressions joined with a /// binary operator. /// From 25cf030498bdedf2e8ba20ea193db592633dc9ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 18:51:47 +0100 Subject: [PATCH 8/8] CHANGELOG --- CHANGELOG.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a48b6cbd..85ee7d253 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 4.x Releases @@ -61,9 +59,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - + +- [#683](https://github.com/groue/GRDB.swift/pull/683): String concatenation ## 4.8.1