Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2020-01-17 07:41:27 +01:00
commit f67232b80f
11 files changed
+382 -157

No files matched your search

+11
View File
@@ -13,6 +13,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 4.x Releases
- `4.9.x` Releases - [4.9.0](#490)
- `4.8.x` Releases - [4.8.0](#480) | [4.8.1](#481)
- `4.7.x` Releases - [4.7.0](#470)
- `4.6.x` Releases - [4.6.0](#460) | [4.6.1](#461) | [4.6.2](#462)
@@ -66,6 +67,16 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
-->
## 4.9.0
Released January 17, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.8.1...v4.9.0)
**New**
- [#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
## 4.8.1
Released January 12, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.8.0...v4.8.1)
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '4.8.1'
s.version = '4.9.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -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 {
+17 -4
View File
@@ -1,3 +1,5 @@
import Foundation
/// Types that adopt TableRecord declare a particular relationship with
/// a database table.
///
@@ -59,18 +61,24 @@ extension TableRecord {
/// - HTTPRequest -> "httpRequest"
/// - TOEFL -> "toefl"
internal static var defaultDatabaseTableName: String {
if let cached = defaultDatabaseTableNameCache.object(forKey: "\(Self.self)" as NSString) {
return cached as String
}
let typeName = "\(Self.self)".replacingOccurrences(of: "(.)\\b.*$", with: "$1", options: [.regularExpression])
let initial = typeName.replacingOccurrences(of: "^([A-Z]+).*$", with: "$1", options: [.regularExpression])
let tableName: String
switch initial.count {
case typeName.count:
return initial.lowercased()
tableName = initial.lowercased()
case 0:
return typeName
tableName = typeName
case 1:
return initial.lowercased() + typeName.dropFirst()
tableName = initial.lowercased() + typeName.dropFirst()
default:
return initial.dropLast().lowercased() + typeName.dropFirst(initial.count - 1)
tableName = initial.dropLast().lowercased() + typeName.dropFirst(initial.count - 1)
}
defaultDatabaseTableNameCache.setObject(tableName as NSString, forKey: "\(Self.self)" as NSString)
return tableName
}
/// The default name of the database table used to build requests.
@@ -153,3 +161,8 @@ extension TableRecord {
.reduce(0, +)
}
}
/// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation
///
/// This cache mitigates the cost of the calculation by storing the name for later retrieval
private let defaultDatabaseTableNameCache = NSCache<NSString, NSString>()
+3 -3
View File
@@ -459,10 +459,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.8.1 \
--module-version 4.8.1 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.9.0 \
--module-version 4.9.0 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/4.8/ \
--root-url http://groue.github.io/GRDB.swift/docs/4.9/ \
--output Documentation/Reference \
--podspec GRDB.swift.podspec
else
+52 -24
View File
@@ -12,14 +12,14 @@
---
**Latest release**: January 12, 2020 • version 4.8.1 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md)
**Latest release**: January 17, 2020 • version 4.9.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md)
**Requirements**: iOS 9.0+ / macOS 10.9+ / tvOS 9.0+ / watchOS 2.0+ &bull; Swift 4.2+ / Xcode 10.0+
| Swift version | GRDB version |
| ------------- | ----------------------------------------------------------- |
| **Swift 5** | **v4.8.1** |
| **Swift 4.2** | **v4.8.1** |
| **Swift 5** | **v4.9.0** |
| **Swift 4.2** | **v4.9.0** |
| Swift 4.1 | [v3.7.0](https://github.com/groue/GRDB.swift/tree/v3.7.0) |
| Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) |
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
@@ -263,7 +263,7 @@ Documentation
#### Reference
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.8/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.9/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -477,7 +477,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.8/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.9/Structs/Configuration.html) for more details.
## Database Pools
@@ -558,7 +558,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.8/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.9/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -618,7 +618,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.9/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
In Swift 5, you can embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
@@ -819,7 +819,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
- **Cursors are granted with direct access to SQLite,** unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays.
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.8/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.9/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
```swift
// Prints all Github links
@@ -901,7 +901,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.9/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
@@ -1184,7 +1184,7 @@ GRDB ships with built-in support for the following value types:
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.9/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1591,7 +1591,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
}
```
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.8/Structs/Configuration.html) configuration flag:
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.9/Structs/Configuration.html) configuration flag:
```swift
// fatal error: A transaction has been left opened at the end of a database access
@@ -1705,7 +1705,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.9/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1964,7 +1964,7 @@ row["consumed"] // "Hello"
row["produced"] // nil
```
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.8/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.9/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support).
@@ -2426,7 +2426,7 @@ try Place.fetchAll(db, sql: "SELECT ...", arguments:...) // [Place]
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.9/Structs/StatementArguments.html) for more information about the query arguments.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
@@ -2807,7 +2807,7 @@ protocol EncodableRecord {
}
```
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.8/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.8/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.8/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.9/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.9/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.9/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
@@ -4194,7 +4194,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.9/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -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))
@@ -4781,7 +4809,7 @@ let request = Player.all()
**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol.
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.8/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.9/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
```swift
extension Player {
@@ -4825,7 +4853,7 @@ let request = Player.all()
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.8/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.9/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request.
### Fetching From Custom Requests
@@ -6359,7 +6387,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
### DatabaseRegion
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.8/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.9/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion.
@@ -6369,7 +6397,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.8/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.9/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
#### The DatabaseRegionConvertible Protocol
@@ -7473,7 +7501,7 @@ try snapshot2.read { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.8/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.8/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.9/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.9/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
@@ -8157,7 +8185,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), [@gusrota](https://github.com/gusrota), [@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), [@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), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@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), [@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.
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>4.8.1</string>
<string>4.9.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -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 {