Merge pull request #683 from groue/dev/concat

String concatenation
This commit is contained in:
Gwendal Roué authored and GitHub committed 2020-01-17 07:34:44 +01:00
commit f3bc08160d
7 files changed
+328 -126

No files matched your search

+1
View File
@@ -61,6 +61,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
- [#683](https://github.com/groue/GRDB.swift/pull/683): String concatenation
- [#685](https://github.com/groue/GRDB.swift/pull/685) by [@gjeck](https://github.com/gjeck): Add cache for TableRecord.defaultDatabaseTableName
@@ -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,159 @@ 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 ")
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// 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.
public let strictlyAssociative: Bool
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: alias) })
}
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
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
public init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool) {
self.sql = sql
self.neutralValue = neutralValue
self.strictlyAssociative = strictlyAssociative
}
}
// MARK: - SQLExpressionOr
@available(*, deprecated, renamed: "SQLAssociativeBinaryOperator")
typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator
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]) {
self.expressions = expressions
/// 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
// 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 {
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<Int64>? {
if expressions.isEmpty {
return []
}
var result: Set<Int64> = []
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<Int64> = []
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))
}
}
+78 -60
View File
@@ -558,19 +558,37 @@ 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
///
/// 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,
strictlyAssociative: false)
}
extension SQLUnaryOperator {
/// The `-` unary operator
static let minus = SQLUnaryOperator("-", needsRightSpace: false)
@@ -581,7 +599,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 +607,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 +615,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 +647,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 +655,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 +663,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 +679,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 +687,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 +695,42 @@ 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
///
/// 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,
strictlyAssociative: true)
}
/// 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 +738,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 +746,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 +754,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 +762,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 +770,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 +786,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 {
@@ -801,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
@@ -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 {
+30 -2
View File
@@ -4282,7 +4282,35 @@ 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.
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.
- `||`
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`
@@ -4293,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))
@@ -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 {
@@ -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()
@@ -1079,6 +1127,41 @@ 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"
""")
// 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"
""")
}
// MARK: - Function
func testCustomFunction() throws {