From bf1d6038e1ddcad7b35e0f7b5626cd528fbc7088 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 13:33:35 +0200 Subject: [PATCH 1/8] Failing tests for #816 --- .../QueryInterfaceExpressionsTests.swift | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 9ea55cc2a..013123b0e 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -463,16 +463,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age == true)), - "SELECT * FROM \"readers\" WHERE \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" = 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true == Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" = 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age == false)), - "SELECT * FROM \"readers\" WHERE NOT \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" = 0") XCTAssertEqual( sql(dbQueue, tableRequest.filter(false == Col.age)), - "SELECT * FROM \"readers\" WHERE NOT \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" = 0") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true == true)), "SELECT * FROM \"readers\" WHERE 1") @@ -615,16 +615,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != true)), - "SELECT * FROM \"readers\" WHERE NOT \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true != Col.age)), - "SELECT * FROM \"readers\" WHERE NOT \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != false)), - "SELECT * FROM \"readers\" WHERE \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") XCTAssertEqual( sql(dbQueue, tableRequest.filter(false != Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true != true)), "SELECT * FROM \"readers\" WHERE 0") From c532b8709c77f542804df6dd2d79243750b6721e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 14:19:31 +0200 Subject: [PATCH 2/8] Refactor boolean tests (fix #816) --- GRDB/Core/DatabaseValue.swift | 40 +++--- .../SQL/SQLExpression+QueryInterface.swift | 124 ++++++++++++------ GRDB/QueryInterface/SQL/SQLExpression.swift | 67 ++++++++-- GRDB/QueryInterface/SQL/SQLOperators.swift | 46 +++---- 4 files changed, 182 insertions(+), 95 deletions(-) diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index d23325b5d..0b47a837b 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -221,30 +221,30 @@ extension DatabaseValue { // SQLExpression extension DatabaseValue { + // Specific boolean checks for null, true, and false /// :nodoc: - public var _negated: SQLExpression { + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch storage { case .null: - // SELECT NOT NULL -- NULL return DatabaseValue.null - case .int64(let int64): - return (int64 == 0).sqlExpression - case .double(let double): - return (double == 0.0).sqlExpression - case .string: - // We can't assume all strings are true, and return false: - // - // SELECT NOT '1' -- 0 (because '1' is turned into the integer 1, which is negated into 0) - // SELECT NOT '0' -- 1 (because '0' is turned into the integer 0, which is negated into 1) - return _SQLExpressionNot(self) - case .blob: - // We can't assume all blobs are true, and return false: - // - // SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', - // then into integer 1, which is negated into 0) - // SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', - // then into integer 0, which is negated into 1) - return _SQLExpressionNot(self) + + case .int64(let int64) where int64 == 0 || int64 == 1: + switch test { + case .true: + return (int64 == 1).sqlExpression + case .false, .falsey: + return (int64 == 0).sqlExpression + } + + default: + switch test { + case .true: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + case .falsey: + return _SQLExpressionNot(self) + } } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index bc6aad488..df9f4582a 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -12,18 +12,6 @@ extension SQLExpression { // MARK: - _SQLExpressionNot -extension SQLExpression { - /// The default implementation returns the expression prefixed by `NOT`. - /// - /// let column = Column("favorite") - /// column.negated // NOT favorite - /// - /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionNot(self) - } -} - /// :nodoc: public struct _SQLExpressionNot: SQLExpression { let expression: SQLExpression @@ -32,6 +20,22 @@ public struct _SQLExpressionNot: SQLExpression { self.expression = expression } + /// :nodoc: + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + + case .false: + // `(NOT expression) == 0` is equivalent to `expression` + return expression + + case .falsey: + // Support `NOT (NOT expression)` as a technique to build 0 or 1 + return _SQLExpressionNot(self) + } + } + /// :nodoc: public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { _SQLExpressionNot(expression._qualifiedExpression(with: alias)) @@ -99,13 +103,17 @@ struct SQLBinaryOperator: Hashable { /// The SQL for the negated operator, if any let negatedSQL: String? + /// Does the operator output a boolean value? + let isBoolean: Bool + /// Creates a binary operator /// - /// SQLBinaryOperator("-") - /// SQLBinaryOperator("IS", negated: "IS NOT") - init(_ sql: String, negated: String? = nil) { + /// SQLBinaryOperator("-", isBoolean: false) + /// SQLBinaryOperator("LIKE", negated: "NOT LIKE", isBoolean: true) + init(_ sql: String, negated: String? = nil, isBoolean: Bool) { self.sql = sql self.negatedSQL = negated + self.isBoolean = isBoolean } /// Returns the negated binary operator, if any @@ -116,32 +124,32 @@ struct SQLBinaryOperator: Hashable { guard let negatedSQL = negatedSQL else { return nil } - return SQLBinaryOperator(negatedSQL, negated: sql) + return SQLBinaryOperator(negatedSQL, negated: sql, isBoolean: isBoolean) } /// The `<` binary operator - static let lessThan = SQLBinaryOperator("<") + static let lessThan = SQLBinaryOperator("<", isBoolean: true) /// The `<=` binary operator - static let lessThanOrEqual = SQLBinaryOperator("<=") + static let lessThanOrEqual = SQLBinaryOperator("<=", isBoolean: true) /// The `>` binary operator - static let greaterThan = SQLBinaryOperator(">") + static let greaterThan = SQLBinaryOperator(">", isBoolean: true) /// The `>=` binary operator - static let greaterThanOrEqual = SQLBinaryOperator(">=") + static let greaterThanOrEqual = SQLBinaryOperator(">=", isBoolean: true) /// The `-` binary operator - static let subtract = SQLBinaryOperator("-") + static let subtract = SQLBinaryOperator("-", isBoolean: false) /// The `/` binary operator - static let divide = SQLBinaryOperator("/") + static let divide = SQLBinaryOperator("/", isBoolean: false) /// The `LIKE` binary operator - static let like = SQLBinaryOperator("LIKE") + static let like = SQLBinaryOperator("LIKE", negated: "NOT LIKE", isBoolean: true) /// The `MATCH` binary operator - static let match = SQLBinaryOperator("MATCH") + static let match = SQLBinaryOperator("MATCH", isBoolean: true) } /// _SQLExpressionBinary is an expression made of two expressions joined with a @@ -167,11 +175,28 @@ public struct _SQLExpressionBinary: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - if let negatedOp = op.negated { - return _SQLExpressionBinary(negatedOp, lhs, rhs) - } else { - return _SQLExpressionNot(self) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + if op.isBoolean { + return self + } else { + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + } + case .false: + if let negatedOp = op.negated { + return _SQLExpressionBinary(negatedOp, lhs, rhs) + } else if op.isBoolean { + return _SQLExpressionNot(self) + } else { + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + } + case .falsey: + if let negatedOp = op.negated { + return _SQLExpressionBinary(negatedOp, lhs, rhs) + } else { + return _SQLExpressionNot(self) + } } } @@ -380,8 +405,13 @@ public struct _SQLExpressionEqual: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionEqual(op.negated, lhs, rhs) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + case .false, .falsey: + return _SQLExpressionEqual(op.negated, lhs, rhs) + } } /// :nodoc: @@ -416,8 +446,13 @@ public struct _SQLExpressionContains: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionContains(expression, collection, negated: !isNegated) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + case .false, .falsey: + return _SQLExpressionContains(expression, collection, negated: !isNegated) + } } /// :nodoc: @@ -457,8 +492,13 @@ public struct _SQLExpressionBetween: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + case .false, .falsey: + return _SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) + } } /// :nodoc: @@ -574,8 +614,13 @@ public struct _SQLExpressionIsEmpty: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + case .false, .falsey: + return _SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) + } } /// :nodoc: @@ -626,6 +671,11 @@ public struct _SQLExpressionCollate: SQLExpression { self.collationName = collationName } + /// :nodoc: + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + _SQLExpressionCollate(expression._is(test), collationName: collationName) + } + /// :nodoc: public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { _SQLExpressionCollate(expression._qualifiedExpression(with: alias), collationName: collationName) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 41a7540a0..b46110a4a 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -4,19 +4,34 @@ /// /// :nodoc: public protocol _SQLExpression { - /// Returns the expression, negated. This property fuels the `!` operator. + /// Performs a boolean test. /// - /// The default implementation returns the expression prefixed by `NOT`. + /// We generally distinguish four boolean values: /// - /// let column = Column("favorite") - /// column.negated // NOT favorite + /// 1. truthy: `filter(expression)` + /// 2. falsey: `filter(!expression)` + /// 3. true: `filter(expression == true)` + /// 4. false: `filter(expression == false)` /// - /// Some expressions may provide a custom implementation that returns a - /// more natural SQL expression. + /// They generally produce the following SQL: /// - /// let expression = [1,2,3].contains(Column("id")) // id IN (1,2,3) - /// expression.negated // id NOT IN (1,2,3) - var _negated: SQLExpression { get } + /// 1. truthy: `WHERE expression` + /// 2. falsey: `WHERE NOT expression` + /// 3. true: `WHERE expression = 1` + /// 4. false: `WHERE expression = 0` + /// + /// The "true" and "false" tests allow the SQLite query planner to + /// optimize indexed boolean columns. This is why it is important that the + /// user can explicitly use them. See https://github.com/groue/GRDB.swift/issues/816 + /// + /// This method is a customization point, so that some specific expressions + /// can produce idiomatic SQL. For example: + /// + /// - `column.like(pattern` -> `column LIKE pattern` + /// - `!(column.like(pattern)` -> `column NOT LIKE pattern` + /// - `(column.like(pattern) == true` -> `column LIKE pattern` + /// - `(column.like(pattern) == false` -> `column NOT LIKE pattern` + func _is(_ test: _SQLBooleanTest) -> SQLExpression /// Returns a qualified expression func _qualifiedExpression(with alias: TableAlias) -> SQLExpression @@ -29,6 +44,40 @@ public protocol _SQLExpression { /// described at https://www.sqlite.org/lang_expr.html public protocol SQLExpression: _SQLExpression, SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { } +/// `_SQLBooleanTest` supports boolean tests. +/// +/// See `SQLExpression._is(_:)` +/// +/// :nodoc: +public enum _SQLBooleanTest { + /// Fuels `expression == true` + case `true` + + /// Fuels `expression == false` + case `false` + + /// Fuels `!expression` + case falsey +} + +extension SQLExpression { + /// The default implementation of boolean tests. + /// + /// :nodoc: + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + + case .falsey: + return _SQLExpressionNot(self) + } + } +} + extension SQLExpression { /// :nodoc: public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index d6dbda147..475deee30 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -59,9 +59,9 @@ public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpressi /// Column("validated") == false public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { if rhs { - return lhs.sqlExpression + return lhs.sqlExpression._is(.true) } else { - return lhs.sqlExpression._negated + return lhs.sqlExpression._is(.false) } } @@ -102,9 +102,9 @@ public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpressi /// false == Column("validated") public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { if lhs { - return rhs.sqlExpression + return rhs.sqlExpression._is(.true) } else { - return rhs.sqlExpression._negated + return rhs.sqlExpression._is(.false) } } @@ -126,7 +126,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // name IS NOT NULL /// Column("name") != nil public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)._negated + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -139,7 +139,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// // name IS NOT NULL /// Column("name").collating(.nocase) != nil public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - _SQLExpressionCollate(lhs.expression != rhs, collationName: lhs.collationName) + !(lhs == rhs) } /// An SQL expression that checks the boolean value of an expression. @@ -152,11 +152,7 @@ public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpressi /// // validated /// Column("validated") != false public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { - if rhs { - return lhs.sqlExpression._negated - } else { - return lhs.sqlExpression - } + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -169,7 +165,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// // name IS NOT NULL /// nil != Column("name") public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { - isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression)._negated + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -182,7 +178,7 @@ public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// // name IS NOT NULL /// nil != Column("name").collating(.nocase) public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs != rhs.expression, collationName: rhs.collationName) + !(lhs == rhs) } /// An SQL expression that checks the boolean value of an expression. @@ -195,11 +191,7 @@ public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpressi /// // validated /// false != Column("validated") public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { - if lhs { - return rhs.sqlExpression._negated - } else { - return rhs.sqlExpression - } + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -207,7 +199,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { /// // email <> login /// Column("email") != Column("login") public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - isEqual(lhs.sqlExpression, rhs.sqlExpression)._negated + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -259,7 +251,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// // name IS NOT 'Arthur' /// Column("name") !== "Arthur" public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - _SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + !(lhs === rhs) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -267,7 +259,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// // name IS NOT 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) !== "Arthur" public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - _SQLExpressionCollate(lhs.expression !== rhs, collationName: lhs.collationName) + !(lhs === rhs) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -275,11 +267,7 @@ public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress /// // name IS NOT 'Arthur' /// "Arthur" !== Column("name") public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { - if let lhs = lhs { - return _SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) - } else { - return _SQLExpressionEqual(.isNot, rhs.sqlExpression, DatabaseValue.null) - } + !(lhs === rhs) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -287,7 +275,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// // name IS NOT 'Arthur' COLLATE NOCASE /// "Arthur" !== Column("name").collating(.nocase) public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs !== rhs.expression, collationName: rhs.collationName) + !(lhs === rhs) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -295,7 +283,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS NOT login /// Column("email") !== Column("login") public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) + !(lhs === rhs) } // MARK: - Comparison Operators (<, >, <=, >=) @@ -726,7 +714,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // id NOT BETWEEN 1 AND 10 /// !((1...10).contains(Column("id"))) public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { - value.sqlExpression._negated + value.sqlExpression._is(.falsey) } // MARK: - Like Operator From 454b9d5546b8c02266b269f3579d56ab3dd64396 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 14:19:46 +0200 Subject: [PATCH 3/8] More tests for boolean tests --- .../QueryInterfaceExpressionsTests.swift | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 013123b0e..10ccc1c35 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -584,6 +584,25 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.filter(Col.age != Col.age)), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == 10))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == (10 as Int?)))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(10 == Col.age))), + "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!((10 as Int?) == Col.age))), + "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(10 == 10))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != nil)), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") @@ -600,6 +619,22 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.filter(Col.age != Col.age)), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == nil))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == DatabaseValue.null))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(nil == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(DatabaseValue.null == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name != "B")), "SELECT * FROM \"readers\" WHERE \"name\" <> 'B'") @@ -613,6 +648,19 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.filter(Col.name != Col.name)), "SELECT * FROM \"readers\" WHERE \"name\" <> \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.name == "B"))), + "SELECT * FROM \"readers\" WHERE \"name\" <> 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!("B" == Col.name))), + "SELECT * FROM \"readers\" WHERE 'B' <> \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!("B" == "B"))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.name == Col.name))), + "SELECT * FROM \"readers\" WHERE \"name\" <> \"name\"") + XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != true)), "SELECT * FROM \"readers\" WHERE \"age\" <> 1") @@ -634,6 +682,28 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(true != false)), "SELECT * FROM \"readers\" WHERE 1") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == true))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(true == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == false))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(false == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(true == true))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(false == false))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(true == false))), + "SELECT * FROM \"readers\" WHERE 1") } func testNotEqualWithCollation() throws { @@ -1217,6 +1287,18 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.like("%foo"))), "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!Col.name.like("%foo"))), + "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == true)), + "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == false)), + "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo'") } From 843624044cb2e2b45170af2aed000988b753ad2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 15:08:21 +0200 Subject: [PATCH 4/8] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0799e3e53..9412bf1cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,6 +71,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release - **New**: DatabasePool readers don't invalidate their database schema cache until schema is actually changed. +- **Breaking Change**: [#817](https://github.com/groue/GRDB.swift/pull/817): Allow query planner to optimize some boolean tests + ## 5.0.0-beta.9 From 474c2c3a766cbd096b10f70e01def520aacd09d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 15:09:43 +0200 Subject: [PATCH 5/8] Thank you notice --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 993952f97..10279bbbe 100644 --- a/README.md +++ b/README.md @@ -7822,7 +7822,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. +- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@mallman](https://github.com/mallman), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. From 8cc82ae2b7d10003b60081bd3193a4734cb2ddc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 15:16:19 +0200 Subject: [PATCH 6/8] Update migration guide --- Documentation/GRDB5MigrationGuide.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 5825ba706..563c2a281 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -461,6 +461,26 @@ let publisher = observation 13. Many types and methods that support the query builder used to be publicly exposed and flagged as experimental. They are now private, or renamed with an underscore prefix, which means they are not for public use. +14. Explicit boolean tests `expression == true` and `expression == false` generate different SQL: + + ```swift + // GRDB 4: SELECT * FROM player WHERE isActive + // GRDB 5: SELECT * FROM player WHERE isActive = 1 + Player.filter(Column("isActive") == true) + + // GRDB 4: SELECT * FROM player WHERE NOT isActive + // GRDB 5: SELECT * FROM player WHERE isActive = 0 + Player.filter(Column("isActive") == false) + + // GRDB 4 & 5: SELECT * FROM player WHERE isActive + Player.filter(Column("isActive")) + + // GRDB 4 & 5: SELECT * FROM player WHERE NOT isActive + Player.filter(!Column("isActive")) + ``` + + This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values. + [ValueObservation]: ../README.md#valueobservation [DatabaseRegionObservation]: ../README.md#databaseregionobservation From 6ee7db48c8a0bbaa4988d4cb7fd8ac3673db3dca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 16:04:02 +0200 Subject: [PATCH 7/8] Take care of indexes on expressions as well sqlite> create table t(a,b); sqlite> create index i on t(a like '%a', a, b); sqlite> explain query plan select * from t where a like '%a'; QUERY PLAN `--SCAN TABLE t sqlite> explain query plan select * from t where a not like '%a'; QUERY PLAN `--SCAN TABLE t sqlite> explain query plan select * from t where (a like '%a') = 1; QUERY PLAN `--SEARCH TABLE t USING COVERING INDEX i (=?) sqlite> explain query plan select * from t where (a like '%a') = 0; QUERY PLAN `--SEARCH TABLE t USING COVERING INDEX i (=?) --- .../SQL/SQLExpression+QueryInterface.swift | 75 +++++++++---------- .../QueryInterfaceExpressionsTests.swift | 4 +- 2 files changed, 39 insertions(+), 40 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index df9f4582a..61be23e42 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -24,12 +24,11 @@ public struct _SQLExpressionNot: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return self + return _SQLExpressionEqual(.equal, self, true.sqlExpression) case .false: - // `(NOT expression) == 0` is equivalent to `expression` - return expression - + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + case .falsey: // Support `NOT (NOT expression)` as a technique to build 0 or 1 return _SQLExpressionNot(self) @@ -103,17 +102,13 @@ struct SQLBinaryOperator: Hashable { /// The SQL for the negated operator, if any let negatedSQL: String? - /// Does the operator output a boolean value? - let isBoolean: Bool - /// Creates a binary operator /// - /// SQLBinaryOperator("-", isBoolean: false) - /// SQLBinaryOperator("LIKE", negated: "NOT LIKE", isBoolean: true) - init(_ sql: String, negated: String? = nil, isBoolean: Bool) { + /// SQLBinaryOperator("-") + /// SQLBinaryOperator("LIKE", negated: "NOT LIKE") + init(_ sql: String, negated: String? = nil) { self.sql = sql self.negatedSQL = negated - self.isBoolean = isBoolean } /// Returns the negated binary operator, if any @@ -124,32 +119,32 @@ struct SQLBinaryOperator: Hashable { guard let negatedSQL = negatedSQL else { return nil } - return SQLBinaryOperator(negatedSQL, negated: sql, isBoolean: isBoolean) + return SQLBinaryOperator(negatedSQL, negated: sql) } /// The `<` binary operator - static let lessThan = SQLBinaryOperator("<", isBoolean: true) + static let lessThan = SQLBinaryOperator("<") /// The `<=` binary operator - static let lessThanOrEqual = SQLBinaryOperator("<=", isBoolean: true) + static let lessThanOrEqual = SQLBinaryOperator("<=") /// The `>` binary operator - static let greaterThan = SQLBinaryOperator(">", isBoolean: true) + static let greaterThan = SQLBinaryOperator(">") /// The `>=` binary operator - static let greaterThanOrEqual = SQLBinaryOperator(">=", isBoolean: true) + static let greaterThanOrEqual = SQLBinaryOperator(">=") /// The `-` binary operator - static let subtract = SQLBinaryOperator("-", isBoolean: false) + static let subtract = SQLBinaryOperator("-") /// The `/` binary operator - static let divide = SQLBinaryOperator("/", isBoolean: false) + static let divide = SQLBinaryOperator("/") /// The `LIKE` binary operator - static let like = SQLBinaryOperator("LIKE", negated: "NOT LIKE", isBoolean: true) + static let like = SQLBinaryOperator("LIKE", negated: "NOT LIKE") /// The `MATCH` binary operator - static let match = SQLBinaryOperator("MATCH", isBoolean: true) + static let match = SQLBinaryOperator("MATCH") } /// _SQLExpressionBinary is an expression made of two expressions joined with a @@ -178,19 +173,11 @@ public struct _SQLExpressionBinary: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - if op.isBoolean { - return self - } else { - return _SQLExpressionEqual(.equal, self, true.sqlExpression) - } + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + case .false: - if let negatedOp = op.negated { - return _SQLExpressionBinary(negatedOp, lhs, rhs) - } else if op.isBoolean { - return _SQLExpressionNot(self) - } else { - return _SQLExpressionEqual(.equal, self, false.sqlExpression) - } + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + case .falsey: if let negatedOp = op.negated { return _SQLExpressionBinary(negatedOp, lhs, rhs) @@ -408,8 +395,12 @@ public struct _SQLExpressionEqual: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return self - case .false, .falsey: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + + case .falsey: return _SQLExpressionEqual(op.negated, lhs, rhs) } } @@ -449,8 +440,12 @@ public struct _SQLExpressionContains: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return self - case .false, .falsey: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + + case .falsey: return _SQLExpressionContains(expression, collection, negated: !isNegated) } } @@ -495,8 +490,12 @@ public struct _SQLExpressionBetween: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return self - case .false, .falsey: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + + case .falsey: return _SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } } diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 10ccc1c35..e4e56d594 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1294,11 +1294,11 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == true)), - "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo'") + "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo') = 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == false)), - "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo'") + "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo') = 0") } From 9529939262d713027bce810d83a89fa45ee6385b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 27 Jul 2020 06:40:18 +0200 Subject: [PATCH 8/8] Documentation --- GRDB/QueryInterface/SQL/SQLExpression.swift | 25 ++++++++++++++------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b46110a4a..c89490b20 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -20,17 +20,26 @@ public protocol _SQLExpression { /// 3. true: `WHERE expression = 1` /// 4. false: `WHERE expression = 0` /// - /// The "true" and "false" tests allow the SQLite query planner to - /// optimize indexed boolean columns. This is why it is important that the - /// user can explicitly use them. See https://github.com/groue/GRDB.swift/issues/816 + /// The `= 1` and `= 0` tests allow the SQLite query planner to + /// optimize queries with indices on boolean columns and expressions. + /// See https://github.com/groue/GRDB.swift/issues/816 /// /// This method is a customization point, so that some specific expressions - /// can produce idiomatic SQL. For example: + /// can produce idiomatic SQL. /// - /// - `column.like(pattern` -> `column LIKE pattern` - /// - `!(column.like(pattern)` -> `column NOT LIKE pattern` - /// - `(column.like(pattern) == true` -> `column LIKE pattern` - /// - `(column.like(pattern) == false` -> `column NOT LIKE pattern` + /// For example, the `like(_)` expression: + /// + /// - `column.like(pattern)` -> `column LIKE pattern` + /// - `!(column.like(pattern))` -> `column NOT LIKE pattern` + /// - `column.like(pattern) == true` -> `(column LIKE pattern) = 1` + /// - `column.like(pattern) == false` -> `(column LIKE pattern) = 0` + /// + /// Another example, the `isEmpty` association aggregate: + /// + /// - `association.isEmpty` -> `COUNT(child.id) = 0` + /// - `!association.isEmpty` -> `COUNT(child.id) > 0` + /// - `association.isEmpty == true` -> `COUNT(child.id) = 0` + /// - `association.isEmpty == false` -> `COUNT(child.id) > 0` func _is(_ test: _SQLBooleanTest) -> SQLExpression /// Returns a qualified expression