From 32a40b18fdfa6daf9cc45c7540ed66d184acbd77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:01:48 +0100 Subject: [PATCH 01/11] Introduce associative binary operators --- .../SQL/SQLExpression+QueryInterface.swift | 157 ++++++++++++------ GRDB/QueryInterface/SQL/SQLOperators.swift | 92 ++++------ .../SQLGeneration/SQLQueryGenerator.swift | 12 +- 3 files changed, 141 insertions(+), 120 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 814dabf46..63511ef77 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -164,7 +164,7 @@ public struct SQLExpressionUnary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// -/// SQLBinaryOperator is a SQLite binary operator. +/// SQLBinaryOperator is an SQLite binary operator, such as >, =, etc. /// /// :nodoc: public struct SQLBinaryOperator: Hashable { @@ -182,7 +182,7 @@ public struct SQLBinaryOperator: Hashable { /// /// Creates a binary operator /// - /// SQLBinaryOperator("+") + /// SQLBinaryOperator("-") /// SQLBinaryOperator("IS", negated: "IS NOT") public init(_ sql: String, negated: String? = nil) { self.sql = sql @@ -233,7 +233,7 @@ public struct SQLExpressionBinary: SQLExpression { /// binary operator. /// /// // length * width - /// SQLExpressionBinary(.multiply, Column("length"), Column("width")) + /// SQLExpressionBinary(.subtract, Column("score"), Column("malus")) public init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) { self.lhs = lhs.sqlExpression self.op = op @@ -270,87 +270,136 @@ public struct SQLExpressionBinary: SQLExpression { } } -// MARK: - SQLExpressionAnd +// MARK: - SQLExpressionBinaryReduce -struct SQLExpressionAnd: SQLExpression { - let expressions: [SQLExpression] +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// SQLAssociativeBinaryOperator is an SQLite associative binary operator, such +/// as +, *, AND, etc. +/// +/// :nodoc: +public struct SQLAssociativeBinaryOperator: Hashable { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The SQL operator + public let sql: String - init(_ expressions: [SQLExpression]) { - self.expressions = expressions - } + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The neutral value + public let neutralValue: DatabaseValue - func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - guard let first = expressions.first else { - // Ruby [].all? # => true - return true.sqlExpression.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) - } - if expressions.count == 1 { - return first.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) - } - let expressionSQLs = expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: true) } - if wrappedInParenthesis { - return "(\(expressionSQLs.joined(separator: " AND ")))" - } else { - return expressionSQLs.joined(separator: " AND ") - } - } - - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: alias) }) - } - - func matchedRowIds(rowIdName: String?) -> Set? { - let matchedRowIds = expressions.compactMap { - $0.matchedRowIds(rowIdName: rowIdName) - } - guard let first = matchedRowIds.first else { - return nil - } - return matchedRowIds.suffix(from: 1).reduce(into: first) { $0.formIntersection($1) } + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Creates a binary operator + /// + /// SQLAssociativeBinaryOperator("+") + /// SQLAssociativeBinaryOperator("AND") + public init(_ sql: String, neutralValue: DatabaseValue) { + self.sql = sql + self.neutralValue = neutralValue } } -// MARK: - SQLExpressionOr - -struct SQLExpressionOr: SQLExpression { +/// SQLExpressionBinary is an expression made of two expressions joined with a +/// binary operator. +/// +/// SQLExpressionBinary(.multiply, Column("length"), Column("width")) +struct SQLExpressionBinaryReduce: SQLExpression { let expressions: [SQLExpression] + let op: SQLAssociativeBinaryOperator - init(_ expressions: [SQLExpression]) { + /// Creates an expression made of expressions joined with an associative + /// binary operator. + /// + /// // length * width + /// SQLExpressionBinaryReduce(.multiply, [Column("length"), Column("width")]) + init(_ op: SQLAssociativeBinaryOperator, _ expressions: [SQLExpression]) { + self.op = op self.expressions = expressions } func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { guard let first = expressions.first else { - // Ruby [].any? # => false - return false.sqlExpression.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) + return op.neutralValue.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) } if expressions.count == 1 { return first.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) } let expressionSQLs = expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: true) } + let joiner = " \(op.sql) " if wrappedInParenthesis { - return "(\(expressionSQLs.joined(separator: " OR ")))" + return "(\(expressionSQLs.joined(separator: joiner)))" } else { - return expressionSQLs.joined(separator: " OR ") + return expressionSQLs.joined(separator: joiner) } } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: alias) }) + return SQLExpressionBinaryReduce(op, expressions.map { $0.qualifiedExpression(with: alias) }) } func matchedRowIds(rowIdName: String?) -> Set? { - if expressions.isEmpty { - return [] - } - var result: Set = [] - for expr in expressions { - guard let matchedRowIds = expr.matchedRowIds(rowIdName: rowIdName) else { + switch op { + case .and: + let matchedRowIds = expressions.compactMap { + $0.matchedRowIds(rowIdName: rowIdName) + } + guard let first = matchedRowIds.first else { return nil } - result.formUnion(matchedRowIds) + return matchedRowIds.suffix(from: 1).reduce(into: first) { $0.formIntersection($1) } + case .or: + if expressions.isEmpty { + return [] + } + var result: Set = [] + for expr in expressions { + guard let matchedRowIds = expr.matchedRowIds(rowIdName: rowIdName) else { + return nil + } + result.formUnion(matchedRowIds) + } + return result + default: + return nil } - return result + } +} + +extension Sequence where Element == SQLExpression { + /// Returns an expression by joining all elements with an SQL + /// binary operator. + /// + /// For example: + /// + /// // SELECT * FROM player + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >= 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// + /// When the sequence is empty, `joined(operator:)` returns the neutral + /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, + /// false for `.or`, true for `.and`... + /// and `joined(operator: .or)` returns false: + /// When the sequence is empty, `joined(operator: .and)` returns true, + /// and `joined(operator: .or)` returns false: + /// + /// // SELECT 0 FROM player + /// Player.select([].joined(operator: .add)) + /// + /// // SELECT * FROM player WHERE 1 + /// Player.filter([].joined(operator: .and)) + /// + /// // SELECT * FROM player WHERE 0 + /// Player.filter([].joined(operator: .or)) + public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { + return SQLExpressionBinaryReduce(`operator`, Array(self)) } } diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index ac0ee9c87..b18ae8bc2 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -558,19 +558,21 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { // MARK: - Arithmetic Operators (+, -, *, /) extension SQLBinaryOperator { - /// The `+` binary operator - static let plus = SQLBinaryOperator("+") - /// The `-` binary operator - static let minus = SQLBinaryOperator("-") - - /// The `*` binary operator - static let multiply = SQLBinaryOperator("*") + static let subtract = SQLBinaryOperator("-") /// The `/` binary operator static let divide = SQLBinaryOperator("/") } +extension SQLAssociativeBinaryOperator { + /// The `+` binary operator + public static let add = SQLAssociativeBinaryOperator("+", neutralValue: 0.databaseValue) + + /// The `*` binary operator + public static let multiply = SQLAssociativeBinaryOperator("*", neutralValue: 1.databaseValue) +} + extension SQLUnaryOperator { /// The `-` unary operator static let minus = SQLUnaryOperator("-", needsRightSpace: false) @@ -581,7 +583,7 @@ extension SQLUnaryOperator { /// // width * 2 /// Column("width") * 2 public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.multiply, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -589,7 +591,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 * width /// 2 * Column("width") public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.multiply, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -597,7 +599,7 @@ public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width * height /// Column("width") * Column("height") public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.multiply, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic division. @@ -629,7 +631,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // width + 2 /// Column("width") + 2 public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.plus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -637,7 +639,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 + width /// 2 + Column("width") public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.plus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -645,7 +647,7 @@ public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width + height /// Column("width") + Column("height") public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.plus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated SQL arithmetic expression. @@ -661,7 +663,7 @@ public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { /// // width - 2 /// Column("width") - 2 public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.minus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -669,7 +671,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 - width /// 2 - Column("width") public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.minus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -677,18 +679,26 @@ public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width - height /// Column("width") - Column("height") public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.minus, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } // MARK: - Logical Operators (AND, OR, NOT) +extension SQLAssociativeBinaryOperator { + /// The `AND` binary operator + public static let and = SQLAssociativeBinaryOperator("AND", neutralValue: true.databaseValue) + + /// The `OR` binary operator + public static let or = SQLAssociativeBinaryOperator("OR", neutralValue: false.databaseValue) +} + /// A logical SQL expression with the `AND` SQL operator. /// /// // favorite AND 0 /// Column("favorite") && false public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -696,7 +706,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 AND favorite /// false && Column("favorite") public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -704,7 +714,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NOT NULL AND favorite /// Column("email") != nil && Column("favorite") public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -712,7 +722,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // favorite OR 1 /// Column("favorite") || true public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -720,7 +730,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 OR favorite /// true || Column("favorite") public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -728,7 +738,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NULL OR hidden /// Column("email") == nil || Column("hidden") public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) + return SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression with the `NOT` SQL operator. @@ -744,44 +754,6 @@ public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { return value.sqlExpression.negated } -public enum SQLLogicalBinaryOperator { - case and, or -} - -extension Sequence where Element == SQLExpression { - /// Returns an expression by joining all elements with an SQL - /// logical operator. - /// - /// For example: - /// - /// // SELECT * FROM player - /// // WHERE (registered - /// // AND (score >= 1000) - /// // AND (name IS NOT NULL)) - /// let conditions = [ - /// Column("registered"), - /// Column("score") >= 1000, - /// Column("name") != nil] - /// Player.filter(conditions.joined(operator: .and)) - /// - /// When the sequence is empty, `joined(operator: .and)` returns true, - /// and `joined(operator: .or)` returns false: - /// - /// // SELECT * FROM player WHERE 1 - /// Player.filter([].joined(operator: .and)) - /// - /// // SELECT * FROM player WHERE 0 - /// Player.filter([].joined(operator: .or)) - public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { - let expressions = Array(self) - switch `operator` { - case .and: return SQLExpressionAnd(expressions) - case .or: return SQLExpressionOr(expressions) - } - } -} - - // MARK: - Like Operator extension SQLBinaryOperator { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index cdc09eb11..04ea0b584 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -65,7 +65,7 @@ struct SQLQueryGenerator { let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { sql += " WHERE " - sql += SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) + sql += filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false) } if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { @@ -77,7 +77,7 @@ struct SQLQueryGenerator { if havingExpressions.isEmpty == false { sql += " HAVING " - sql += SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false) + sql += havingExpressions.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false) } let orderings = try relation.ordering.resolve(db) @@ -117,7 +117,7 @@ struct SQLQueryGenerator { // The filters knows better let filters = try relation.filtersPromise.resolve(db) - guard let rowIds = SQLExpressionAnd(filters).matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + guard let rowIds = filters.joined(operator: .and).matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { return databaseRegion } @@ -144,7 +144,7 @@ struct SQLQueryGenerator { let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) + sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false) } if let limit = limit { @@ -238,7 +238,7 @@ struct SQLQueryGenerator { let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) + sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false) } if let limit = limit { @@ -680,7 +680,7 @@ private struct SQLQualifiedJoin { let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias) + relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " ON \(SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false))" + sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))" } for (_, join) in relation.joins { From a398c6dc9913b70f3e3797447162aa625944793c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:17:11 +0100 Subject: [PATCH 02/11] Flattten stricly associative operators --- .../SQL/SQLExpression+QueryInterface.swift | 30 +++++++++++++++---- GRDB/QueryInterface/SQL/SQLOperators.swift | 20 ++++++++++--- .../AssociationTableAliasTestsSQLTests.swift | 6 ++-- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 63511ef77..5d4842d03 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -291,13 +291,21 @@ public struct SQLAssociativeBinaryOperator: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// - /// Creates a binary operator + /// if true, (a • b) • c is strictly equal to a • (b • c). /// - /// SQLAssociativeBinaryOperator("+") - /// SQLAssociativeBinaryOperator("AND") - public init(_ sql: String, neutralValue: DatabaseValue) { + /// `AND`, `OR`, `||` (concat) are stricly associative. + /// + /// + and * are not stricly associative when applied to floating + /// point values. + public let strictlyAssociative: Bool + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Creates a binary operator + public init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool) { self.sql = sql self.neutralValue = neutralValue + self.strictlyAssociative = strictlyAssociative } } @@ -316,7 +324,19 @@ struct SQLExpressionBinaryReduce: SQLExpression { /// SQLExpressionBinaryReduce(.multiply, [Column("length"), Column("width")]) init(_ op: SQLAssociativeBinaryOperator, _ expressions: [SQLExpression]) { self.op = op - self.expressions = expressions + + // flatten when possible: a • (b • c) = a • b • c + if op.strictlyAssociative { + self.expressions = expressions.flatMap { expression -> [SQLExpression] in + if let reduce = expression as? SQLExpressionBinaryReduce, reduce.op == op { + return reduce.expressions + } else { + return [expression] + } + } + } else { + self.expressions = expressions + } } func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index b18ae8bc2..e32b06896 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -567,10 +567,16 @@ extension SQLBinaryOperator { extension SQLAssociativeBinaryOperator { /// The `+` binary operator - public static let add = SQLAssociativeBinaryOperator("+", neutralValue: 0.databaseValue) + public static let add = SQLAssociativeBinaryOperator( + sql: "+", + neutralValue: 0.databaseValue, + strictlyAssociative: false) /// The `*` binary operator - public static let multiply = SQLAssociativeBinaryOperator("*", neutralValue: 1.databaseValue) + public static let multiply = SQLAssociativeBinaryOperator( + sql: "*", + neutralValue: 1.databaseValue, + strictlyAssociative: false) } extension SQLUnaryOperator { @@ -687,10 +693,16 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE extension SQLAssociativeBinaryOperator { /// The `AND` binary operator - public static let and = SQLAssociativeBinaryOperator("AND", neutralValue: true.databaseValue) + public static let and = SQLAssociativeBinaryOperator( + sql: "AND", + neutralValue: true.databaseValue, + strictlyAssociative: true) /// The `OR` binary operator - public static let or = SQLAssociativeBinaryOperator("OR", neutralValue: false.databaseValue) + public static let or = SQLAssociativeBinaryOperator( + sql: "OR", + neutralValue: false.databaseValue, + strictlyAssociative: true) } /// A logical SQL expression with the `AND` SQL operator. diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift index 994ba938c..dc18cf213 100644 --- a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -53,7 +53,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase { let expectedSQL = """ SELECT "name" \ FROM "a" \ - WHERE ("id" = 1) AND (("name" IS NOT NULL) AND ("name" = 'foo')) \ + WHERE ("id" = 1) AND ("name" IS NOT NULL) AND ("name" = 'foo') \ GROUP BY "name" \ HAVING "name" \ ORDER BY "name" @@ -90,7 +90,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase { let expectedSQL = """ SELECT "customA"."name" \ FROM "a" "customA" \ - WHERE ("customA"."id" = 1) AND (("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo')) \ + WHERE ("customA"."id" = 1) AND ("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo') \ GROUP BY "customA"."name" \ HAVING "customA"."name" \ ORDER BY "customA"."name" @@ -307,7 +307,7 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase { JOIN "a" "a2" ON "a2"."bid2" = "b1"."id" \ JOIN "b" "b2" ON "b2"."id" = "a1"."bid2" \ JOIN "a" "a3" ON "a3"."bid1" = "b2"."id" \ - WHERE (("a1"."name" IS NOT NULL) AND ("a1"."name" > "a3"."name")) AND ("a2"."name" = 'foo') + WHERE ("a1"."name" IS NOT NULL) AND ("a1"."name" > "a3"."name") AND ("a2"."name" = 'foo') """ do { From 01b47a833ac624ab6bebb326ea46d33c4a92a980 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:38:17 +0100 Subject: [PATCH 03/11] Introduce the || string concatenation operator --- GRDB/QueryInterface/SQL/SQLOperators.swift | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index e32b06896..ea8085bd9 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -567,12 +567,22 @@ extension SQLBinaryOperator { extension SQLAssociativeBinaryOperator { /// The `+` binary operator + /// + /// For example: + /// + /// // score + bonus + /// [Column("score"), Column("bonus")].joined(operator: .add) public static let add = SQLAssociativeBinaryOperator( sql: "+", neutralValue: 0.databaseValue, strictlyAssociative: false) /// The `*` binary operator + /// + /// For example: + /// + /// // score * factor + /// [Column("score"), Column("factor")].joined(operator: .multiply) public static let multiply = SQLAssociativeBinaryOperator( sql: "*", neutralValue: 1.databaseValue, @@ -693,12 +703,22 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE extension SQLAssociativeBinaryOperator { /// The `AND` binary operator + /// + /// For example: + /// + /// // isBlue AND isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .and) public static let and = SQLAssociativeBinaryOperator( sql: "AND", neutralValue: true.databaseValue, strictlyAssociative: true) /// The `OR` binary operator + /// + /// For example: + /// + /// // isBlue OR isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .or) public static let or = SQLAssociativeBinaryOperator( sql: "OR", neutralValue: false.databaseValue, @@ -785,6 +805,20 @@ extension SQLSpecificExpressible { } } +// MARK: - Concat Operator + +extension SQLAssociativeBinaryOperator { + /// The `||` string concatenation operator + /// + /// For example: + /// + /// // firstName || ' ' || lastName + /// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat) + public static let concat = SQLAssociativeBinaryOperator( + sql: "||", + neutralValue: "".databaseValue, + strictlyAssociative: true) +} // MARK: - Match Operator From c9373929ca3be43d073f9c4139034da2e3742630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:38:26 +0100 Subject: [PATCH 04/11] Documentation for the || string concatenation operator --- README.md | 15 ++++++++++- .../QueryInterfaceExpressionsTests.swift | 25 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 25db069ea..4054600f6 100644 --- a/README.md +++ b/README.md @@ -4282,7 +4282,20 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Planet.select((temperatureColumn * 1.8 + 32).forKey("farenheit")) ``` - > :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. + > :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. See the `concat` operator below. + +- `||` + + Concatenate several strings: + + ```swift + // SELECT firstName || ' ' || lastName FROM player + Player.select([firstNameColumn, " ".databaseValue, lastNameColumn].joined(operator: .concat)) + ``` + + Note in the example above how you concatenate raw strings: `" ".databaseValue`. A plain `" "` would not compile. + + When the sequence is empty, `joined(operator: .concat)` returns the empty string. - `AND`, `OR`, `NOT` diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 2023a0d78..dd33b276e 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1079,6 +1079,31 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { } + // MARK: - || concat operator + + func testConcatOperator() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.name, Col.name].joined(operator: .concat))), + """ + SELECT "name" || "name" FROM "readers" + """) + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.name, Col.name].joined(operator: .concat) == "foo")), + """ + SELECT * FROM "readers" WHERE ("name" || "name") = 'foo' + """) + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.name, " ".databaseValue, Col.name].joined(operator: .concat))), + """ + SELECT "name" || ' ' || "name" FROM "readers" + """) + } + + // MARK: - Function func testCustomFunction() throws { From 62fad30af5cdb09948c4db0d998e275452d4a454 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 08:57:07 +0100 Subject: [PATCH 05/11] Documentation associative operator joining for add and multiply operations --- README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4054600f6..d8944f60e 100644 --- a/README.md +++ b/README.md @@ -4283,6 +4283,21 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ``` > :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. See the `concat` operator below. + + When you want to join a sequence of expressions with the `+` or `*` operator, use `joined(operator:)`: + + ```swift + // SELECT score + bonus + 1000 FROM player + let values = [ + scoreColumn, + bonusColumn, + 1000.databaseValue] + Player.select(values.joined(operator: .add)) + ``` + + Note in the example above how you concatenate raw values: `1000.databaseValue`. A plain `1000` would not compile. + + When the sequence is empty, `joined(operator: .add)` returns 0, and `joined(operator: .multiply)` returns 1. - `||` @@ -4306,7 +4321,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Player.filter(!verifiedColumn || scoreColumn < 1000) ``` - When you want to join a sequence of expressions with `AND` or `OR` operators, use `joined(operator:)`: + When you want to join a sequence of expressions with the `AND` or `OR` operator, use `joined(operator:)`: ```swift // SELECT * FROM player WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) From 95ddae7968b7b95265059dbd7ca84c8e1ed7c58f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 09:08:30 +0100 Subject: [PATCH 06/11] More tests for associative operators --- .../QueryInterfaceExpressionsTests.swift | 62 ++++++++++++++++++- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index dd33b276e..e721c2194 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -868,7 +868,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE -((-\"age\") + 1)") } - func testInfixMinusOperator() throws { + func testInfixSubtractOperator() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( @@ -891,7 +891,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE 1 - ((\"age\" > 1) AND (\"age\" IS NULL))") } - func testInfixPlusOperator() throws { + func testInfixAddOperator() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( @@ -914,6 +914,30 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE 1 + ((\"age\" > 1) AND (\"age\" IS NULL))") } + func testJoinedAddOperator() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([].joined(operator: .add))), + "SELECT 0 FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .add))), + "SELECT \"age\" + \"age\" FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .add))), + "SELECT \"age\" + 2 + \"age\" FROM \"readers\"") + + // Not flattened + XCTAssertEqual( + sql(dbQueue, tableRequest.select([ + [Col.age, 1.databaseValue].joined(operator: .add), + [2.databaseValue, Col.age].joined(operator: .add), + ].joined(operator: .add))), + "SELECT (\"age\" + 1) + (2 + \"age\") FROM \"readers\"") + } + func testInfixMultiplyOperator() throws { let dbQueue = try makeDatabaseQueue() @@ -934,6 +958,30 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE 2 * (\"age\" * \"age\")") } + func testJoinedMultiplyOperator() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([].joined(operator: .multiply))), + "SELECT 1 FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .multiply))), + "SELECT \"age\" * \"age\" FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .multiply))), + "SELECT \"age\" * 2 * \"age\" FROM \"readers\"") + + // Not flattened + XCTAssertEqual( + sql(dbQueue, tableRequest.select([ + [Col.age, 1.databaseValue].joined(operator: .multiply), + [2.databaseValue, Col.age].joined(operator: .multiply), + ].joined(operator: .multiply))), + "SELECT (\"age\" * 1) * (2 * \"age\") FROM \"readers\"") + } + func testInfixDivideOperator() throws { let dbQueue = try makeDatabaseQueue() @@ -1101,6 +1149,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { """ SELECT "name" || ' ' || "name" FROM "readers" """) + + // Flattened + XCTAssertEqual( + sql(dbQueue, tableRequest.select([ + [Col.name, "a".databaseValue].joined(operator: .concat), + ["b".databaseValue, Col.name].joined(operator: .concat), + ].joined(operator: .concat))), + """ + SELECT "name" || 'a' || 'b' || "name" FROM "readers" + """) } From 4bfab90750db5af9e2bbd06e4ff75d4c92a6d063 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 18:50:48 +0100 Subject: [PATCH 07/11] Restore and deprecate SQLLogicalBinaryOperator --- GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 5d4842d03..f772d78cb 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -309,6 +309,9 @@ public struct SQLAssociativeBinaryOperator: Hashable { } } +@available(*, deprecated, renamed: "SQLAssociativeBinaryOperator") +typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator + /// SQLExpressionBinary is an expression made of two expressions joined with a /// binary operator. /// From 25cf030498bdedf2e8ba20ea193db592633dc9ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 18:51:47 +0100 Subject: [PATCH 08/11] CHANGELOG --- CHANGELOG.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a48b6cbd..85ee7d253 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 4.x Releases @@ -61,9 +59,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - + +- [#683](https://github.com/groue/GRDB.swift/pull/683): String concatenation ## 4.8.1 From 2717b52e97513e323247d8fdfbb91f6e89d5f2da Mon Sep 17 00:00:00 2001 From: gjeck Date: Thu, 16 Jan 2020 09:59:18 -0800 Subject: [PATCH 09/11] Add cache for TableRecord.defaultDatabaseTableName Resolves cpu/memory impact from repeated calls by cacheing the name in a private global NSCache. --- GRDB/Record/TableRecord.swift | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index d7ea7513d..5871b2300 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -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() From ac215430c2bef5a0c945ee9ce9e7b322a1a597b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Jan 2020 19:48:29 +0100 Subject: [PATCH 10/11] CHANGELOG and thank you notice --- CHANGELOG.md | 6 ++---- README.md | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a48b6cbd..25bd85377 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 4.x Releases @@ -61,9 +59,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - + +- [#685](https://github.com/groue/GRDB.swift/pull/685) by [@gjeck](https://github.com/gjeck): Add cache for TableRecord.defaultDatabaseTableName ## 4.8.1 diff --git a/README.md b/README.md index 25db069ea..9c87a8ecd 100644 --- a/README.md +++ b/README.md @@ -8157,7 +8157,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. From 6b32c3aeecd810f68ec855c352c8602dbcd3ad4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 17 Jan 2020 07:40:42 +0100 Subject: [PATCH 11/11] v4.9.0 --- CHANGELOG.md | 12 ++++++++++++ GRDB.swift.podspec | 2 +- Makefile | 6 +++--- README.md | 42 +++++++++++++++++++++--------------------- Support/Info.plist | 2 +- 5 files changed, 38 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00aa23373..73024c9ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,14 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. + #### 4.x Releases +- `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) @@ -59,7 +62,16 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... + + + +## 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 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index a00f0aeb3..521b7ddbe 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -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.' diff --git a/Makefile b/Makefile index 97d64013a..331bb7629 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/README.md b/README.md index 53ad82bed..e0d31aa87 100644 --- a/README.md +++ b/README.md @@ -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+ • 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) @@ -4809,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 { @@ -4853,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 @@ -6387,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. @@ -6397,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 @@ -7501,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: diff --git a/Support/Info.plist b/Support/Info.plist index 99529bbd3..0a8545d54 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 4.8.1 + 4.9.0 CFBundleSignature ???? CFBundleVersion