From 9d5cb15380f4d08fb00eb00c9b67aead053a08ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 3 Mar 2021 20:03:56 +0100 Subject: [PATCH] SQLExpression documentation & cleanup --- GRDB/Fixit/GRDB-5.0.swift | 4 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 815 +++++++++++--------- 2 files changed, 455 insertions(+), 364 deletions(-) diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index a24fddeb6..bae59bcf2 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -226,8 +226,8 @@ extension SQLLiteral { public var arguments: StatementArguments { preconditionFailure() } } -@available(*, unavailable, renamed: "SQLAssociativeBinaryOperator") -typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator +@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator") +typealias SQLLogicalBinaryOperator = SQLExpression.AssociativeBinaryOperator extension SQLRequest { @available(*, unavailable, renamed: "RowDecoder") diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 7dcf92b75..582181cde 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -3,20 +3,27 @@ public struct SQLExpression { private var impl: Impl + /// The private implementation of the public `SQLExpression`. private enum Impl { - // MARK: Basic Expressions - - /// An unqualified database column. + /// A column. /// - /// "score" is a valid unqualified name. "player.score" is not. + /// id + /// name case column(String) - /// A qualified column in the database, as in + /// A qualified column. /// - /// SELECT player.score FROM player + /// player.id + /// player.name case qualifiedColumn(String, TableAlias) - /// A database value + /// A database value. + /// + /// NULL + /// 42 + /// 'Alice' + /// 3.14 + /// case databaseValue(DatabaseValue) /// A [row value](https://www.sqlite.org/rowvalue.html). @@ -30,130 +37,362 @@ public struct SQLExpression { /// A literal SQL expression case literal(SQLLiteral) - // MARK: Operators - - /// An expression that checks if a values is included in a range with the - /// `BETWEEN` operator. + /// The `BETWEEN` and `NOT BETWEEN` operators. /// - /// id BETWEEN 1 AND 3 + /// BETWEEN AND indirect case between( expression: SQLExpression, lowerBound: SQLExpression, upperBound: SQLExpression, isNegated: Bool) - /// An expression made of two expressions joined with a - /// binary operator. + /// A binary operator. /// - /// length * width - /// score >= 1000 - indirect case binary(SQLBinaryOperator, SQLExpression, SQLExpression) + /// * + /// <= + /// LIKE + indirect case binary(BinaryOperator, SQLExpression, SQLExpression) - /// An expression made of several expressions joined with an associative - /// binary operator. + /// An associative binary operator. /// - /// a AND b AND c - /// score + bonus + /// AND + /// + + /// /// - precondition: expressions.count > 1 - case associativeBinary(SQLAssociativeBinaryOperator, [SQLExpression]) + case associativeBinary(AssociativeBinaryOperator, [SQLExpression]) - /// An expression that checks the inclusion of a value in a collection - /// with the `IN` operator. + /// The `IN` and `NOT IN` operators. /// - /// id IN (1,2,3) - /// score IN (SELECT ...) + /// IN + /// NOT IN indirect case `in`(SQLExpression, SQLCollection, isNegated: Bool) - /// An expression made of an unary operator and an operand expression. + /// An unary operator. /// - /// -score - indirect case unary(SQLUnaryOperator, SQLExpression) + /// - + indirect case unary(UnaryOperator, SQLExpression) - /// An equality comparison + /// An equality comparison. /// - /// a = b - /// a <> b - /// a IS b - /// a IS NOT b - indirect case compare(SQLCompareOperator, SQLExpression, SQLExpression) + /// = + /// <> + /// IS + /// IS NOT + indirect case compare(EqualityOperator, SQLExpression, SQLExpression) - /// A full-text table match + /// A table full-text match. /// - /// SELECT * FROM document WHERE document MATCH 'query' + /// MATCH indirect case tableMatch(TableAlias, SQLExpression) - /// The logical not + /// A logical `NOT` operator. /// - /// NOT selected + /// NOT indirect case not(SQLExpression) - // MARK: Collations - - /// An expression tainted by an SQLite collation. + /// A collated expression. /// - /// SELECT * FROM player WHERE email = 'arthur@example.com' COLLATE NOCASE + /// COLLATE indirect case collated(SQLExpression, Database.CollationName) - // MARK: Functions - - /// A call to the SQL `COUNT(...)` function. + /// The `COUNT` function. /// - /// SELECT COUNT(name) FROM player - /// SELECT COUNT(*) FROM player + /// COUNT(*) + /// COUNT() indirect case count(SQLSelection) - /// A call to the SQL `COUNT(DISTINCT ...)` function. + /// The `COUNT(DISTINCT)` function. /// - /// SELECT COUNT(DISTINCT name) FROM player + /// COUNT(DISTINCT ) indirect case countDistinct(SQLExpression) - /// A function call + /// A function call. /// - /// LENGTH(name) + /// (, ...) case function(String, [SQLExpression]) - /// This expression helps generating `COUNT(...) = 0` or - /// `COUNT(...) > 0`. + /// An expression that checks for zero or positive values. /// - /// It has a specific behavior when negated with the `!` logical - /// operator, or compared with booleans. - /// - /// WHERE COUNT(DISTINCT player.id) == 0 - /// WHERE COUNT(DISTINCT player.id) > 0 + /// = 0 + /// > 0 indirect case isEmpty(SQLExpression, isNegated: Bool) - // MARK: Deferred - /// An expression that picks the fastest available primary key. /// /// It crashes for WITHOUT ROWID table with a multi-columns primary key. /// Future versions of GRDB may use [row values](https://www.sqlite.org/rowvalue.html). + /// + /// id + /// rowid + /// code case fastPrimaryKey - /// Qualified version of `.fastPrimaryKey` + /// A qualified "fast primary key" (see `.fastPrimaryKey`). + /// + /// player.id + /// document.rowid + /// country.code case qualifiedFastPrimaryKey(TableAlias) } + /// `BooleanTest` supports truthiness tests. + /// + /// See `SQLExpression.is(_:)` + enum BooleanTest { + /// Fuels `expression == true` + case `true` + + /// Fuels `expression == false` + case `false` + + /// Fuels `!expression` + case falsey + } + + /// `AssociativeBinaryOperator` is an associative binary operator, + /// such as `+`, `*`, `AND`, etc. + /// + /// Use it with the `joined(operator:)` method. For example: + /// + /// // SELECT score + bonus + 1000 FROM player + /// let values = [ + /// scoreColumn, + /// bonusColumn, + /// 1000.databaseValue] + /// Player.select(values.joined(operator: .add)) + public struct AssociativeBinaryOperator: Hashable { + /// The SQL operator + let sql: String + + /// The neutral value + let neutralValue: DatabaseValue + + /// If true, (a • b) • c is strictly equal to a • (b • c). + /// + /// `AND`, `OR`, `||` (concat) are stricly associative. + /// + /// `+` and `*` are not stricly associative when applied to floating + /// point values. + let isStrictlyAssociative: Bool + + /// If true, (a • b) is a bijective function of a, and a bijective + /// function of b. + /// + /// `+` and `||` (concat) are bijective. + /// + /// `AND`, `OR` and `*` are not. + let isBijective: Bool + + /// Creates a binary operator + init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool, bijective: Bool) { + self.sql = sql + self.neutralValue = neutralValue + self.isStrictlyAssociative = strictlyAssociative + self.isBijective = bijective + } + + /// The `+` binary operator + /// + /// For example: + /// + /// // score + bonus + /// [Column("score"), Column("bonus")].joined(operator: .add) + public static let add = AssociativeBinaryOperator( + sql: "+", + neutralValue: 0.databaseValue, + strictlyAssociative: false, + bijective: true) + + /// The `*` binary operator + /// + /// For example: + /// + /// // score * factor + /// [Column("score"), Column("factor")].joined(operator: .multiply) + public static let multiply = AssociativeBinaryOperator( + sql: "*", + neutralValue: 1.databaseValue, + strictlyAssociative: false, + bijective: false) + + /// The `AND` binary operator + /// + /// For example: + /// + /// // isBlue AND isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .and) + public static let and = AssociativeBinaryOperator( + sql: "AND", + neutralValue: true.databaseValue, + strictlyAssociative: true, + bijective: false) + + /// The `OR` binary operator + /// + /// For example: + /// + /// // isBlue OR isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .or) + public static let or = AssociativeBinaryOperator( + sql: "OR", + neutralValue: false.databaseValue, + strictlyAssociative: true, + bijective: false) + + /// The `||` string concatenation operator + /// + /// For example: + /// + /// // firstName || ' ' || lastName + /// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat) + public static let concat = AssociativeBinaryOperator( + sql: "||", + neutralValue: "".databaseValue, + strictlyAssociative: true, + bijective: true) + } + + /// `BinaryOperator` is an SQLite binary operator, such as `>`, `=`, etc. + /// + /// See also `AssociativeBinaryOperator` and `EqualityOperator`. + struct BinaryOperator: Hashable { + /// The SQL operator + let sql: String + + /// The SQL for the negated operator, if any + let negatedSQL: String? + + /// Creates a binary operator + /// + /// BinaryOperator("-") + /// BinaryOperator("LIKE", negated: "NOT LIKE") + init(_ sql: String, negated: String? = nil) { + self.sql = sql + self.negatedSQL = negated + } + + /// Returns the negated binary operator, if any + /// + /// let operator = BinaryOperator("IS", negated: "IS NOT") + /// operator.negated!.sql // IS NOT + var negated: BinaryOperator? { + guard let negatedSQL = negatedSQL else { + return nil + } + return BinaryOperator(negatedSQL, negated: sql) + } + + /// The `<` binary operator + static let lessThan = BinaryOperator("<") + + /// The `<=` binary operator + static let lessThanOrEqual = BinaryOperator("<=") + + /// The `>` binary operator + static let greaterThan = BinaryOperator(">") + + /// The `>=` binary operator + static let greaterThanOrEqual = BinaryOperator(">=") + + /// The `-` binary operator + static let subtract = BinaryOperator("-") + + /// The `/` binary operator + static let divide = BinaryOperator("/") + + /// The `LIKE` binary operator + static let like = BinaryOperator("LIKE", negated: "NOT LIKE") + + /// The `MATCH` binary operator + static let match = BinaryOperator("MATCH") + } + + /// `EqualityOperator` is an SQLite equality operator. + enum EqualityOperator: String { + case equal = "=" + case notEqual = "<>" + case `is` = "IS" + case isNot = "IS NOT" + + var negated: EqualityOperator { + switch self { + case .equal: return .notEqual + case .notEqual: return .equal + case .is: return .isNot + case .isNot: return .is + } + } + } + + /// `UnaryOperator` is a SQLite unary operator. + struct UnaryOperator: Hashable { + /// The SQL operator + let sql: String + + /// If true GRDB puts a white space between the operator and the operand. + let needsRightSpace: Bool + + /// Creates an unary operator + /// + /// UnaryOperator("~", needsRightSpace: false) + init(_ sql: String, needsRightSpace: Bool) { + self.sql = sql + self.needsRightSpace = needsRightSpace + } + + /// The `-` unary operator + static let minus = UnaryOperator("-", needsRightSpace: false) + } +} + +@available(*, deprecated, renamed: "SQLExpression.AssociativeBinaryOperator") +public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator + +// MARK: - Creating Expressions + +extension SQLExpression { + /// SQLite row values were shipped in SQLite 3.15: /// https://www.sqlite.org/releaselog/3_15_0.html static let rowValuesAreAvailable = (sqlite3_libversion_number() >= 3015000) + // MARK: Basic Expressions + + /// A column. + /// + /// id + /// name static func column(_ name: String) -> Self { self.init(impl: .column(name)) } + /// A qualified column. + /// + /// player.id + /// player.name static func qualifiedColumn(_ name: String, _ alias: TableAlias) -> Self { self.init(impl: .qualifiedColumn(name, alias)) } + /// A database value. + /// + /// NULL + /// 42 + /// 'Alice' + /// 3.14 + /// + /// + /// See also `SQLExpression.null` static func databaseValue(_ dbValue: DatabaseValue) -> Self { self.init(impl: .databaseValue(dbValue)) } + /// The `NULL` expression. static let null = SQLExpression.databaseValue(.null) - /// Returns nil if and only if expressions is empty + /// A [row value](https://www.sqlite.org/rowvalue.html). + /// + /// Returns nil if and only if expressions is empty. static func rowValue(_ expressions: [SQLExpression]) -> Self? { guard let expression = expressions.first else { return nil @@ -164,14 +403,21 @@ public struct SQLExpression { return self.init(impl: .rowValue(expressions)) } + /// A subquery expression. static func subquery(_ subquery: SQLSubquery) -> Self { self.init(impl: .subquery(subquery)) } + /// A literal SQL expression. static func literal(_ sqlLiteral: SQLLiteral) -> Self { self.init(impl: .literal(sqlLiteral)) } + // MARK: Operators + + /// The `BETWEEN` and `NOT BETWEEN` operators. + /// + /// BETWEEN AND static func between( expression: SQLExpression, lowerBound: SQLExpression, @@ -185,11 +431,31 @@ public struct SQLExpression { isNegated: isNegated)) } - static func binary(_ op: SQLBinaryOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { + /// A binary operator. + /// + /// * + /// <= + /// LIKE + static func binary(_ op: BinaryOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { self.init(impl: .binary(op, lhs, rhs)) } - static func associativeBinary(_ op: SQLAssociativeBinaryOperator, _ expressions: [SQLExpression]) -> Self { + /// An associative binary operator. + /// + /// AND + /// + + + /// + /// When the `expressions` array is empty, returns the neutral value of + /// the operator. + /// + /// When the `expressions` array contains a single expression, returns + /// this expression. + /// + /// When the operator is strictly associative, the expressions + /// are flattened: + /// + /// (a AND b) AND c -> a AND b AND c + static func associativeBinary(_ op: AssociativeBinaryOperator, _ expressions: [SQLExpression]) -> Self { // flatten when possible: a • (b • c) = a • b • c var expressions = expressions if op.isStrictlyAssociative { @@ -211,19 +477,40 @@ public struct SQLExpression { return self.init(impl: .associativeBinary(op, expressions)) } + /// The `IN` and `NOT IN` operators. + /// + /// IN + /// NOT IN + /// + /// See also `SQLCollection.contains(_:)`. static func `in`(_ expression: SQLExpression, _ collection: SQLCollection, isNegated: Bool = false) -> Self { self.init(impl: .in(expression, collection, isNegated: isNegated)) } - static func unary(_ op: SQLUnaryOperator, _ expression: SQLExpression) -> Self { + /// An unary operator. + /// + /// - + static func unary(_ op: UnaryOperator, _ expression: SQLExpression) -> Self { self.init(impl: .unary(op, expression)) } - static func compare(_ op: SQLCompareOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { + /// An equality comparison. + /// + /// = + /// <> + /// IS + /// IS NOT + /// + /// See also `SQLExpression.equal(_:_:)`. + static func compare(_ op: EqualityOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { self.init(impl: .compare(op, lhs, rhs)) } - /// "x = y" or "x IS NULL" + /// An equality comparison. Null database values are checked with `IS NULL`. + /// + /// = + /// IS NULL + /// IS NULL static func equal(_ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { switch (lhs.impl, rhs.impl) { case let (impl, .databaseValue(.null)), @@ -236,36 +523,76 @@ public struct SQLExpression { } } + /// A table full-text match. + /// + ///
MATCH static func tableMatch(_ alias: TableAlias, _ expression: SQLExpression) -> Self { self.init(impl: .tableMatch(alias, expression)) } + /// A logical `NOT` operator. + /// + /// NOT static func not(_ expression: SQLExpression) -> Self { self.init(impl: .not(expression)) } + /// A collated expression. + /// + /// COLLATE static func collated(_ expression: SQLExpression, _ collationName: Database.CollationName) -> Self { self.init(impl: .collated(expression, collationName)) } + // MARK: Functions + + /// The `COUNT` function. + /// + /// COUNT(*) + /// COUNT() static func count(_ selection: SQLSelection) -> Self { self.init(impl: .count(selection)) } + /// The `COUNT(DISTINCT)` function. + /// + /// COUNT(DISTINCT ) static func countDistinct(_ expression: SQLExpression) -> Self { self.init(impl: .countDistinct(expression)) } + /// A function call. + /// + /// (, ...) static func function(_ name: String, _ expressions: [SQLExpression]) -> Self { self.init(impl: .function(name, expressions)) } + /// An expression that checks for zero or positive values. + /// + /// = 0 + /// > 0 static func isEmpty(_ expression: SQLExpression, isNegated: Bool = false) -> Self { self.init(impl: .isEmpty(expression, isNegated: isNegated)) } + // MARK: Deferred + + /// An expression that picks the fastest available primary key. + /// + /// It crashes for WITHOUT ROWID table with a multi-columns primary key. + /// Future versions of GRDB may use [row values](https://www.sqlite.org/rowvalue.html). + /// + /// id + /// rowid + /// code static let fastPrimaryKey = SQLExpression(impl: .fastPrimaryKey) + /// A qualified "fast primary key" (see `SQLExpression.fastPrimaryKey`). + /// + /// player.id + /// document.rowid + /// country.code static func qualifiedFastPrimaryKey(_ alias: TableAlias) -> Self { self.init(impl: .qualifiedFastPrimaryKey(alias)) } @@ -279,9 +606,7 @@ extension SQLExpression { let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) return try sql(context) } -} - -extension SQLExpression { + /// If this expression is a table colum, returns the name of this column. /// /// When in doubt, returns nil. @@ -372,9 +697,7 @@ extension SQLExpression { return nil } } -} - -extension SQLExpression { + /// Returns an SQL string that represents the expression. /// /// - parameter context: An SQL generation context which accepts @@ -558,9 +881,7 @@ extension SQLExpression { .sql(context, wrappedInParenthesis: wrappedInParenthesis) } } -} - -extension SQLExpression { + /// Returns the columns that identify a unique row in the request /// /// When in doubt, returns an empty set. @@ -627,9 +948,7 @@ extension SQLExpression { return [] } } -} - -extension SQLExpression { + /// Returns the rowIds that identify rows in the request. A nil result means /// an unbounded list. /// @@ -752,9 +1071,7 @@ extension SQLExpression { return nil } } -} - -extension SQLExpression { + /// Performs a boolean test. /// /// We generally distinguish four boolean values: @@ -791,7 +1108,7 @@ extension SQLExpression { /// - `!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 { + func `is`(_ test: BooleanTest) -> SQLExpression { switch impl { case let .databaseValue(dbValue): switch dbValue.storage { @@ -910,9 +1227,7 @@ extension SQLExpression { } } } -} - -extension SQLExpression { + private static let knownPureFunctions = [ "ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL", "IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD", @@ -978,9 +1293,7 @@ extension SQLExpression { return false } } -} - -extension SQLExpression { + /// Returns a qualified expression func qualified(with alias: TableAlias) -> SQLExpression { switch impl { @@ -1051,9 +1364,7 @@ extension SQLExpression { return .qualifiedFastPrimaryKey(alias) } } -} - -extension SQLExpression { + /// Returns true if the expression is an aggregate. /// /// When in doubt, returns false. @@ -1116,7 +1427,7 @@ extension SQLExpression { } else if name == "GROUP_CONCAT" && (expressions.count == 1 || expressions.count == 2) { return true } else { - // TODO: return true if all arguments are aggregates? + // Return true if all arguments are aggregates? return false } @@ -1126,270 +1437,6 @@ extension SQLExpression { } } -extension Sequence where Element: SQLSpecificExpressible { - /// Returns an expression by joining all elements with an associative 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`, and true for `.and`. - public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { - .associativeBinary(`operator`, map(\.sqlExpression)) - } -} - -extension Sequence where Element == SQLSpecificExpressible { - /// Returns an expression by joining all elements with an associative 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`, and true for `.and`. - public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { - .associativeBinary(`operator`, map(\.sqlExpression)) - } -} - -// MARK: - SQLBooleanTest - -/// `SQLBooleanTest` supports boolean tests. -/// -/// See `SQLExpression.is(_:)` -enum SQLBooleanTest { - /// Fuels `expression == true` - case `true` - - /// Fuels `expression == false` - case `false` - - /// Fuels `!expression` - case falsey -} - -// MARK: - SQLAssociativeBinaryOperator - -/// SQLAssociativeBinaryOperator is an SQLite associative binary operator, such -/// as `+`, `*`, `AND`, etc. -/// -/// Use it with the `joined(operator:)` method. For example: -/// -/// // SELECT score + bonus + 1000 FROM player -/// let values = [ -/// scoreColumn, -/// bonusColumn, -/// 1000.databaseValue] -/// Player.select(values.joined(operator: .add)) -public struct SQLAssociativeBinaryOperator: Hashable { - /// The SQL operator - let sql: String - - /// The neutral value - let neutralValue: DatabaseValue - - /// If true, (a • b) • c is strictly equal to a • (b • c). - /// - /// `AND`, `OR`, `||` (concat) are stricly associative. - /// - /// `+` and `*` are not stricly associative when applied to floating - /// point values. - let isStrictlyAssociative: Bool - - /// If true, (a • b) is a bijective function of a, and a bijective - /// function of b. - /// - /// `+` and `||` (concat) are bijective. - /// - /// `AND`, `OR` and `*` are not. - let isBijective: Bool - - /// Creates a binary operator - init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool, bijective: Bool) { - self.sql = sql - self.neutralValue = neutralValue - self.isStrictlyAssociative = strictlyAssociative - self.isBijective = bijective - } - - /// 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, - bijective: true) - - /// The `*` binary operator - /// - /// For example: - /// - /// // score * factor - /// [Column("score"), Column("factor")].joined(operator: .multiply) - public static let multiply = SQLAssociativeBinaryOperator( - sql: "*", - neutralValue: 1.databaseValue, - strictlyAssociative: false, - bijective: false) - - /// 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, - bijective: false) - - /// 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, - strictlyAssociative: true, - bijective: false) - - /// 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, - bijective: true) -} - -// MARK: - SQLBinaryOperator - -/// SQLBinaryOperator is an SQLite binary operator, such as >, =, etc. -struct SQLBinaryOperator: Hashable { - /// The SQL operator - let sql: String - - /// The SQL for the negated operator, if any - let negatedSQL: String? - - /// Creates a binary operator - /// - /// SQLBinaryOperator("-") - /// SQLBinaryOperator("LIKE", negated: "NOT LIKE") - init(_ sql: String, negated: String? = nil) { - self.sql = sql - self.negatedSQL = negated - } - - /// Returns the negated binary operator, if any - /// - /// let operator = SQLBinaryOperator("IS", negated: "IS NOT") - /// operator.negated!.sql // IS NOT - var negated: SQLBinaryOperator? { - guard let negatedSQL = negatedSQL else { - return nil - } - return SQLBinaryOperator(negatedSQL, negated: sql) - } - - /// The `<` binary operator - static let lessThan = SQLBinaryOperator("<") - - /// The `<=` binary operator - static let lessThanOrEqual = SQLBinaryOperator("<=") - - /// The `>` binary operator - static let greaterThan = SQLBinaryOperator(">") - - /// The `>=` binary operator - static let greaterThanOrEqual = SQLBinaryOperator(">=") - - /// The `-` binary operator - static let subtract = SQLBinaryOperator("-") - - /// The `/` binary operator - static let divide = SQLBinaryOperator("/") - - /// The `LIKE` binary operator - static let like = SQLBinaryOperator("LIKE", negated: "NOT LIKE") - - /// The `MATCH` binary operator - static let match = SQLBinaryOperator("MATCH") -} - -// MARK: - SQLCompareOperator - -enum SQLCompareOperator: String { - case equal = "=" - case notEqual = "<>" - case `is` = "IS" - case isNot = "IS NOT" - - var negated: SQLCompareOperator { - switch self { - case .equal: return .notEqual - case .notEqual: return .equal - case .is: return .isNot - case .isNot: return .is - } - } -} - -// MARK: - SQLUnaryOperator - -/// SQLUnaryOperator is a SQLite unary operator. -struct SQLUnaryOperator: Hashable { - /// The SQL operator - let sql: String - - /// If true GRDB puts a white space between the operator and the operand. - let needsRightSpace: Bool - - /// Creates an unary operator - /// - /// SQLUnaryOperator("~", needsRightSpace: false) - init(_ sql: String, needsRightSpace: Bool) { - self.sql = sql - self.needsRightSpace = needsRightSpace - } - - /// The `-` unary operator - static let minus = SQLUnaryOperator("-", needsRightSpace: false) -} - // MARK: - SQLExpressible /// `SQLExpressible` is the protocol for all types that can be used as an @@ -1450,9 +1497,56 @@ extension SQLExpression: SQLSpecificExpressible { public var sqlExpression: SQLExpression { self } } +extension Sequence where Element: SQLSpecificExpressible { + /// Returns an expression by joining all elements with an associative 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`, and true for `.and`. + public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression { + .associativeBinary(`operator`, map(\.sqlExpression)) + } +} + +extension Sequence where Element == SQLSpecificExpressible { + /// Returns an expression by joining all elements with an associative 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`, and true for `.and`. + public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression { + .associativeBinary(`operator`, map(\.sqlExpression)) + } +} + // MARK: - SQL Ordering Support -/// :nodoc: extension SQLSpecificExpressible { /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() @@ -1502,7 +1596,6 @@ extension SQLSpecificExpressible { #endif } - // MARK: - SQL Selection Support /// :nodoc: @@ -1544,10 +1637,8 @@ extension SQLSpecificExpressible { } } - // MARK: - SQL Collations Support -/// :nodoc: extension SQLSpecificExpressible { /// Returns a collated expression.