From 9d5cb15380f4d08fb00eb00c9b67aead053a08ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 3 Mar 2021 20:03:56 +0100 Subject: [PATCH 01/60] SQLExpression documentation & cleanup --- GRDB/Fixit/GRDB-5.0.swift | 4 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 815 +++++++++++--------- 2 files changed, 455 insertions(+), 364 deletions(-) diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index a24fddeb6..bae59bcf2 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -226,8 +226,8 @@ extension SQLLiteral { public var arguments: StatementArguments { preconditionFailure() } } -@available(*, unavailable, renamed: "SQLAssociativeBinaryOperator") -typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator +@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator") +typealias SQLLogicalBinaryOperator = SQLExpression.AssociativeBinaryOperator extension SQLRequest { @available(*, unavailable, renamed: "RowDecoder") diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 7dcf92b75..582181cde 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -3,20 +3,27 @@ public struct SQLExpression { private var impl: Impl + /// The private implementation of the public `SQLExpression`. private enum Impl { - // MARK: Basic Expressions - - /// An unqualified database column. + /// A column. /// - /// "score" is a valid unqualified name. "player.score" is not. + /// id + /// name case column(String) - /// A qualified column in the database, as in + /// A qualified column. /// - /// SELECT player.score FROM player + /// player.id + /// player.name case qualifiedColumn(String, TableAlias) - /// A database value + /// A database value. + /// + /// NULL + /// 42 + /// 'Alice' + /// 3.14 + /// case databaseValue(DatabaseValue) /// A [row value](https://www.sqlite.org/rowvalue.html). @@ -30,130 +37,362 @@ public struct SQLExpression { /// A literal SQL expression case literal(SQLLiteral) - // MARK: Operators - - /// An expression that checks if a values is included in a range with the - /// `BETWEEN` operator. + /// The `BETWEEN` and `NOT BETWEEN` operators. /// - /// id BETWEEN 1 AND 3 + /// BETWEEN AND indirect case between( expression: SQLExpression, lowerBound: SQLExpression, upperBound: SQLExpression, isNegated: Bool) - /// An expression made of two expressions joined with a - /// binary operator. + /// A binary operator. /// - /// length * width - /// score >= 1000 - indirect case binary(SQLBinaryOperator, SQLExpression, SQLExpression) + /// * + /// <= + /// LIKE + indirect case binary(BinaryOperator, SQLExpression, SQLExpression) - /// An expression made of several expressions joined with an associative - /// binary operator. + /// An associative binary operator. /// - /// a AND b AND c - /// score + bonus + /// AND + /// + + /// /// - precondition: expressions.count > 1 - case associativeBinary(SQLAssociativeBinaryOperator, [SQLExpression]) + case associativeBinary(AssociativeBinaryOperator, [SQLExpression]) - /// An expression that checks the inclusion of a value in a collection - /// with the `IN` operator. + /// The `IN` and `NOT IN` operators. /// - /// id IN (1,2,3) - /// score IN (SELECT ...) + /// IN + /// NOT IN indirect case `in`(SQLExpression, SQLCollection, isNegated: Bool) - /// An expression made of an unary operator and an operand expression. + /// An unary operator. /// - /// -score - indirect case unary(SQLUnaryOperator, SQLExpression) + /// - + indirect case unary(UnaryOperator, SQLExpression) - /// An equality comparison + /// An equality comparison. /// - /// a = b - /// a <> b - /// a IS b - /// a IS NOT b - indirect case compare(SQLCompareOperator, SQLExpression, SQLExpression) + /// = + /// <> + /// IS + /// IS NOT + indirect case compare(EqualityOperator, SQLExpression, SQLExpression) - /// A full-text table match + /// A table full-text match. /// - /// SELECT * FROM document WHERE document MATCH 'query' + /// MATCH indirect case tableMatch(TableAlias, SQLExpression) - /// The logical not + /// A logical `NOT` operator. /// - /// NOT selected + /// NOT indirect case not(SQLExpression) - // MARK: Collations - - /// An expression tainted by an SQLite collation. + /// A collated expression. /// - /// SELECT * FROM player WHERE email = 'arthur@example.com' COLLATE NOCASE + /// COLLATE indirect case collated(SQLExpression, Database.CollationName) - // MARK: Functions - - /// A call to the SQL `COUNT(...)` function. + /// The `COUNT` function. /// - /// SELECT COUNT(name) FROM player - /// SELECT COUNT(*) FROM player + /// COUNT(*) + /// COUNT() indirect case count(SQLSelection) - /// A call to the SQL `COUNT(DISTINCT ...)` function. + /// The `COUNT(DISTINCT)` function. /// - /// SELECT COUNT(DISTINCT name) FROM player + /// COUNT(DISTINCT ) indirect case countDistinct(SQLExpression) - /// A function call + /// A function call. /// - /// LENGTH(name) + /// (, ...) case function(String, [SQLExpression]) - /// This expression helps generating `COUNT(...) = 0` or - /// `COUNT(...) > 0`. + /// An expression that checks for zero or positive values. /// - /// It has a specific behavior when negated with the `!` logical - /// operator, or compared with booleans. - /// - /// WHERE COUNT(DISTINCT player.id) == 0 - /// WHERE COUNT(DISTINCT player.id) > 0 + /// = 0 + /// > 0 indirect case isEmpty(SQLExpression, isNegated: Bool) - // MARK: Deferred - /// An expression that picks the fastest available primary key. /// /// It crashes for WITHOUT ROWID table with a multi-columns primary key. /// Future versions of GRDB may use [row values](https://www.sqlite.org/rowvalue.html). + /// + /// id + /// rowid + /// code case fastPrimaryKey - /// Qualified version of `.fastPrimaryKey` + /// A qualified "fast primary key" (see `.fastPrimaryKey`). + /// + /// player.id + /// document.rowid + /// country.code case qualifiedFastPrimaryKey(TableAlias) } + /// `BooleanTest` supports truthiness tests. + /// + /// See `SQLExpression.is(_:)` + enum BooleanTest { + /// Fuels `expression == true` + case `true` + + /// Fuels `expression == false` + case `false` + + /// Fuels `!expression` + case falsey + } + + /// `AssociativeBinaryOperator` is an associative binary operator, + /// such as `+`, `*`, `AND`, etc. + /// + /// Use it with the `joined(operator:)` method. For example: + /// + /// // SELECT score + bonus + 1000 FROM player + /// let values = [ + /// scoreColumn, + /// bonusColumn, + /// 1000.databaseValue] + /// Player.select(values.joined(operator: .add)) + public struct AssociativeBinaryOperator: Hashable { + /// The SQL operator + let sql: String + + /// The neutral value + let neutralValue: DatabaseValue + + /// If true, (a • b) • c is strictly equal to a • (b • c). + /// + /// `AND`, `OR`, `||` (concat) are stricly associative. + /// + /// `+` and `*` are not stricly associative when applied to floating + /// point values. + let isStrictlyAssociative: Bool + + /// If true, (a • b) is a bijective function of a, and a bijective + /// function of b. + /// + /// `+` and `||` (concat) are bijective. + /// + /// `AND`, `OR` and `*` are not. + let isBijective: Bool + + /// Creates a binary operator + init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool, bijective: Bool) { + self.sql = sql + self.neutralValue = neutralValue + self.isStrictlyAssociative = strictlyAssociative + self.isBijective = bijective + } + + /// The `+` binary operator + /// + /// For example: + /// + /// // score + bonus + /// [Column("score"), Column("bonus")].joined(operator: .add) + public static let add = AssociativeBinaryOperator( + sql: "+", + neutralValue: 0.databaseValue, + strictlyAssociative: false, + bijective: true) + + /// The `*` binary operator + /// + /// For example: + /// + /// // score * factor + /// [Column("score"), Column("factor")].joined(operator: .multiply) + public static let multiply = AssociativeBinaryOperator( + sql: "*", + neutralValue: 1.databaseValue, + strictlyAssociative: false, + bijective: false) + + /// The `AND` binary operator + /// + /// For example: + /// + /// // isBlue AND isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .and) + public static let and = AssociativeBinaryOperator( + sql: "AND", + neutralValue: true.databaseValue, + strictlyAssociative: true, + bijective: false) + + /// The `OR` binary operator + /// + /// For example: + /// + /// // isBlue OR isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .or) + public static let or = AssociativeBinaryOperator( + sql: "OR", + neutralValue: false.databaseValue, + strictlyAssociative: true, + bijective: false) + + /// The `||` string concatenation operator + /// + /// For example: + /// + /// // firstName || ' ' || lastName + /// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat) + public static let concat = AssociativeBinaryOperator( + sql: "||", + neutralValue: "".databaseValue, + strictlyAssociative: true, + bijective: true) + } + + /// `BinaryOperator` is an SQLite binary operator, such as `>`, `=`, etc. + /// + /// See also `AssociativeBinaryOperator` and `EqualityOperator`. + struct BinaryOperator: Hashable { + /// The SQL operator + let sql: String + + /// The SQL for the negated operator, if any + let negatedSQL: String? + + /// Creates a binary operator + /// + /// BinaryOperator("-") + /// BinaryOperator("LIKE", negated: "NOT LIKE") + init(_ sql: String, negated: String? = nil) { + self.sql = sql + self.negatedSQL = negated + } + + /// Returns the negated binary operator, if any + /// + /// let operator = BinaryOperator("IS", negated: "IS NOT") + /// operator.negated!.sql // IS NOT + var negated: BinaryOperator? { + guard let negatedSQL = negatedSQL else { + return nil + } + return BinaryOperator(negatedSQL, negated: sql) + } + + /// The `<` binary operator + static let lessThan = BinaryOperator("<") + + /// The `<=` binary operator + static let lessThanOrEqual = BinaryOperator("<=") + + /// The `>` binary operator + static let greaterThan = BinaryOperator(">") + + /// The `>=` binary operator + static let greaterThanOrEqual = BinaryOperator(">=") + + /// The `-` binary operator + static let subtract = BinaryOperator("-") + + /// The `/` binary operator + static let divide = BinaryOperator("/") + + /// The `LIKE` binary operator + static let like = BinaryOperator("LIKE", negated: "NOT LIKE") + + /// The `MATCH` binary operator + static let match = BinaryOperator("MATCH") + } + + /// `EqualityOperator` is an SQLite equality operator. + enum EqualityOperator: String { + case equal = "=" + case notEqual = "<>" + case `is` = "IS" + case isNot = "IS NOT" + + var negated: EqualityOperator { + switch self { + case .equal: return .notEqual + case .notEqual: return .equal + case .is: return .isNot + case .isNot: return .is + } + } + } + + /// `UnaryOperator` is a SQLite unary operator. + struct UnaryOperator: Hashable { + /// The SQL operator + let sql: String + + /// If true GRDB puts a white space between the operator and the operand. + let needsRightSpace: Bool + + /// Creates an unary operator + /// + /// UnaryOperator("~", needsRightSpace: false) + init(_ sql: String, needsRightSpace: Bool) { + self.sql = sql + self.needsRightSpace = needsRightSpace + } + + /// The `-` unary operator + static let minus = UnaryOperator("-", needsRightSpace: false) + } +} + +@available(*, deprecated, renamed: "SQLExpression.AssociativeBinaryOperator") +public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator + +// MARK: - Creating Expressions + +extension SQLExpression { + /// SQLite row values were shipped in SQLite 3.15: /// https://www.sqlite.org/releaselog/3_15_0.html static let rowValuesAreAvailable = (sqlite3_libversion_number() >= 3015000) + // MARK: Basic Expressions + + /// A column. + /// + /// id + /// name static func column(_ name: String) -> Self { self.init(impl: .column(name)) } + /// A qualified column. + /// + /// player.id + /// player.name static func qualifiedColumn(_ name: String, _ alias: TableAlias) -> Self { self.init(impl: .qualifiedColumn(name, alias)) } + /// A database value. + /// + /// NULL + /// 42 + /// 'Alice' + /// 3.14 + /// + /// + /// See also `SQLExpression.null` static func databaseValue(_ dbValue: DatabaseValue) -> Self { self.init(impl: .databaseValue(dbValue)) } + /// The `NULL` expression. static let null = SQLExpression.databaseValue(.null) - /// Returns nil if and only if expressions is empty + /// A [row value](https://www.sqlite.org/rowvalue.html). + /// + /// Returns nil if and only if expressions is empty. static func rowValue(_ expressions: [SQLExpression]) -> Self? { guard let expression = expressions.first else { return nil @@ -164,14 +403,21 @@ public struct SQLExpression { return self.init(impl: .rowValue(expressions)) } + /// A subquery expression. static func subquery(_ subquery: SQLSubquery) -> Self { self.init(impl: .subquery(subquery)) } + /// A literal SQL expression. static func literal(_ sqlLiteral: SQLLiteral) -> Self { self.init(impl: .literal(sqlLiteral)) } + // MARK: Operators + + /// The `BETWEEN` and `NOT BETWEEN` operators. + /// + /// BETWEEN AND static func between( expression: SQLExpression, lowerBound: SQLExpression, @@ -185,11 +431,31 @@ public struct SQLExpression { isNegated: isNegated)) } - static func binary(_ op: SQLBinaryOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { + /// A binary operator. + /// + /// * + /// <= + /// LIKE + static func binary(_ op: BinaryOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { self.init(impl: .binary(op, lhs, rhs)) } - static func associativeBinary(_ op: SQLAssociativeBinaryOperator, _ expressions: [SQLExpression]) -> Self { + /// An associative binary operator. + /// + /// AND + /// + + + /// + /// When the `expressions` array is empty, returns the neutral value of + /// the operator. + /// + /// When the `expressions` array contains a single expression, returns + /// this expression. + /// + /// When the operator is strictly associative, the expressions + /// are flattened: + /// + /// (a AND b) AND c -> a AND b AND c + static func associativeBinary(_ op: AssociativeBinaryOperator, _ expressions: [SQLExpression]) -> Self { // flatten when possible: a • (b • c) = a • b • c var expressions = expressions if op.isStrictlyAssociative { @@ -211,19 +477,40 @@ public struct SQLExpression { return self.init(impl: .associativeBinary(op, expressions)) } + /// The `IN` and `NOT IN` operators. + /// + /// IN + /// NOT IN + /// + /// See also `SQLCollection.contains(_:)`. static func `in`(_ expression: SQLExpression, _ collection: SQLCollection, isNegated: Bool = false) -> Self { self.init(impl: .in(expression, collection, isNegated: isNegated)) } - static func unary(_ op: SQLUnaryOperator, _ expression: SQLExpression) -> Self { + /// An unary operator. + /// + /// - + static func unary(_ op: UnaryOperator, _ expression: SQLExpression) -> Self { self.init(impl: .unary(op, expression)) } - static func compare(_ op: SQLCompareOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { + /// An equality comparison. + /// + /// = + /// <> + /// IS + /// IS NOT + /// + /// See also `SQLExpression.equal(_:_:)`. + static func compare(_ op: EqualityOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { self.init(impl: .compare(op, lhs, rhs)) } - /// "x = y" or "x IS NULL" + /// An equality comparison. Null database values are checked with `IS NULL`. + /// + /// = + /// IS NULL + /// IS NULL static func equal(_ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { switch (lhs.impl, rhs.impl) { case let (impl, .databaseValue(.null)), @@ -236,36 +523,76 @@ public struct SQLExpression { } } + /// A table full-text match. + /// + ///
MATCH static func tableMatch(_ alias: TableAlias, _ expression: SQLExpression) -> Self { self.init(impl: .tableMatch(alias, expression)) } + /// A logical `NOT` operator. + /// + /// NOT static func not(_ expression: SQLExpression) -> Self { self.init(impl: .not(expression)) } + /// A collated expression. + /// + /// COLLATE static func collated(_ expression: SQLExpression, _ collationName: Database.CollationName) -> Self { self.init(impl: .collated(expression, collationName)) } + // MARK: Functions + + /// The `COUNT` function. + /// + /// COUNT(*) + /// COUNT() static func count(_ selection: SQLSelection) -> Self { self.init(impl: .count(selection)) } + /// The `COUNT(DISTINCT)` function. + /// + /// COUNT(DISTINCT ) static func countDistinct(_ expression: SQLExpression) -> Self { self.init(impl: .countDistinct(expression)) } + /// A function call. + /// + /// (, ...) static func function(_ name: String, _ expressions: [SQLExpression]) -> Self { self.init(impl: .function(name, expressions)) } + /// An expression that checks for zero or positive values. + /// + /// = 0 + /// > 0 static func isEmpty(_ expression: SQLExpression, isNegated: Bool = false) -> Self { self.init(impl: .isEmpty(expression, isNegated: isNegated)) } + // MARK: Deferred + + /// An expression that picks the fastest available primary key. + /// + /// It crashes for WITHOUT ROWID table with a multi-columns primary key. + /// Future versions of GRDB may use [row values](https://www.sqlite.org/rowvalue.html). + /// + /// id + /// rowid + /// code static let fastPrimaryKey = SQLExpression(impl: .fastPrimaryKey) + /// A qualified "fast primary key" (see `SQLExpression.fastPrimaryKey`). + /// + /// player.id + /// document.rowid + /// country.code static func qualifiedFastPrimaryKey(_ alias: TableAlias) -> Self { self.init(impl: .qualifiedFastPrimaryKey(alias)) } @@ -279,9 +606,7 @@ extension SQLExpression { let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) return try sql(context) } -} - -extension SQLExpression { + /// If this expression is a table colum, returns the name of this column. /// /// When in doubt, returns nil. @@ -372,9 +697,7 @@ extension SQLExpression { return nil } } -} - -extension SQLExpression { + /// Returns an SQL string that represents the expression. /// /// - parameter context: An SQL generation context which accepts @@ -558,9 +881,7 @@ extension SQLExpression { .sql(context, wrappedInParenthesis: wrappedInParenthesis) } } -} - -extension SQLExpression { + /// Returns the columns that identify a unique row in the request /// /// When in doubt, returns an empty set. @@ -627,9 +948,7 @@ extension SQLExpression { return [] } } -} - -extension SQLExpression { + /// Returns the rowIds that identify rows in the request. A nil result means /// an unbounded list. /// @@ -752,9 +1071,7 @@ extension SQLExpression { return nil } } -} - -extension SQLExpression { + /// Performs a boolean test. /// /// We generally distinguish four boolean values: @@ -791,7 +1108,7 @@ extension SQLExpression { /// - `!association.isEmpty` -> `COUNT(child.id) > 0` /// - `association.isEmpty == true` -> `COUNT(child.id) = 0` /// - `association.isEmpty == false` -> `COUNT(child.id) > 0` - func `is`(_ test: SQLBooleanTest) -> SQLExpression { + func `is`(_ test: BooleanTest) -> SQLExpression { switch impl { case let .databaseValue(dbValue): switch dbValue.storage { @@ -910,9 +1227,7 @@ extension SQLExpression { } } } -} - -extension SQLExpression { + private static let knownPureFunctions = [ "ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL", "IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD", @@ -978,9 +1293,7 @@ extension SQLExpression { return false } } -} - -extension SQLExpression { + /// Returns a qualified expression func qualified(with alias: TableAlias) -> SQLExpression { switch impl { @@ -1051,9 +1364,7 @@ extension SQLExpression { return .qualifiedFastPrimaryKey(alias) } } -} - -extension SQLExpression { + /// Returns true if the expression is an aggregate. /// /// When in doubt, returns false. @@ -1116,7 +1427,7 @@ extension SQLExpression { } else if name == "GROUP_CONCAT" && (expressions.count == 1 || expressions.count == 2) { return true } else { - // TODO: return true if all arguments are aggregates? + // Return true if all arguments are aggregates? return false } @@ -1126,270 +1437,6 @@ extension SQLExpression { } } -extension Sequence where Element: SQLSpecificExpressible { - /// Returns an expression by joining all elements with an associative SQL - /// binary operator. - /// - /// For example: - /// - /// // SELECT * FROM player - /// // WHERE (registered - /// // AND (score >= 1000) - /// // AND (name IS NOT NULL)) - /// let conditions = [ - /// Column("registered"), - /// Column("score") >= 1000, - /// Column("name") != nil] - /// Player.filter(conditions.joined(operator: .and)) - /// - /// When the sequence is empty, `joined(operator:)` returns the neutral - /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, - /// false for `.or`, and true for `.and`. - public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { - .associativeBinary(`operator`, map(\.sqlExpression)) - } -} - -extension Sequence where Element == SQLSpecificExpressible { - /// Returns an expression by joining all elements with an associative SQL - /// binary operator. - /// - /// For example: - /// - /// // SELECT * FROM player - /// // WHERE (registered - /// // AND (score >= 1000) - /// // AND (name IS NOT NULL)) - /// let conditions = [ - /// Column("registered"), - /// Column("score") >= 1000, - /// Column("name") != nil] - /// Player.filter(conditions.joined(operator: .and)) - /// - /// When the sequence is empty, `joined(operator:)` returns the neutral - /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, - /// false for `.or`, and true for `.and`. - public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { - .associativeBinary(`operator`, map(\.sqlExpression)) - } -} - -// MARK: - SQLBooleanTest - -/// `SQLBooleanTest` supports boolean tests. -/// -/// See `SQLExpression.is(_:)` -enum SQLBooleanTest { - /// Fuels `expression == true` - case `true` - - /// Fuels `expression == false` - case `false` - - /// Fuels `!expression` - case falsey -} - -// MARK: - SQLAssociativeBinaryOperator - -/// SQLAssociativeBinaryOperator is an SQLite associative binary operator, such -/// as `+`, `*`, `AND`, etc. -/// -/// Use it with the `joined(operator:)` method. For example: -/// -/// // SELECT score + bonus + 1000 FROM player -/// let values = [ -/// scoreColumn, -/// bonusColumn, -/// 1000.databaseValue] -/// Player.select(values.joined(operator: .add)) -public struct SQLAssociativeBinaryOperator: Hashable { - /// The SQL operator - let sql: String - - /// The neutral value - let neutralValue: DatabaseValue - - /// If true, (a • b) • c is strictly equal to a • (b • c). - /// - /// `AND`, `OR`, `||` (concat) are stricly associative. - /// - /// `+` and `*` are not stricly associative when applied to floating - /// point values. - let isStrictlyAssociative: Bool - - /// If true, (a • b) is a bijective function of a, and a bijective - /// function of b. - /// - /// `+` and `||` (concat) are bijective. - /// - /// `AND`, `OR` and `*` are not. - let isBijective: Bool - - /// Creates a binary operator - init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool, bijective: Bool) { - self.sql = sql - self.neutralValue = neutralValue - self.isStrictlyAssociative = strictlyAssociative - self.isBijective = bijective - } - - /// The `+` binary operator - /// - /// For example: - /// - /// // score + bonus - /// [Column("score"), Column("bonus")].joined(operator: .add) - public static let add = SQLAssociativeBinaryOperator( - sql: "+", - neutralValue: 0.databaseValue, - strictlyAssociative: false, - bijective: true) - - /// The `*` binary operator - /// - /// For example: - /// - /// // score * factor - /// [Column("score"), Column("factor")].joined(operator: .multiply) - public static let multiply = SQLAssociativeBinaryOperator( - sql: "*", - neutralValue: 1.databaseValue, - strictlyAssociative: false, - bijective: false) - - /// The `AND` binary operator - /// - /// For example: - /// - /// // isBlue AND isTall - /// [Column("isBlue"), Column("isTall")].joined(operator: .and) - public static let and = SQLAssociativeBinaryOperator( - sql: "AND", - neutralValue: true.databaseValue, - strictlyAssociative: true, - bijective: false) - - /// The `OR` binary operator - /// - /// For example: - /// - /// // isBlue OR isTall - /// [Column("isBlue"), Column("isTall")].joined(operator: .or) - public static let or = SQLAssociativeBinaryOperator( - sql: "OR", - neutralValue: false.databaseValue, - strictlyAssociative: true, - bijective: false) - - /// The `||` string concatenation operator - /// - /// For example: - /// - /// // firstName || ' ' || lastName - /// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat) - public static let concat = SQLAssociativeBinaryOperator( - sql: "||", - neutralValue: "".databaseValue, - strictlyAssociative: true, - bijective: true) -} - -// MARK: - SQLBinaryOperator - -/// SQLBinaryOperator is an SQLite binary operator, such as >, =, etc. -struct SQLBinaryOperator: Hashable { - /// The SQL operator - let sql: String - - /// The SQL for the negated operator, if any - let negatedSQL: String? - - /// Creates a binary operator - /// - /// SQLBinaryOperator("-") - /// SQLBinaryOperator("LIKE", negated: "NOT LIKE") - init(_ sql: String, negated: String? = nil) { - self.sql = sql - self.negatedSQL = negated - } - - /// Returns the negated binary operator, if any - /// - /// let operator = SQLBinaryOperator("IS", negated: "IS NOT") - /// operator.negated!.sql // IS NOT - var negated: SQLBinaryOperator? { - guard let negatedSQL = negatedSQL else { - return nil - } - return SQLBinaryOperator(negatedSQL, negated: sql) - } - - /// The `<` binary operator - static let lessThan = SQLBinaryOperator("<") - - /// The `<=` binary operator - static let lessThanOrEqual = SQLBinaryOperator("<=") - - /// The `>` binary operator - static let greaterThan = SQLBinaryOperator(">") - - /// The `>=` binary operator - static let greaterThanOrEqual = SQLBinaryOperator(">=") - - /// The `-` binary operator - static let subtract = SQLBinaryOperator("-") - - /// The `/` binary operator - static let divide = SQLBinaryOperator("/") - - /// The `LIKE` binary operator - static let like = SQLBinaryOperator("LIKE", negated: "NOT LIKE") - - /// The `MATCH` binary operator - static let match = SQLBinaryOperator("MATCH") -} - -// MARK: - SQLCompareOperator - -enum SQLCompareOperator: String { - case equal = "=" - case notEqual = "<>" - case `is` = "IS" - case isNot = "IS NOT" - - var negated: SQLCompareOperator { - switch self { - case .equal: return .notEqual - case .notEqual: return .equal - case .is: return .isNot - case .isNot: return .is - } - } -} - -// MARK: - SQLUnaryOperator - -/// SQLUnaryOperator is a SQLite unary operator. -struct SQLUnaryOperator: Hashable { - /// The SQL operator - let sql: String - - /// If true GRDB puts a white space between the operator and the operand. - let needsRightSpace: Bool - - /// Creates an unary operator - /// - /// SQLUnaryOperator("~", needsRightSpace: false) - init(_ sql: String, needsRightSpace: Bool) { - self.sql = sql - self.needsRightSpace = needsRightSpace - } - - /// The `-` unary operator - static let minus = SQLUnaryOperator("-", needsRightSpace: false) -} - // MARK: - SQLExpressible /// `SQLExpressible` is the protocol for all types that can be used as an @@ -1450,9 +1497,56 @@ extension SQLExpression: SQLSpecificExpressible { public var sqlExpression: SQLExpression { self } } +extension Sequence where Element: SQLSpecificExpressible { + /// Returns an expression by joining all elements with an associative SQL + /// binary operator. + /// + /// For example: + /// + /// // SELECT * FROM player + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >= 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// + /// When the sequence is empty, `joined(operator:)` returns the neutral + /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, + /// false for `.or`, and true for `.and`. + public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression { + .associativeBinary(`operator`, map(\.sqlExpression)) + } +} + +extension Sequence where Element == SQLSpecificExpressible { + /// Returns an expression by joining all elements with an associative SQL + /// binary operator. + /// + /// For example: + /// + /// // SELECT * FROM player + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >= 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// + /// When the sequence is empty, `joined(operator:)` returns the neutral + /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, + /// false for `.or`, and true for `.and`. + public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression { + .associativeBinary(`operator`, map(\.sqlExpression)) + } +} + // MARK: - SQL Ordering Support -/// :nodoc: extension SQLSpecificExpressible { /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() @@ -1502,7 +1596,6 @@ extension SQLSpecificExpressible { #endif } - // MARK: - SQL Selection Support /// :nodoc: @@ -1544,10 +1637,8 @@ extension SQLSpecificExpressible { } } - // MARK: - SQL Collations Support -/// :nodoc: extension SQLSpecificExpressible { /// Returns a collated expression. From 174766925a8709959bd821cb4b47061cc788728d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 3 Mar 2021 20:04:08 +0100 Subject: [PATCH 02/60] Remove warning --- Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index 2555a1c44..05e1e586c 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -1,7 +1,6 @@ import XCTest import GRDB -#warning("TODO: test decoding error") // A type that adopts DatabaseValueConvertible and StatementColumnConvertible private struct Fetched: DatabaseValueConvertible, StatementColumnConvertible, Hashable { let int: Int From bac7b6b0e574d49ce8e6cb1ee3fca90967f0d5cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Mar 2021 13:25:25 +0100 Subject: [PATCH 03/60] Refactor function calls and make it possible to express other DISTINCT aggregates than COUNT: SUM(DISTINCT ...), etc. --- GRDB/Core/DatabaseFunction.swift | 12 ++ .../Association/AssociationAggregate.swift | 16 +-- GRDB/QueryInterface/SQL/SQLExpression.swift | 117 +++++++++--------- GRDB/QueryInterface/SQL/SQLFunctions.swift | 23 +--- GRDB/QueryInterface/SQL/SQLQuery.swift | 4 +- GRDB/QueryInterface/SQL/SQLSelection.swift | 64 ++++++---- 6 files changed, 127 insertions(+), 109 deletions(-) diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 12d847823..fb137e7c4 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -107,6 +107,18 @@ public final class DatabaseFunction: Hashable { self.kind = .aggregate { Aggregate() } } + /// Returns an SQL expression that applies the function. + /// + /// See https://github.com/groue/GRDB.swift/#sql-functions + public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { + switch kind { + case .aggregate: + return .function(name, arguments.map(\.sqlExpression)) + case .function: + return .aggregate(name, arguments.map(\.sqlExpression)) + } + } + /// Calls sqlite3_create_function_v2 /// See https://sqlite.org/c3ref/create_function.html func install(in db: Database) { diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index fde5a0685..6163a2cf2 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -38,8 +38,8 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { - let expression = SQLExpression.countDistinct(.fastPrimaryKey) - return makeAggregate(expression).forKey("\(key.singularizedName)Count") + makeAggregate(.countDistinct(.fastPrimaryKey)) + .forKey("\(key.singularizedName)Count") } /// Creates an aggregate that is true if there exists no associated records. @@ -58,8 +58,8 @@ extension AssociationToMany { /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { - let expression = SQLExpression.isEmpty(.countDistinct(.fastPrimaryKey)) - return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") + makeAggregate(.isEmpty(.countDistinct(.fastPrimaryKey))) + .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } /// Creates an aggregate which evaluate to the average value of the given @@ -80,7 +80,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) public func average(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.function("AVG", [expression.sqlExpression])) + let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -107,7 +107,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) public func max(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.function("MAX", [expression.sqlExpression])) + let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -134,7 +134,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) public func min(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.function("MIN", [expression.sqlExpression])) + let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -161,7 +161,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) public func sum(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(.function("SUM", [expression.sqlExpression])) + let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 582181cde..203e604d8 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -95,21 +95,14 @@ public struct SQLExpression { /// COLLATE indirect case collated(SQLExpression, Database.CollationName) - /// The `COUNT` function. - /// - /// COUNT(*) - /// COUNT() - indirect case count(SQLSelection) - - /// The `COUNT(DISTINCT)` function. - /// - /// COUNT(DISTINCT ) - indirect case countDistinct(SQLExpression) + /// The `COUNT(*)` expression. + case countAll /// A function call. /// /// (, ...) - case function(String, [SQLExpression]) + /// (DISTINCT ) + case function(String, aggregate: Bool, distinct: Bool, arguments: [SQLExpression]) /// An expression that checks for zero or positive values. /// @@ -148,7 +141,7 @@ public struct SQLExpression { /// Fuels `!expression` case falsey } - + /// `AssociativeBinaryOperator` is an associative binary operator, /// such as `+`, `*`, `AND`, etc. /// @@ -251,7 +244,7 @@ public struct SQLExpression { strictlyAssociative: true, bijective: true) } - + /// `BinaryOperator` is an SQLite binary operator, such as `>`, `=`, etc. /// /// See also `AssociativeBinaryOperator` and `EqualityOperator`. @@ -323,7 +316,7 @@ public struct SQLExpression { } } } - + /// `UnaryOperator` is a SQLite unary operator. struct UnaryOperator: Hashable { /// The SQL operator @@ -546,26 +539,48 @@ extension SQLExpression { // MARK: Functions + /// The `COUNT(*)` expression. + static let countAll = SQLExpression(impl: .countAll) + /// The `COUNT` function. /// - /// COUNT(*) - /// COUNT() - static func count(_ selection: SQLSelection) -> Self { - self.init(impl: .count(selection)) + /// COUNT() + static func count(_ expression: SQLExpression) -> Self { + .aggregate("COUNT", [expression]) } /// The `COUNT(DISTINCT)` function. /// /// COUNT(DISTINCT ) static func countDistinct(_ expression: SQLExpression) -> Self { - self.init(impl: .countDistinct(expression)) + .distinctAggregate("COUNT", expression) } /// A function call. /// /// (, ...) - static func function(_ name: String, _ expressions: [SQLExpression]) -> Self { - self.init(impl: .function(name, expressions)) + /// + /// - warning: for aggregate functions, call one of: + /// - `SQLExpression.aggregate(_:_:)`, + /// - `SQLExpression.distinctAggregate(_:_:)`, + /// - `SQLExpression.countDistinct(_:)` + /// - `SQLExpression.countAll`. + static func function(_ name: String, _ arguments: [SQLExpression]) -> Self { + self.init(impl: .function(name, aggregate: false, distinct: false, arguments: arguments)) + } + + /// An aggregate function call. + /// + /// (, ...) + static func aggregate(_ name: String, _ arguments: [SQLExpression]) -> Self { + self.init(impl: .function(name, aggregate: true, distinct: false, arguments: arguments)) + } + + /// A distinct aggregate function call. + /// + /// (DISTINCT ) + static func distinctAggregate(_ name: String, _ argument: SQLExpression) -> Self { + self.init(impl: .function(name, aggregate: true, distinct: true, arguments: [argument])) } /// An expression that checks for zero or positive values. @@ -674,15 +689,15 @@ extension SQLExpression { case let .collated(expression, _): return try expression.column(db, for: alias, acceptsBijection: acceptsBijection) - case let .function(name, expressions): + case let .function(name, aggregate: false, distinct: false, arguments: arguments): guard acceptsBijection else { return nil } let name = name.uppercased() - if ["HEX", "QUOTE"].contains(name) && expressions.count == 1 { - return try expressions[0].column(db, for: alias, acceptsBijection: acceptsBijection) - } else if name == "IFNULL" && expressions.count == 2 && expressions[1].isConstantInRequest { - return try expressions[0].column(db, for: alias, acceptsBijection: acceptsBijection) + if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 { + return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection) + } else if name == "IFNULL" && arguments.count == 2 && arguments[1].isConstantInRequest { + return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection) } else { return nil } @@ -844,16 +859,15 @@ extension SQLExpression { } return resultSQL - case let .count(selection): - return try "COUNT(\(selection.countedSQL(context)))" + case .countAll: + return "COUNT(*)" - case let .countDistinct(expression): - return try "COUNT(DISTINCT \(expression.sql(context)))" - - case let .function(name, expressions): + case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments): + assert(!distinct || aggregate, "distinct requires aggregate") + assert(!distinct || arguments.count == 1, "distinct requires a single argument") return try name - + "(" - + expressions.map { try $0.sql(context) }.joined(separator: ", ") + + (distinct ? "(DISTINCT " : "(") + + arguments.map { try $0.sql(context) }.joined(separator: ", ") + ")" case let .isEmpty(expression, isNegated: isNegated): @@ -1279,15 +1293,15 @@ extension SQLExpression { let .collated(expression, _): return expression.isConstantInRequest - case let .function(name, expressions): + case let .function(name, aggregate: false, distinct: false, arguments: arguments): let name = name.uppercased() - guard ((name == "MAX" || name == "MIN") && expressions.count > 1) + guard ((name == "MAX" || name == "MIN") && arguments.count > 1) || Self.knownPureFunctions.contains(name) else { return false // Don't know - assume not constant } - return expressions.allSatisfy(\.isConstantInRequest) + return arguments.allSatisfy(\.isConstantInRequest) default: return false @@ -1348,14 +1362,12 @@ extension SQLExpression { case let .collated(expression, collationName): return .collated(expression.qualified(with: alias), collationName) - case let .count(selection): - return .count(selection.qualified(with: alias)) + case .countAll: + return .countAll - case let .countDistinct(expression): - return .countDistinct(expression.qualified(with: alias)) - - case let .function(name, expressions): - return .function(name, expressions.map { $0.qualified(with: alias) }) + case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments): + return SQLExpression(impl: .function(name, aggregate: aggregate, distinct: distinct, + arguments: arguments.map { $0.qualified(with: alias) })) case let .isEmpty(expression, isNegated: isNegated): return .isEmpty(expression.qualified(with: alias), isNegated: isNegated) @@ -1414,23 +1426,10 @@ extension SQLExpression { return false - case .count, - .countDistinct: + case .countAll, + .function(_, aggregate: true, distinct: _, arguments: _): return true - case let .function(name, expressions): - let name = name.uppercased() - if ["MIN", "MAX"].contains(name) && expressions.count == 1 { - return true - } else if ["AVG", "COUNT", "SUM", "TOTAL"].contains(name) && expressions.count == 1 { - return true - } else if name == "GROUP_CONCAT" && (expressions.count == 1 || expressions.count == 2) { - return true - } else { - // Return true if all arguments are aggregates? - return false - } - default: return false } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index f350abeef..7c39dd23a 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -1,15 +1,3 @@ -// MARK: - Custom Functions - -extension DatabaseFunction { - /// Returns an SQL expression that applies the function. - /// - /// See https://github.com/groue/GRDB.swift/#sql-functions - public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { - .function(name, arguments.map(\.sqlExpression)) - } -} - - // MARK: - ABS(...) /// Returns an expression that evaluates the `ABS` SQL function. @@ -28,18 +16,19 @@ public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { /// // AVG(length) /// average(Column("length")) public func average(_ value: SQLSpecificExpressible) -> SQLExpression { - .function("AVG", [value.sqlExpression]) + .aggregate("AVG", [value.sqlExpression]) } // MARK: - COUNT(...) +// TODO: deprecate, replace with count(expression) /// Returns an expression that evaluates the `COUNT` SQL function. /// /// // COUNT(email) /// count(Column("email")) public func count(_ counted: SQLSelectable) -> SQLExpression { - .count(counted.sqlSelection) + counted.sqlSelection.countExpression } @@ -83,7 +72,7 @@ public func length(_ value: SQLSpecificExpressible) -> SQLExpression { /// // MAX(score) /// max(Column("score")) public func max(_ value: SQLSpecificExpressible) -> SQLExpression { - .function("MAX", [value.sqlExpression]) + .aggregate("MAX", [value.sqlExpression]) } @@ -94,7 +83,7 @@ public func max(_ value: SQLSpecificExpressible) -> SQLExpression { /// // MIN(score) /// min(Column("score")) public func min(_ value: SQLSpecificExpressible) -> SQLExpression { - .function("MIN", [value.sqlExpression]) + .aggregate("MIN", [value.sqlExpression]) } @@ -105,7 +94,7 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression { /// // SUM(amount) /// sum(Column("amount")) public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { - .function("SUM", [value.sqlExpression]) + .aggregate("SUM", [value.sqlExpression]) } diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index c069475b9..83fe3a7b3 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -123,7 +123,7 @@ extension SQLQuery { countQuery.isDistinct = false switch count { case .all: - countQuery = countQuery.select(.count(.allColumns)) + countQuery = countQuery.select(.countAll) case .distinct(let expression): countQuery = countQuery.select(.countDistinct(expression)) } @@ -138,7 +138,7 @@ extension SQLQuery { // SELECT expr1, expr2, ... FROM tableName ... // -> // SELECT COUNT(*) FROM tableName ... - let countQuery = unordered().select(SQLExpression.count(.allColumns)) + let countQuery = unordered().select(.countAll) return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! } } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index f919460d9..e4bbfb781 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -3,15 +3,12 @@ public struct SQLSelection { private var impl: Impl + /// The private implementation of the public `SQLSelection`. private enum Impl { - /// All columns - /// - /// SELECT * + /// All columns: `*` case allColumns - /// All columns from a table - /// - /// SELECT player.* + /// All columns, qualified: `player.*` case qualifiedAllColumns(TableAlias) // As long as the CTE is embedded here, the following request will fail @@ -28,48 +25,55 @@ public struct SQLSelection { // - prefer `annotated(with:)` when she wants to extend the selection. // // TODO: Make `cteRequestOrAssociation.select(AllColumns())` possible. - /// All columns from a common table expression + /// All columns of a common table expression case allCTEColumns(SQLCTE) + /// All columns of a common table expression, qualified case qualifiedAllCTEColumns(SQLCTE, TableAlias) /// An expression - /// - /// SELECT id - /// SELECT LENGTH(name) case expression(SQLExpression) /// An aliased expression /// - /// SELECT score + bonud AS totalScore + /// AS name case aliasedExpression(SQLExpression, String) /// A literal SQL selection case literal(SQLLiteral) } + /// All columns: `*` static let allColumns = SQLSelection(impl: .allColumns) + /// All columns, qualified: `player.*` static func qualifiedAllColumns(_ alias: TableAlias) -> Self { self.init(impl: .qualifiedAllColumns(alias)) } + /// All columns of a common table expression static func allCTEColumns(_ cte: SQLCTE) -> Self { self.init(impl: .allCTEColumns(cte)) } + /// All columns of a common table expression, qualified static func qualifiedAllCTEColumns(_ cte: SQLCTE, _ alias: TableAlias) -> Self { self.init(impl: .qualifiedAllCTEColumns(cte, alias)) } + /// An expression static func expression(_ expression: SQLExpression) -> Self { self.init(impl: .expression(expression)) } + /// An aliased expression + /// + /// AS name static func aliasedExpression(_ expression: SQLExpression, _ name: String) -> Self { self.init(impl: .aliasedExpression(expression, name)) } + /// A literal SQL selection static func literal(_ sqlLiteral: SQLLiteral) -> Self { self.init(impl: .literal(sqlLiteral)) } @@ -104,9 +108,29 @@ extension SQLSelection { """) } } -} - -extension SQLSelection { + + /// Support for `count(selection)`. + /// TODO: deprecate `count(selection)`, and get rid of this property. + var countExpression: SQLExpression { + switch impl { + case .allColumns, + .allCTEColumns: + return .countAll + + case .qualifiedAllColumns, + .qualifiedAllCTEColumns: + // COUNT(player.*) is not valid SQL + fatalError("Uncountable selection") + + case let .expression(expression), + let .aliasedExpression(expression, _): + return .count(expression) + + case let .literal(sqlLiteral): + return .count(sqlLiteral.sqlExpression) + } + } + /// If the selection can be counted, return how to count it. func count(distinct: Bool) -> SQLCount? { switch impl { @@ -182,9 +206,7 @@ extension SQLSelection { """) } } -} - -extension SQLSelection { + /// Returns the SQL that feeds the selection of a `SELECT` statement. /// /// For example: @@ -221,9 +243,7 @@ extension SQLSelection { return try sqlLiteral.sql(context) } } -} - -extension SQLSelection { + /// Returns true if the selection is an aggregate. /// /// When in doubt, returns false. @@ -252,9 +272,7 @@ extension SQLSelection { return false } } -} - -extension SQLSelection { + /// Returns a qualified selection func qualified(with alias: TableAlias) -> SQLSelection { switch impl { From 48b6faa45e607879c52fac76d4d5942c229ae6bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Mar 2021 13:25:52 +0100 Subject: [PATCH 04/60] Improve documentation of Configuration.prepareDatabase --- GRDB/Core/Configuration.swift | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 4a50a426b..f0ae2fd82 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -108,6 +108,9 @@ public struct Configuration { /// The function argument is run when an SQLite connection is opened, /// before the connection is made available for database access methods. /// + /// This method can be called several times. The preparation functions are + /// run in the same order. + /// /// For example: /// /// var config = Configuration() @@ -115,8 +118,21 @@ public struct Configuration { /// try db.execute(sql: "PRAGMA kdf_iter = 10000") /// } /// - /// This method can be called several times. The setup functions are run in - /// the same order. + /// When you use a `DatabasePool`, preparation functions are called for + /// the writer connection and all reader connections. You can distinguish + /// them by querying `db.configuration.readonly`: + /// + /// var config = Configuration() + /// config.prepareDatabase { db in + /// if db.configuration.readonly { + /// // reader connection + /// } else { + /// // writer connection + /// } + /// } + /// + /// On newly created databases, `DatabasePool` the WAL mode is activated + /// after the preparation functions have run. public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) { setups.append(setup) } From 424df6dee3576f36f0760da57877b203a7988374 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Mar 2021 13:25:59 +0100 Subject: [PATCH 05/60] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 93c61b103..74f3179cd 100644 --- a/TODO.md +++ b/TODO.md @@ -15,6 +15,7 @@ ## Features +- [ ] See if SQLITE_FCNTL_DATA_VERSION could help working around the lack of snapshots in order to avoid double initial fetch of ValueObservation - [ ] Grab all FTS tokens in a string - [ ] GRDB 6: decoding errors - [ ] GRDB 6: conflict resolution in persistence methods From 7623a96034c302a772d83ff29121a007db8ee910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Mar 2021 13:34:27 +0100 Subject: [PATCH 06/60] Failing test for #931 --- Tests/GRDBTests/DatabasePoolTests.swift | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Tests/GRDBTests/DatabasePoolTests.swift b/Tests/GRDBTests/DatabasePoolTests.swift index a4817b50b..b2c3b35f6 100644 --- a/Tests/GRDBTests/DatabasePoolTests.swift +++ b/Tests/GRDBTests/DatabasePoolTests.swift @@ -52,4 +52,27 @@ class DatabasePoolTests: GRDBTestCase { XCTAssertFalse(fm.fileExists(atPath: path + "-wal")) XCTAssertFalse(fm.fileExists(atPath: path + "-shm")) } + + // Regression test + func testIssue931() throws { + dbConfiguration.prepareDatabase { db in + var flag: CInt = 0 + let code = withUnsafeMutablePointer(to: &flag) { flagP in + sqlite3_file_control(db.sqliteConnection, nil, SQLITE_FCNTL_PERSIST_WAL, flagP) + } + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: ResultCode(rawValue: code)) + } + } + let dbQueue = try makeDatabaseQueue() + + var migrator = DatabaseMigrator() + migrator.registerMigration("v1", migrate: { _ in }) + migrator.eraseDatabaseOnSchemaChange = true + try migrator.migrate(dbQueue) + + // Trigger #931: the migrator creates a temporary database and + // calls `sqlite3_file_control` as part of the preparation function. + try migrator.migrate(dbQueue) + } } From 8be0976bd1fee48523d28bc6813c151975c56be8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Mar 2021 14:01:56 +0100 Subject: [PATCH 07/60] Fix #931 --- GRDB/Migration/DatabaseMigrator.swift | 55 ++++++++++++++++++--------- 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index f4b3e471e..5de3d6f81 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -1,3 +1,5 @@ +import Foundation + /// A DatabaseMigrator registers and applies database migrations. /// /// Migrations are named blocks of SQL statements that are guaranteed to be @@ -130,27 +132,46 @@ public struct DatabaseMigrator { return .commit } - if let lastAppliedIdentifier = migrations.lazy - .map({ $0.identifier }) + if let lastAppliedIdentifier = migrations + .map(\.identifier) .last(where: { appliedIdentifiers.contains($0) }) { - // Database has been partially migrated. + // Some migrations were already applied. // - // Create a temporary witness database (on disk, just in case - // migrations would involve a lot of data). - var witnessConfiguration = writer.configuration - witnessConfiguration.targetQueue = nil // Avoid deadlocks - witnessConfiguration.label = "GRDB.DatabaseMigrator.temporary" - let witness = try DatabaseQueue(path: "", configuration: witnessConfiguration) + // Let's migrate a temporary database up to the same + // level, and compare the database schemas. If they + // differ, we'll erase the database. + let tmpSchema: SchemaInfo = try { + // Make sure the temporary database is configured + // just as the migrated database + var tmpConfig = writer.configuration + tmpConfig.targetQueue = nil // Avoid deadlocks + tmpConfig.label = "GRDB.DatabaseMigrator.temporary" + + // Create the temporary database on disk, just in + // case migrations would involve a lot of data. + // + // SQLite supports temporary on-disk databases, but + // those are not guaranteed to accept the + // preparation functions provided by the user. + // + // See https://github.com/groue/GRDB.swift/issues/931 + // for an issue created by such databases. + // + // So let's create a "regular" temporary database: + let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory()) + .appendingPathComponent(ProcessInfo().globallyUniqueString) + defer { + try? FileManager().removeItem(at: tmpURL) + } + let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig) + return try tmpDatabase.writeWithoutTransaction { db in + try runMigrations(db, upTo: lastAppliedIdentifier) + return try db.schema() + } + }() - // Grab schema of migrated witness database - let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in - try runMigrations(db, upTo: lastAppliedIdentifier) - return try db.schema() - } - - // Erase database if we detect a schema change - if try db.schema() != witnessSchema { + if try db.schema() != tmpSchema { needsErase = true return .commit } From 37279dfad2aaed17d51d87f9c07b13e26c27373b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Mar 2021 14:20:11 +0100 Subject: [PATCH 08/60] CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e17f9527..48c778900 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases +- [Development Branch](#development-branch) - `5.5.x` Releases - [5.5.0](#550) - `5.4.x` Releases - [5.4.0](#540) - `5.3.x` Releases - [5.3.0](#530) @@ -71,6 +72,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... +## Development Branch + +- **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases + ## 5.5.0 Released March 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0) From 5400217bb63f7955cba9dcc32a92ee21e3469ef0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Mar 2021 15:21:31 +0100 Subject: [PATCH 09/60] ReceiveValuesOnSubscription forwards cancellation Fixes #932 --- GRDB/Utils/ReceiveValuesOn.swift | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/GRDB/Utils/ReceiveValuesOn.swift b/GRDB/Utils/ReceiveValuesOn.swift index fa06c35b7..00d2ac1eb 100644 --- a/GRDB/Utils/ReceiveValuesOn.swift +++ b/GRDB/Utils/ReceiveValuesOn.swift @@ -119,8 +119,22 @@ where subscription.request(currentDemand) } - case .waitingForRequest, .subscribed, .finished: + case .waitingForRequest, .subscribed: preconditionFailure() + + case .finished: + // We receive the upstream subscription requested by + // `upstream.receive(subscriber: self)` above. + // + // But self has been cancelled since, so let's cancel this + // upstream subscription that has turned purposeless. + // + // This cancellation avoids the bug described in + // https://github.com/groue/GRDB.swift/pull/932 + // TODO: write a regression test. + sideEffect = { + subscription.cancel() + } } } } From 3eb17fdbb754f9c44dea112d8347871a9f63fe79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 12:11:50 +0100 Subject: [PATCH 10/60] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48c778900..123824552 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,6 +75,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Development Branch - **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases +- **Fixed**: [#934](https://github.com/groue/GRDB.swift/pull/934): Fix a crash in the ValueObservation publisher ## 5.5.0 From 4b5a6b503a7c9e58101d0af4355b024d0b80b071 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 13:12:28 +0100 Subject: [PATCH 11/60] TODO --- TODO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index 74f3179cd..e03a53130 100644 --- a/TODO.md +++ b/TODO.md @@ -15,7 +15,7 @@ ## Features -- [ ] See if SQLITE_FCNTL_DATA_VERSION could help working around the lack of snapshots in order to avoid double initial fetch of ValueObservation +- [X] See if SQLITE_FCNTL_DATA_VERSION could help working around the lack of snapshots in order to avoid double initial fetch of ValueObservation. Result: no, it does not look it returns values that are comparable between two distinct SQLite connections (from the initial reader, and from the writer thhat starts the observation) - [ ] Grab all FTS tokens in a string - [ ] GRDB 6: decoding errors - [ ] GRDB 6: conflict resolution in persistence methods From 37faf0a1fd1702458fc3b1f38e67a5992213580c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 14:20:28 +0100 Subject: [PATCH 12/60] Upgrade obsolete documentation --- GRDB/QueryInterface/SQL/SQLExpression.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 203e604d8..55ac559b4 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1106,8 +1106,7 @@ extension SQLExpression { /// optimize queries with indices on boolean columns and expressions. /// See https://github.com/groue/GRDB.swift/issues/816 /// - /// This method is a customization point, so that some specific expressions - /// can produce idiomatic SQL. + /// Some specific expressions can produce idiomatic SQL. /// /// For example, the `like(_)` expression: /// From f49fab0cff015bd3f55db0d4c19b48d929cbdfcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 14:37:53 +0100 Subject: [PATCH 13/60] Merge SQLQuery into SQLRelation --- GRDB.xcodeproj/project.pbxproj | 10 -- .../Request/CommonTableExpression.swift | 2 +- .../Request/QueryInterfaceRequest.swift | 85 ++++----- GRDB/QueryInterface/SQL/SQLQuery.swift | 164 ------------------ GRDB/QueryInterface/SQL/SQLRelation.swift | 163 +++++++++++++---- GRDB/QueryInterface/SQL/SQLSubquery.swift | 16 +- .../SQLGeneration/SQLQueryGenerator.swift | 162 ++++++++--------- GRDBCustom.xcodeproj/project.pbxproj | 6 - 8 files changed, 247 insertions(+), 361 deletions(-) delete mode 100644 GRDB/QueryInterface/SQL/SQLQuery.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 85df6e3db..96ce7b050 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -829,9 +829,6 @@ 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; }; 56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; }; 56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; }; - 56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; }; - 56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; }; - 56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; }; 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -953,7 +950,6 @@ AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; }; AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */; }; - AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; }; AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; }; AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; @@ -1565,7 +1561,6 @@ 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; 56D91AA82205F2F000770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = ""; }; - 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -2042,7 +2037,6 @@ 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */, 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */, 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */, - 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */, 56D91AA12205E03700770D8D /* SQLRelation.swift */, 568ECA8925D7013000B71526 /* SQLSelection.swift */, 568ECB1725D9161500B71526 /* SQLSubquery.swift */, @@ -2866,7 +2860,6 @@ 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, 5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, - 56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, 564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, @@ -3070,7 +3063,6 @@ 56AE64132229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */, - 56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, 5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, @@ -3655,7 +3647,6 @@ AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */, AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */, AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */, - AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */, AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */, AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */, AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */, @@ -3946,7 +3937,6 @@ files = ( 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */, 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, - 56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, 5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 8ace50580..b83650e4f 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -444,7 +444,7 @@ extension QueryInterfaceRequest { /// - parameter cte: A common table expression. /// - returns: A request. public func with(_ cte: CommonTableExpression) -> Self { - with(\.query.ctes[cte.tableName], cte.cte) + with(\.relation.ctes[cte.tableName], cte.cte) } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 631894e2a..7aabf8770 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -29,24 +29,18 @@ /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct QueryInterfaceRequest { - var query: SQLQuery -} - -extension QueryInterfaceRequest { - init(relation: SQLRelation) { - self.init(query: SQLQuery(relation: relation)) - } + var relation: SQLRelation } extension QueryInterfaceRequest: Refinable { } extension QueryInterfaceRequest: FetchRequest { public var sqlSubquery: SQLSubquery { - .query(query) + .relation(relation) } public func fetchCount(_ db: Database) throws -> Int { - try query.fetchCount(db) + try relation.fetchCount(db) } public func makePreparedRequest( @@ -54,13 +48,13 @@ extension QueryInterfaceRequest: FetchRequest { forSingleResult singleResult: Bool = false) throws -> PreparedRequest { - let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult) + let generator = SQLQueryGenerator(relation: relation, forSingleResult: singleResult) var preparedRequest = try generator.makePreparedRequest(db) - let associations = query.relation.prefetchedAssociations + let associations = relation.prefetchedAssociations if associations.isEmpty == false { // Eager loading of prefetched associations - preparedRequest = preparedRequest.with(\.supplementaryFetch) { [query] db, rows in - try prefetch(db, associations: associations, from: query, into: rows) + preparedRequest = preparedRequest.with(\.supplementaryFetch) { [relation] db, rows in + try prefetch(db, associations: associations, from: relation, into: rows) } } return preparedRequest @@ -83,7 +77,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select { db in [Column("id")] } /// .select { db in [Column("email")] } public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { - map(\.query) { $0.select { try selection($0).map(\.sqlSelection) } } + map(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } } } /// Creates a request which selects *selection*, and fetches values of @@ -174,7 +168,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select([Column("id"), Column("email")]) /// .annotated(with: { db in [Column("name")] }) public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { - map(\.query) { $0.annotated { try selection($0).map(\.sqlSelection) } } + map(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } } } } @@ -186,7 +180,7 @@ extension QueryInterfaceRequest: FilteredRequest { /// var request = Player.all() /// request = request.filter { db in true } public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - map(\.query) { $0.filter { try predicate($0).sqlExpression } } + map(\.relation) { $0.filter { try predicate($0).sqlExpression } } } } @@ -205,7 +199,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// .reversed() /// .order{ _ in [Column("name")] } public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { - map(\.query) { $0.order { try orderings($0).map(\.sqlOrdering) } } + map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } } } /// Creates a request that reverses applied orderings. @@ -220,7 +214,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// var request = Player.all() /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { - map(\.query) { $0.reversed() } + map(\.relation) { $0.reversed() } } /// Creates a request without any ordering. @@ -229,20 +223,20 @@ extension QueryInterfaceRequest: OrderedRequest { /// var request = Player.all().order(Column("name")) /// request = request.unordered() public func unordered() -> QueryInterfaceRequest { - map(\.query) { $0.unordered() } + map(\.relation) { $0.unordered() } } } extension QueryInterfaceRequest: AggregatingRequest { /// Creates a request grouped according to *expressions promise*. public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { - map(\.query) { $0.group { try expressions($0).map(\.sqlExpression) } } + map(\.relation) { $0.group { try expressions($0).map(\.sqlExpression) } } } /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - map(\.query) { $0.having { try predicate($0).sqlExpression } } + map(\.relation) { $0.having { try predicate($0).sqlExpression } } } } @@ -250,27 +244,27 @@ extension QueryInterfaceRequest: AggregatingRequest { extension QueryInterfaceRequest: _JoinableRequest { /// :nodoc: public func _including(all association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.query) { $0._including(all: association) } + map(\.relation) { $0._including(all: association) } } /// :nodoc: public func _including(optional association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.query) { $0._including(optional: association) } + map(\.relation) { $0._including(optional: association) } } /// :nodoc: public func _including(required association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.query) { $0._including(required: association) } + map(\.relation) { $0._including(required: association) } } /// :nodoc: public func _joining(optional association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.query) { $0._joining(optional: association) } + map(\.relation) { $0._joining(optional: association) } } /// :nodoc: public func _joining(required association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.query) { $0._joining(required: association) } + map(\.relation) { $0._joining(required: association) } } } @@ -279,7 +273,7 @@ extension QueryInterfaceRequest: JoinableRequest { } extension QueryInterfaceRequest: TableRequest { /// :nodoc: public var databaseTableName: String { - query.relation.source.tableName + relation.source.tableName } /// Creates a request that allows you to define expressions that target @@ -300,7 +294,7 @@ extension QueryInterfaceRequest: TableRequest { /// .aliased(playerAlias) /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - map(\.query) { $0.aliased(alias) } + map(\.relation) { $0.aliased(alias) } } } @@ -317,7 +311,7 @@ extension QueryInterfaceRequest { /// var request = Player.select(Column("name")) /// request = request.distinct() public func distinct() -> QueryInterfaceRequest { - map(\.query) { $0.distinct() } + with(\.relation.isDistinct, true) } /// Creates a request which fetches *limit* rows, starting at *offset*. @@ -328,7 +322,7 @@ extension QueryInterfaceRequest { /// /// Any previous limit is replaced. public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { - map(\.query) { $0.limit(limit, offset: offset) } + with(\.relation.limit, SQLLimit(limit: limit, offset: offset)) } /// Creates a request bound to type RowDecoder. @@ -345,7 +339,7 @@ extension QueryInterfaceRequest { /// - parameter type: The fetched type RowDecoder /// - returns: A request bound to type RowDecoder. public func asRequest(of type: RowDecoder.Type) -> QueryInterfaceRequest { - QueryInterfaceRequest(query: query) + QueryInterfaceRequest(relation: relation) } } @@ -410,7 +404,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @discardableResult public func deleteAll(_ db: Database) throws -> Int { - try SQLQueryGenerator(query: query).makeDeleteStatement(db).execute() + try SQLQueryGenerator(relation: relation).makeDeleteStatement(db).execute() return db.changesCount } } @@ -440,7 +434,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { _ assignments: [ColumnAssignment]) throws -> Int { let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate - guard let updateStatement = try SQLQueryGenerator(query: query).makeUpdateStatement( + guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement( db, conflictResolution: conflictResolution, assignments: assignments) else @@ -582,7 +576,7 @@ public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign private func prefetch( _ db: Database, associations: [_SQLAssociation], - from originQuery: SQLQuery, + from originRelation: SQLRelation, into originRows: [Row]) throws { guard let firstOriginRow = originRows.first else { @@ -598,7 +592,7 @@ private func prefetch( fatalError("Not implemented: prefetch association without any foreign key") case let .foreignKey(pivotForeignKey): - let originTable = originQuery.relation.source.tableName + let originTable = originRelation.source.tableName let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable) let pivotColumns = pivotMapping.map(\.right) let leftColumns = pivotMapping.map(\.left) @@ -647,17 +641,16 @@ private func prefetch( // FROM country // JOIN passport ON passport.countryCode = country.code // AND (passport.a, passport.b) IN grdb_base - let originQuery = originQuery.map(\.relation) { baseRelation in - // Ordering and including(all:) children are - // useless, and we only need pivoting columns: - baseRelation - .unordered() - .removingChildrenForPrefetchedAssociations() - .selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection }) - } + // + // In the CTE, ordering and including(all:) children are + // useless, and we only need to select pivot columns: + let originRelation = originRelation + .unordered() + .removingChildrenForPrefetchedAssociations() + .selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection }) let originCTE = CommonTableExpression( named: "grdb_base", - request: SQLSubquery.query(originQuery)) + request: SQLSubquery.relation(originRelation)) let pivotRowValue = SQLExpression.rowValue(pivotColumns.map(SQLExpression.column))! let pivotFilter = originCTE.contains(pivotRowValue) @@ -785,9 +778,7 @@ throws -> DatabaseRegion .map(\.pivot.relation) { $0.filter(pivotFilter) } .destinationRelation() - let prefetchQuery = SQLQuery(relation: prefetchRelation) - - return try SQLQueryGenerator(query: prefetchQuery) + return try SQLQueryGenerator(relation: prefetchRelation) .makeSelectStatement(db) .databaseRegion // contains region of nested associations } diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift deleted file mode 100644 index 83fe3a7b3..000000000 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ /dev/null @@ -1,164 +0,0 @@ -/// SQLQuery is a representation of an SQL query. -/// -/// See SQLQueryGenerator for actual SQL generation. -struct SQLQuery { - var relation: SQLRelation - var isDistinct: Bool = false - var groupPromise: DatabasePromise<[SQLExpression]>? - var havingExpressionPromise: DatabasePromise = DatabasePromise(value: nil) - var limit: SQLLimit? - var ctes: OrderedDictionary = [:] -} - -extension SQLQuery: Refinable { - func distinct() -> Self { - with(\.isDistinct, true) - } - - func limit(_ limit: Int, offset: Int? = nil) -> Self { - with(\.limit, SQLLimit(limit: limit, offset: offset)) - } - - func aliased(_ alias: TableAlias) -> Self { - map(\.relation) { $0.aliased(alias) } - } -} - -extension SQLQuery { - func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self { - map(\.relation) { $0.select(selection) } - } - - // Convenience - func select(_ expressions: SQLExpression...) -> Self { - select { _ in expressions.map { .expression($0) } } - } - - func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self { - map(\.relation) { $0.annotated(with: selection) } - } -} - -extension SQLQuery { - func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { - map(\.relation) { $0.filter(predicate) } - } -} - -extension SQLQuery { - func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self { - map(\.relation) { $0.order(orderings) } - } - - func reversed() -> Self { - map(\.relation) { $0.reversed() } - } - - func unordered() -> Self { - map(\.relation) { $0.unordered() } - } -} - -extension SQLQuery { - func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self { - with(\.groupPromise, DatabasePromise(expressions)) - } - - func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { - map(\.havingExpressionPromise) { promise in - DatabasePromise { db in - if let filter = try promise.resolve(db) { - return try filter && predicate(db) - } else { - return try predicate(db) - } - } - } - } -} - -extension SQLQuery{ - func _including(all association: _SQLAssociation) -> Self { - map(\.relation) { $0._including(all: association) } - } - - func _including(optional association: _SQLAssociation) -> Self { - map(\.relation) { $0._including(optional: association) } - } - - func _including(required association: _SQLAssociation) -> Self { - map(\.relation) { $0._including(required: association) } - } - - func _joining(optional association: _SQLAssociation) -> Self { - map(\.relation) { $0._joining(optional: association) } - } - - func _joining(required association: _SQLAssociation) -> Self { - map(\.relation) { $0._joining(required: association) } - } -} - -extension SQLQuery { - func fetchCount(_ db: Database) throws -> Int { - guard groupPromise == nil && limit == nil && ctes.isEmpty else { - // SELECT ... GROUP BY ... - // SELECT ... LIMIT ... - // WITH ... SELECT ... - return try fetchTrivialCount(db) - } - - if relation.children.contains(where: { $0.value.impactsParentCount }) { // TODO: not tested - // SELECT ... FROM ... JOIN ... - return try fetchTrivialCount(db) - } - - let selection = try relation.selectionPromise.resolve(db) - GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") - if selection.count == 1 { - guard let count = selection[0].count(distinct: isDistinct) else { - return try fetchTrivialCount(db) - } - var countQuery = self.unordered() - countQuery.isDistinct = false - switch count { - case .all: - countQuery = countQuery.select(.countAll) - case .distinct(let expression): - countQuery = countQuery.select(.countDistinct(expression)) - } - return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! - } else { - // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... - - guard !isDistinct else { - return try fetchTrivialCount(db) - } - - // SELECT expr1, expr2, ... FROM tableName ... - // -> - // SELECT COUNT(*) FROM tableName ... - let countQuery = unordered().select(.countAll) - return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! - } - } - - // SELECT COUNT(*) FROM (self) - func fetchTrivialCount(_ db: Database) throws -> Int { - let countRequest: SQLRequest = "SELECT COUNT(*) FROM (\(SQLSubquery.query(unordered())))" - return try countRequest.fetchOne(db)! - } -} - -struct SQLLimit { - let limit: Int - let offset: Int? - - var sql: String { - if let offset = offset { - return "\(limit) OFFSET \(offset)" - } else { - return "\(limit)" - } - } -} diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index edccdff43..1206dff22 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -2,23 +2,20 @@ /// terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology), /// is "a set of tuples sharing the same attributes; a set of columns and rows." /// -/// SQLRelation is defined with a selection, a source table of query, and an -/// eventual filter and ordering. -/// -/// SELECT ... FROM ... WHERE ... ORDER BY ... -/// | | | | -/// | | | • ordering -/// | | • filter -/// | • source -/// • selection -/// -/// Other SQL clauses such as GROUP BY, LIMIT are defined one level up, in the -/// `SQLQuery` type. +/// WITH ... -- ctes +/// SELECT ... -- selectionPromise +/// FROM ... -- source +/// JOIN ... -- children +/// WHERE ... -- filterPromise +/// GROUP BY ... -- groupPromise +/// HAVING ... -- havingExpressionPromise +/// ORDER BY ... -- ordering +/// LIMIT ... -- limit /// /// ## Promises /// -/// Selection, filter, and ordering are "promises" which are resolved when a -/// database connection is available. This is how we can implement requests such +/// Most relation elements are "promises" which are resolved when a database +/// connection is available. This is how we can implement requests such /// as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`: both need a /// database connection in order to introspect the primary key. For example: /// @@ -29,7 +26,7 @@ /// /// ## Children /// -/// Relations may also have children. A child is a link to another relation, and +/// Relations have children. A child is a link to another relation, and /// provide support for joins and prefetched relations. /// /// Relations and their children constitute a tree of relations, which the user @@ -143,30 +140,19 @@ struct SQLRelation { } var source: SQLSource - var selectionPromise: DatabasePromise<[SQLSelection]> = DatabasePromise(value: []) + var selectionPromise: DatabasePromise<[SQLSelection]> var filterPromise: DatabasePromise = DatabasePromise(value: nil) var ordering: SQLRelation.Ordering = SQLRelation.Ordering() var children: OrderedDictionary = [:] - /// All prefetched associations (`including(all:)`), recursively - var prefetchedAssociations: [_SQLAssociation] { - children.flatMap { key, child -> [_SQLAssociation] in - switch child.kind { - case .all: - return [child.makeAssociationForKey(key)] - case .oneOptional, .oneRequired, .bridge: - return child.relation.prefetchedAssociations.map { association in - // Remove redundant pivot child - let pivotKey = association.pivot.keyName - let child = child.map(\.relation) { relation in - assert(relation.children[pivotKey] != nil) - return relation.removingChild(forKey: pivotKey) - } - return association.through(child.makeAssociationForKey(key)) - } - } - } - } + // Properties below MUST NOT be used when joining to-one associations + #warning("TODO: make sure a precondition failure prevents those to be defined on to-one associations") + #warning("TODO: merge") + var isDistinct: Bool = false + var groupPromise: DatabasePromise<[SQLExpression]>? + var havingExpressionPromise: DatabasePromise? + var limit: SQLLimit? + var ctes: OrderedDictionary = [:] } extension SQLRelation { @@ -192,6 +178,11 @@ extension SQLRelation: Refinable { select { _ in selection } } + // Convenience + func select(_ expressions: SQLExpression...) -> Self { + select { _ in expressions.map { .expression($0) } } + } + /// Removes all selections from chidren func selectOnly(_ selection: [SQLSelection]) -> Self { self @@ -251,12 +242,48 @@ extension SQLRelation: Refinable { } } + func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self { + with(\.groupPromise, DatabasePromise(expressions)) + } + + func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { + map(\.havingExpressionPromise) { promise in + DatabasePromise { db in + if let filter = try promise?.resolve(db) { + return try filter && predicate(db) + } else { + return try predicate(db) + } + } + } + } + func aliased(_ alias: TableAlias) -> Self { map(\.source) { $0.aliased(alias) } } } extension SQLRelation { + /// All prefetched associations (`including(all:)`), recursively + var prefetchedAssociations: [_SQLAssociation] { + children.flatMap { key, child -> [_SQLAssociation] in + switch child.kind { + case .all: + return [child.makeAssociationForKey(key)] + case .oneOptional, .oneRequired, .bridge: + return child.relation.prefetchedAssociations.map { association in + // Remove redundant pivot child + let pivotKey = association.pivot.keyName + let child = child.map(\.relation) { relation in + assert(relation.children[pivotKey] != nil) + return relation.removingChild(forKey: pivotKey) + } + return association.through(child.makeAssociationForKey(key)) + } + } + } + } + /// Returns a relation extended with an association. /// /// This method provides support for public joining methods such @@ -466,6 +493,72 @@ extension SQLRelation { } } +extension SQLRelation { + func fetchCount(_ db: Database) throws -> Int { + guard groupPromise == nil && limit == nil && ctes.isEmpty else { + // SELECT ... GROUP BY ... + // SELECT ... LIMIT ... + // WITH ... SELECT ... + return try fetchTrivialCount(db) + } + + if children.contains(where: { $0.value.impactsParentCount }) { // TODO: not tested + // SELECT ... FROM ... JOIN ... + return try fetchTrivialCount(db) + } + + let selection = try selectionPromise.resolve(db) + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") + if selection.count == 1 { + guard let count = selection[0].count(distinct: isDistinct) else { + return try fetchTrivialCount(db) + } + var countRelation = self.unordered() + countRelation.isDistinct = false + switch count { + case .all: + countRelation = countRelation.select(.countAll) + case .distinct(let expression): + countRelation = countRelation.select(.countDistinct(expression)) + } + return try QueryInterfaceRequest(relation: countRelation).fetchOne(db)! + } else { + // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... + + guard !isDistinct else { + return try fetchTrivialCount(db) + } + + // SELECT expr1, expr2, ... FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + let countRelation = unordered().select(.countAll) + return try QueryInterfaceRequest(relation: countRelation).fetchOne(db)! + } + } + + // SELECT COUNT(*) FROM (self) + private func fetchTrivialCount(_ db: Database) throws -> Int { + let countRequest: SQLRequest = "SELECT COUNT(*) FROM (\(SQLSubquery.relation(unordered())))" + return try countRequest.fetchOne(db)! + } +} + +// MARK: - SQLLimit + +struct SQLLimit { + let limit: Int + let offset: Int? + + var sql: String { + if let offset = offset { + return "\(limit) OFFSET \(offset)" + } else { + return "\(limit)" + } + } +} + // MARK: - SQLSource struct SQLSource { diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index c0d474158..cc5403c46 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -6,16 +6,16 @@ public struct SQLSubquery { /// A literal SQL query case literal(SQLLiteral) - /// A query interface query - case query(SQLQuery) + /// A query interface relation + case relation(SQLRelation) } static func literal(_ sqlLiteral: SQLLiteral) -> Self { self.init(impl: .literal(sqlLiteral)) } - static func query(_ query: SQLQuery) -> Self { - self.init(impl: .query(query)) + static func relation(_ relation: SQLRelation) -> Self { + self.init(impl: .relation(relation)) } } @@ -48,8 +48,8 @@ extension SQLSubquery { let statement = try db.cachedSelectStatement(sql: sql) return statement.columnCount - case let .query(query): - return try SQLQueryGenerator(query: query).columnsCount(db) + case let .relation(relation): + return try SQLQueryGenerator(relation: relation).columnsCount(db) } } } @@ -77,8 +77,8 @@ extension SQLSubquery { case let .literal(sqlLiteral): return try sqlLiteral.sql(context) - case let .query(query): - return try SQLQueryGenerator(query: query, forSingleResult: false).requestSQL(context) + case let .relation(relation): + return try SQLQueryGenerator(relation: relation).requestSQL(context) } } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 8ec497706..61bee4b80 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -1,12 +1,7 @@ /// SQLQueryGenerator is able to generate an SQL SELECT query. struct SQLQueryGenerator: Refinable { fileprivate private(set) var relation: SQLQualifiedRelation - private let isDistinct: Bool - private let groupPromise: DatabasePromise<[SQLExpression]>? - private let havingExpressionPromise: DatabasePromise - private let limit: SQLLimit? private let singleResult: Bool - private let ctes: OrderedDictionary // For database region private let prefetchedAssociations: [_SQLAssociation] @@ -15,49 +10,12 @@ struct SQLQueryGenerator: Refinable { /// - parameter singleResult: A hint as to whether the query should be /// optimized for a single result. init( - query: SQLQuery, + relation: SQLRelation, forSingleResult singleResult: Bool = false) { - // To generate SQL, we need a "qualified" relation, where all tables, - // expressions, etc, are identified with table aliases. - // - // All those aliases let us disambiguate tables at the SQL level, and - // prefix columns names. For example, the following request... - // - // Book.filter(Column("kind") == Book.Kind.novel) - // .including(optional: Book.author) - // .including(optional: Book.translator) - // .annotated(with: Book.awards.count) - // - // ... generates the following SQL, where all identifiers are correctly - // disambiguated and qualified: - // - // SELECT book.*, person1.*, person2.*, COUNT(DISTINCT award.id) - // FROM book - // LEFT JOIN person person1 ON person1.id = book.authorId - // LEFT JOIN person person2 ON person2.id = book.translatorId - // LEFT JOIN award ON award.bookId = book.id - // GROUP BY book.id - // WHERE book.kind = 'novel' - relation = SQLQualifiedRelation(query.relation) - - // Qualify group expressions and having clause with the relation alias. - // - // This turns `GROUP BY id` INTO `GROUP BY book.id`, and - // `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`. - let sourceAlias = relation.source.alias - groupPromise = query.groupPromise?.map { - $0.map { $0.qualified(with: sourceAlias) } - } - havingExpressionPromise = query.havingExpressionPromise.map { - $0.map { $0.qualified(with: sourceAlias) } - } - - limit = query.limit - isDistinct = query.isDistinct + self.relation = SQLQualifiedRelation(relation) + self.prefetchedAssociations = relation.prefetchedAssociations self.singleResult = singleResult - prefetchedAssociations = query.relation.prefetchedAssociations - ctes = query.ctes } func requestSQL(_ context: SQLGenerationContext) throws -> String { @@ -66,7 +24,7 @@ struct SQLQueryGenerator: Refinable { var sql = try commonTableExpressionsPrefix(context) sql += "SELECT" - if isDistinct { + if relation.isDistinct { sql += " DISTINCT" } @@ -94,7 +52,7 @@ struct SQLQueryGenerator: Refinable { sql += try filter.sql(context) } - let groupExpressions = try groupPromise?.resolve(context.db) ?? [] + let groupExpressions = try relation.groupPromise?.resolve(context.db) ?? [] if !groupExpressions.isEmpty { sql += " GROUP BY " sql += try groupExpressions @@ -102,7 +60,7 @@ struct SQLQueryGenerator: Refinable { .joined(separator: ", ") } - if let havingExpression = try havingExpressionPromise.resolve(context.db) { + if let havingExpression = try relation.havingExpressionPromise?.resolve(context.db) { sql += " HAVING " sql += try havingExpression.sql(context) } @@ -115,8 +73,8 @@ struct SQLQueryGenerator: Refinable { .joined(separator: ", ") } - var limit = self.limit - if try singleResult && !expectsSingleResult( + var limit = relation.limit + if try limit == nil && singleResult && !expectsSingleResult( context.db, selection: selection, filter: filter, @@ -260,7 +218,7 @@ struct SQLQueryGenerator: Refinable { sql += try filter.sql(context) } - if let limit = limit { + if let limit = relation.limit { let orderings = try relation.ordering.resolve(db) if !orderings.isEmpty { sql += " ORDER BY " @@ -346,7 +304,7 @@ struct SQLQueryGenerator: Refinable { sql += try filter.sql(context) } - if let limit = limit { + if let limit = relation.limit { let orderings = try relation.ordering.resolve(db) if !orderings.isEmpty { sql += " ORDER BY " @@ -416,15 +374,15 @@ struct SQLQueryGenerator: Refinable { } private func commonTableExpressionsPrefix(_ context: SQLGenerationContext) throws -> String { - if ctes.isEmpty { + if relation.ctes.isEmpty { return "" } var sql = "WITH " - if ctes.values.contains(where: \.isRecursive) { + if relation.ctes.values.contains(where: \.isRecursive) { sql += "RECURSIVE " } - sql += try ctes + sql += try relation.ctes .map { tableName, cte in var columnsSQL = "" if let columns = cte.columns, !columns.isEmpty { @@ -457,7 +415,7 @@ struct SQLQueryGenerator: Refinable { private func grouping(_ db: Database) throws -> GroupingInfo { // Empty group clause: no grouping // SELECT * FROM player - guard let groupExpressions = try groupPromise?.resolve(db), groupExpressions.isEmpty == false else { + guard let groupExpressions = try relation.groupPromise?.resolve(db), groupExpressions.isEmpty == false else { return .none } @@ -518,15 +476,40 @@ struct SQLQueryGenerator: Refinable { } } -/// A "qualified" relation, where all tables are identified with a table alias. +/// To generate SQL, we need a "qualified" relation, where all tables, +/// expressions, etc, are qualified with table aliases. /// -/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... -/// | | | | | -/// | | | | • ordering -/// | | | • filterPromise -/// | | • joins -/// | • source -/// • selectionPromise +/// All those aliases let us disambiguate tables at the SQL level, and +/// prefix columns names. For example, the following request... +/// +/// Book.filter(Column("kind") == Book.Kind.novel) +/// .including(optional: Book.author) +/// .including(optional: Book.translator) +/// .annotated(with: Book.awards.count) +/// +/// ... generates the following SQL, where all identifiers are correctly +/// disambiguated and qualified: +/// +/// SELECT book.*, person1.*, person2.*, COUNT(DISTINCT award.id) +/// FROM book +/// LEFT JOIN person person1 ON person1.id = book.authorId +/// LEFT JOIN person person2 ON person2.id = book.translatorId +/// LEFT JOIN award ON award.bookId = book.id +/// GROUP BY book.id +/// WHERE book.kind = 'novel' +/// +/// `SQLQualifiedRelation` contains the following information: +/// +/// WITH ... -- ctes +/// SELECT ... -- selectionPromise +/// FROM ... -- source +/// JOIN ... -- joins +/// WHERE ... -- filterPromise +/// GROUP BY ... -- groupPromise +/// HAVING ... -- havingExpressionPromise +/// ORDER BY ... -- ordering +/// LIMIT ... -- limit + private struct SQLQualifiedRelation { /// All aliases, including aliases of joined relations var allAliases: [TableAlias] { @@ -536,20 +519,15 @@ private struct SQLQualifiedRelation { } /// The source - /// - /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... - /// | - /// • source let source: SQLQualifiedSource /// The selection from source, not including selection of joined relations private var sourceSelectionPromise: DatabasePromise<[SQLSelection]> + #warning("TODO: decide if selectOnly() should reset this flag") + let isDistinct: Bool + /// The full selection, including selection of joined relations - /// - /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... - /// | - /// • selectionPromise var selectionPromise: DatabasePromise<[SQLSelection]> { DatabasePromise { db in let selection = try self.sourceSelectionPromise.resolve(db) @@ -560,34 +538,24 @@ private struct SQLQualifiedRelation { } } - /// The filtering clause - /// - /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... - /// | - /// • filterPromise let filterPromise: DatabasePromise /// The ordering of source, not including ordering of joined relations private let sourceOrdering: SQLRelation.Ordering /// The full ordering, including orderings of joined relations - /// - /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... - /// | - /// • ordering var ordering: SQLRelation.Ordering { joins.reduce(sourceOrdering) { $0.appending($1.value.relation.ordering) } } - /// The joins - /// - /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... - /// | - /// • joins private(set) var joins: OrderedDictionary - + let groupPromise: DatabasePromise<[SQLExpression]>? + let havingExpressionPromise: DatabasePromise? + let limit: SQLLimit? + let ctes: OrderedDictionary + init(_ relation: SQLRelation) { // Qualify the source, so that it be disambiguated with an SQL alias // if needed (when a select query uses the same table several times). @@ -596,9 +564,8 @@ private struct SQLQualifiedRelation { // this SQLQualifiedRelation generates SQL. source = SQLQualifiedSource(relation.source) - // Qualify all joins, selection, filter, and ordering, so that all - // identifiers can be correctly disambiguated and qualified. - joins = relation.children.compactMapValues { SQLQualifiedJoin($0) } + // Qualify all selection, filter, etc, so that all identifiers + // can be correctly disambiguated and qualified. let sourceAlias = source.alias sourceSelectionPromise = relation.selectionPromise.map { $0.map { $0.qualified(with: sourceAlias) } @@ -607,6 +574,21 @@ private struct SQLQualifiedRelation { $0.map { $0.qualified(with: sourceAlias) } } sourceOrdering = relation.ordering.qualified(with: sourceAlias) + groupPromise = relation.groupPromise?.map { + $0.map { $0.qualified(with: sourceAlias) } + } + havingExpressionPromise = relation.havingExpressionPromise.map { + $0.map { $0.qualified(with: sourceAlias) } + } + + // Turns relation children into joins. `including(all:)` children are + // discarded on the way. + joins = relation.children.compactMapValues { SQLQualifiedJoin($0) } + + // Copy other flags + limit = relation.limit + isDistinct = relation.isDistinct + ctes = relation.ctes } /// See SQLQueryGenerator.rowAdapter(_:) diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index fe3bea6c9..4bd666e13 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -256,8 +256,6 @@ 5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */; }; 5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; }; 5656A8982295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; }; - 5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; }; - 5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; }; 5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; }; 5656A8A82295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; }; 5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; @@ -907,7 +905,6 @@ 5656A84A2295BD56001FF3FF /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = ""; }; 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = ""; }; 5656A84E2295BD56001FF3FF /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; - 5656A8502295BD56001FF3FF /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = ""; }; 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; @@ -1549,7 +1546,6 @@ 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */, 5656A8462295BD56001FF3FF /* SQLOperators.swift */, 5656A8452295BD56001FF3FF /* SQLOrdering.swift */, - 5656A8502295BD56001FF3FF /* SQLQuery.swift */, 5656A84E2295BD56001FF3FF /* SQLRelation.swift */, 568ECB0C25D904CA00B71526 /* SQLSelection.swift */, 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */, @@ -2355,7 +2351,6 @@ F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5656A8702295BD56001FF3FF /* Association.swift in Sources */, 563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */, - 5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5656A85C2295BD56001FF3FF /* TableDefinition.swift in Sources */, 5656A8562295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, @@ -2713,7 +2708,6 @@ F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5656A86F2295BD56001FF3FF /* Association.swift in Sources */, 563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */, - 5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */, 5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, From ea6a052b732b045db571440897b8e9f7ad9f1cc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 17:12:26 +0100 Subject: [PATCH 14/60] Merge all SQLRelation properties --- GRDB/QueryInterface/SQL/SQLRelation.swift | 41 ++++++++++++++-- GRDB/Utils/OrderedDictionary.swift | 34 ++++++++++++++ Tests/GRDBTests/OrderedDictionaryTests.swift | 49 ++++++++++++++++++++ 3 files changed, 120 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 1206dff22..75896a9c0 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -141,13 +141,13 @@ struct SQLRelation { var source: SQLSource var selectionPromise: DatabasePromise<[SQLSelection]> + #warning("TODO: turn into DatabasePromise<[SQLExpression]>? like havingExpressionPromise") var filterPromise: DatabasePromise = DatabasePromise(value: nil) var ordering: SQLRelation.Ordering = SQLRelation.Ordering() var children: OrderedDictionary = [:] // Properties below MUST NOT be used when joining to-one associations #warning("TODO: make sure a precondition failure prevents those to be defined on to-one associations") - #warning("TODO: merge") var isDistinct: Bool = false var groupPromise: DatabasePromise<[SQLExpression]>? var havingExpressionPromise: DatabasePromise? @@ -932,11 +932,13 @@ extension PersistenceContainer: ColumnAddressable { extension SQLRelation { /// Returns nil if relations can't be merged (conflict in source, joins...) func merged(with other: SQLRelation) -> Self? { + // Source guard let mergedSource = source.merged(with: other.source) else { // can't merge return nil } + // Filter: merge with AND let mergedFilterPromise = DatabasePromise { db in switch try (self.filterPromise.resolve(db), other.filterPromise.resolve(db)) { case let (lhs?, rhs?): return lhs && rhs @@ -945,6 +947,7 @@ extension SQLRelation { } } + // Children: merge recursively var mergedChildren: OrderedDictionary = [:] for (key, child) in children { if let otherChild = other.children[key] { @@ -961,7 +964,7 @@ extension SQLRelation { mergedChildren.appendValue(child, forKey: key) } - // replace selection unless empty + // Selection: replace unless empty let mergedSelectionPromise = DatabasePromise { db -> [SQLSelection] in let otherSelection = try other.selectionPromise.resolve(db) if otherSelection.isEmpty { @@ -971,15 +974,45 @@ extension SQLRelation { } } - // replace ordering unless empty + // Ordering: prefer other let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering + // Distinct + let mergedDistinct = isDistinct || other.isDistinct + + // Grouping: prefer other + let mergedGroupPromise = other.groupPromise ?? groupPromise + + // Having: merge with AND + let mergedHavingExpressionPromise: DatabasePromise? + switch (havingExpressionPromise, other.havingExpressionPromise) { + case let (lhs?, rhs?): + mergedHavingExpressionPromise = DatabasePromise { + try lhs.resolve($0) && rhs.resolve($0) + } + case let (nil, promise?), let (promise?, nil): + mergedHavingExpressionPromise = promise + case (nil, nil): + mergedHavingExpressionPromise = nil + } + + // Limit: prefer other + let mergedLimit = other.limit ?? limit + + // CTEs: merge & prefer other + let mergedCTEs = ctes.merging(other.ctes, uniquingKeysWith: { (_, other) in other }) + return SQLRelation( source: mergedSource, selectionPromise: mergedSelectionPromise, filterPromise: mergedFilterPromise, ordering: mergedOrdering, - children: mergedChildren) + children: mergedChildren, + isDistinct: mergedDistinct, + groupPromise: mergedGroupPromise, + havingExpressionPromise: mergedHavingExpressionPromise, + limit: mergedLimit, + ctes: mergedCTEs) } } diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index a700c2f54..0d82ba25c 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -118,6 +118,40 @@ struct OrderedDictionary { let keys = self.keys.filter(dictionary.keys.contains) return OrderedDictionary(keys: keys, dictionary: dictionary) } + + func merging( + _ other: S, + uniquingKeysWith combine: (Value, Value) throws -> Value) + rethrows -> OrderedDictionary + where S: Sequence, S.Element == (Key, Value) + { + var result = self + for (key, value) in other { + if let current = result[key] { + result[key] = try combine(current, value) + } else { + result[key] = value + } + } + return result + } + + func merging( + _ other: S, + uniquingKeysWith combine: (Value, Value) throws -> Value) + rethrows -> OrderedDictionary + where S: Sequence, S.Element == (key: Key, value: Value) + { + var result = self + for (key, value) in other { + if let current = result[key] { + result[key] = try combine(current, value) + } else { + result[key] = value + } + } + return result + } } extension OrderedDictionary: Collection { diff --git a/Tests/GRDBTests/OrderedDictionaryTests.swift b/Tests/GRDBTests/OrderedDictionaryTests.swift index 14fe54125..cc5823012 100644 --- a/Tests/GRDBTests/OrderedDictionaryTests.swift +++ b/Tests/GRDBTests/OrderedDictionaryTests.swift @@ -8,4 +8,53 @@ class OrderedDictionaryTests: GRDBTestCase { dict["a", default: []].append("bar") XCTAssertEqual(dict, ["a": ["foo", "bar"]]) } + + func testMergingUniquingKeysWith() { + do { + let dict: OrderedDictionary = ["a": 1, "b": 2] + + let otherDictionary = ["a": 3, "c": 4] + let otherOrderedDictionary: OrderedDictionary = ["a": 3, "c": 4] + let otherSequence = zip(["a", "c"], [3, 4]) + + do { + let result = dict.merging(otherDictionary, uniquingKeysWith: { (current, _) in current }) + XCTAssertEqual(result, ["a": 1, "b": 2, "c": 4]) + } + do { + let result = dict.merging(otherOrderedDictionary, uniquingKeysWith: { (current, _) in current }) + XCTAssertEqual(result, ["a": 1, "b": 2, "c": 4]) + } + do { + let result = dict.merging(otherSequence, uniquingKeysWith: { (current, _) in current }) + XCTAssertEqual(result, ["a": 1, "b": 2, "c": 4]) + } + + do { + let result = dict.merging(otherDictionary, uniquingKeysWith: { (_, new) in new }) + XCTAssertEqual(result, ["a": 3, "b": 2, "c": 4]) + } + do { + let result = dict.merging(otherOrderedDictionary, uniquingKeysWith: { (_, new) in new }) + XCTAssertEqual(result, ["a": 3, "b": 2, "c": 4]) + } + do { + let result = dict.merging(otherSequence, uniquingKeysWith: { (_, new) in new }) + XCTAssertEqual(result, ["a": 3, "b": 2, "c": 4]) + } + + do { + let result = dict.merging(otherDictionary, uniquingKeysWith: { $0 + $1 }) + XCTAssertEqual(result, ["a": 4, "b": 2, "c": 4]) + } + do { + let result = dict.merging(otherOrderedDictionary, uniquingKeysWith: { $0 + $1 }) + XCTAssertEqual(result, ["a": 4, "b": 2, "c": 4]) + } + do { + let result = dict.merging(otherSequence, uniquingKeysWith: { $0 + $1 }) + XCTAssertEqual(result, ["a": 4, "b": 2, "c": 4]) + } + } + } } From a4dca3390a806a02254fc938fee744e9effbcd89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 19:15:09 +0100 Subject: [PATCH 15/60] AggregateJoinableRequest is the new protocol that supports aggregate annotations AssociationToMany is a subprotocol of AggregateJoinableRequest :-) --- .../Request/Association/Association.swift | 151 ++++++++++-------- .../Association/AssociationAggregate.swift | 134 ++++++++++++---- .../Request/QueryInterfaceRequest.swift | 52 +----- .../Request/RequestProtocols.swift | 53 ++++++ 4 files changed, 244 insertions(+), 146 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index d04576c0a..90a796792 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -72,13 +72,12 @@ extension Association { } extension Association { - private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { + fileprivate func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { .init(sqlAssociation: _sqlAssociation.map(\.destination.relation, transform)) } } extension Association { - /// The association key defines how rows fetched from this association /// should be consumed. /// @@ -105,6 +104,67 @@ extension Association { /// } var key: SQLAssociationKey { _sqlAssociation.destination.key } + /// Creates an association with the given key. + /// + /// This new key helps Decodable records decode rows fetched from the + /// resulting association: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// struct PlayerInfo: FetchableRecord, Decodable { + /// let player: Player + /// let team: Team + /// + /// static func all() -> QueryInterfaceRequest { + /// return Player + /// .including(required: Player.team.forKey(CodingKeys.team)) + /// .asRequest(of: PlayerInfo.self) + /// } + /// } + /// + /// let playerInfos = PlayerInfo.all().fetchAll(db) + /// print(playerInfos.first?.team) + public func forKey(_ codingKey: CodingKey) -> Self { + forKey(codingKey.stringValue) + } + + /// Creates an association that allows you to define expressions that target + /// a specific database table. + /// + /// In the example below, the "team.color = 'red'" condition in the where + /// clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... + /// // WHERE team.color = 'red' + /// let teamAlias = TableAlias() + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(teamAlias[Column("color")] == "red") + /// + /// When you give a name to a table alias, you can reliably inject sql + /// snippets in your requests: + /// + /// // SELECT player.*, custom.* + /// // JOIN team custom ON ... + /// // WHERE custom.color = 'red' + /// let teamAlias = TableAlias(name: "custom") + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(sql: "custom.color = ?", arguments: ["red"]) + public func aliased(_ alias: TableAlias) -> Self { + mapDestinationRelation { $0.aliased(alias) } + } +} + +extension Association where Self: SelectionRequest { + /// Creates an association which selects *selection*. /// /// struct Player: TableRecord { @@ -146,7 +206,9 @@ extension Association { public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { mapDestinationRelation { $0.annotated { try selection($0).map(\.sqlSelection) } } } - +} + +extension Association where Self: FilteredRequest { /// Creates an association with the provided *predicate promise* added to /// the eventual set of already applied predicates. /// @@ -162,7 +224,9 @@ extension Association { public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { mapDestinationRelation { $0.filter { try predicate($0).sqlExpression } } } - +} + +extension Association where Self: OrderedRequest { /// Creates an association with the provided *orderings promise*. /// /// struct Player: TableRecord { @@ -229,71 +293,24 @@ extension Association { public func unordered() -> Self { mapDestinationRelation { $0.unordered() } } - - /// Creates an association with the given key. - /// - /// This new key helps Decodable records decode rows fetched from the - /// resulting association: - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// struct PlayerInfo: FetchableRecord, Decodable { - /// let player: Player - /// let team: Team - /// - /// static func all() -> QueryInterfaceRequest { - /// return Player - /// .including(required: Player.team.forKey(CodingKeys.team)) - /// .asRequest(of: PlayerInfo.self) - /// } - /// } - /// - /// let playerInfos = PlayerInfo.all().fetchAll(db) - /// print(playerInfos.first?.team) - public func forKey(_ codingKey: CodingKey) -> Self { - forKey(codingKey.stringValue) - } - - /// Creates an association that allows you to define expressions that target - /// a specific database table. - /// - /// In the example below, the "team.color = 'red'" condition in the where - /// clause could be not achieved without table aliases. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.* - /// // JOIN team ON ... - /// // WHERE team.color = 'red' - /// let teamAlias = TableAlias() - /// let request = Player - /// .including(required: Player.team.aliased(teamAlias)) - /// .filter(teamAlias[Column("color")] == "red") - /// - /// When you give a name to a table alias, you can reliably inject sql - /// snippets in your requests: - /// - /// // SELECT player.*, custom.* - /// // JOIN team custom ON ... - /// // WHERE custom.color = 'red' - /// let teamAlias = TableAlias(name: "custom") - /// let request = Player - /// .including(required: Player.team.aliased(teamAlias)) - /// .filter(sql: "custom.color = ?", arguments: ["red"]) - public func aliased(_ alias: TableAlias) -> Self { - mapDestinationRelation { $0.aliased(alias) } +} + +extension Association where Self: TableRequest { + public var databaseTableName: String { + _sqlAssociation.destination.relation.source.tableName } } -// TableRequest -extension Association { - /// :nodoc: - public var databaseTableName: String { - _sqlAssociation.destination.relation.source.tableName +extension Association where Self: AggregatingRequest { + /// Creates an association grouped according to *expressions promise*. + public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self { + mapDestinationRelation { $0.group { try expressions($0).map(\.sqlExpression) } } + } + + /// Creates an association with the provided *predicate promise* added to + /// the eventual set of already applied predicates. + public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + mapDestinationRelation { $0.having { try predicate($0).sqlExpression } } } } @@ -312,7 +329,7 @@ extension AssociationToOne { // MARK: - AssociationToMany /// The base protocol for all associations that define a one-to-many connection. -public protocol AssociationToMany: Association { } +public protocol AssociationToMany: Association, AggregateJoinableRequest { } extension AssociationToMany { public func forKey(_ key: String) -> Self { diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 6163a2cf2..78aaf6b04 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -1,20 +1,10 @@ import Foundation -typealias AssociationAggregatePreparation = - (inout QueryInterfaceRequest) - -> DatabasePromise - extension AssociationToMany { private func makeAggregate(_ expressionPromise: DatabasePromise) -> AssociationAggregate { - AssociationAggregate { request in - let tableAlias = TableAlias() - request = request - .joining(optional: self.aliased(tableAlias)) - .groupByPrimaryKey() - return expressionPromise.map { tableAlias[$0] } - } + AssociationAggregate(preparation: BasePreparation(association: self, expressionPromise: expressionPromise)) } // Convenience @@ -194,8 +184,13 @@ extension AssociationToMany { /// // Won't compile because Fruit is not Author. /// let request = Fruit.annotated(with: bookCount) public struct AssociationAggregate { - /// Extend the request with the associated records used to compute the - /// aggregate, and return an expression promise which resolves to the + fileprivate let preparation: AssociationAggregatePreparation + + /// The SQL name for the value of this aggregate. See forKey(_:). + var key: String? = nil + + /// Extends the request with the associated records used to compute the + /// aggregate, and returns an expression promise which resolves to the /// aggregated value. /// /// For example: @@ -227,10 +222,12 @@ public struct AssociationAggregate { /// - We don't know yet if the aggregated value will be used in the /// SQL selection, or in the HAVING clause. /// - It helps implementing aggregate operators such as `&&`, `+`, etc. - let prepare: AssociationAggregatePreparation + func prepare(_ request: inout Request) -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + { + preparation.prepare(&request) + } - /// The SQL name for the value of this aggregate. See forKey(_:). - var key: String? = nil } extension AssociationAggregate: Refinable { @@ -265,11 +262,100 @@ extension AssociationAggregate: Refinable { public func forKey(_ key: CodingKey) -> Self { forKey(key.stringValue) } +} + +// MARK: - AssociationAggregatePreparation + +/// An abstract class that workarounds the lack of generic closures in Swift. +/// +/// It only exists as support for `AssociationAggregate.prepare(_:)`. +private class AssociationAggregatePreparation { + func prepare(_ request: inout Request) + -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + { + fatalError("subclass must override") + } +} + +// swiftlint:disable:next colon +private class BasePreparation: + AssociationAggregatePreparation +{ + private let association: Association + private let expressionPromise: DatabasePromise + init(association: Association, expressionPromise: DatabasePromise) { + self.association = association + self.expressionPromise = expressionPromise + } + + override func prepare(_ request: inout Request) + -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == Association.OriginRowDecoder + { + let tableAlias = TableAlias() + request = request + .joining(optional: association.aliased(tableAlias)) + .groupByPrimaryKey() + return expressionPromise.map { tableAlias[$0] } + } +} + +/// Transforms the expression of an aggregate. +private class MapPreparation: AssociationAggregatePreparation { + private let base: AssociationAggregatePreparation + private let transform: (SQLExpression) throws -> SQLExpression + + init( + base: AssociationAggregatePreparation, + transform: @escaping (SQLExpression) throws -> SQLExpression) + { + self.base = base + self.transform = transform + } + + override func prepare(_ request: inout Request) + -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + { + base.prepare(&request).map(transform) + } +} + +extension AssociationAggregate { /// Transforms the expression, and does not preserve key. fileprivate func map(_ transform: @escaping (SQLExpression) throws -> SQLExpression) -> Self { - AssociationAggregate { request in - self.prepare(&request).map(transform) + AssociationAggregate(preparation: MapPreparation(base: preparation, transform: transform)) + } +} + +/// Combines the expressions of two aggregates. +private class CombinePreparation: AssociationAggregatePreparation { + private let lhs: AssociationAggregatePreparation + private let rhs: AssociationAggregatePreparation + private let combine: (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression + + init( + _ lhs: AssociationAggregatePreparation, + _ rhs: AssociationAggregatePreparation, + combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) + { + self.lhs = lhs + self.rhs = rhs + self.combine = combine + } + + override func prepare(_ request: inout Request) + -> DatabasePromise + where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + { + let lhsPromise = lhs.prepare(&request) + let rhsPromise = rhs.prepare(&request) + return DatabasePromise { [combine] db in + try combine( + lhsPromise.resolve(db), + rhsPromise.resolve(db)) } } } @@ -278,18 +364,10 @@ extension AssociationAggregate: Refinable { private func combine( _ lhs: AssociationAggregate, _ rhs: AssociationAggregate, - with combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) + with combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) -> AssociationAggregate { - AssociationAggregate { request in - let lhsPromise = lhs.prepare(&request) - let rhsPromise = rhs.prepare(&request) - return DatabasePromise { db in - try combineExpressions( - lhsPromise.resolve(db), - rhsPromise.resolve(db)) - } - } + AssociationAggregate(preparation: CombinePreparation(lhs.preparation, rhs.preparation, combine: combine)) } // MARK: - Logical Operators (AND, OR, NOT) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 7aabf8770..1e91e60ec 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -299,6 +299,7 @@ extension QueryInterfaceRequest: TableRequest { } extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { } +extension QueryInterfaceRequest: AggregateJoinableRequest where RowDecoder: TableRecord { } extension QueryInterfaceRequest { /// Creates a request which returns distinct rows. @@ -343,57 +344,6 @@ extension QueryInterfaceRequest { } } -// MARK: - Aggregates - -extension QueryInterfaceRequest { - - private func annotated(with aggregate: AssociationAggregate) -> QueryInterfaceRequest { - var request = self - let expressionPromise = aggregate.prepare(&request) - if let key = aggregate.key { - return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] }) - } else { - return request.annotated(with: { db in try [expressionPromise.resolve(db)] }) - } - } - - /// Creates a request which appends *aggregates* to the current selection. - /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// var request = Player.all() - /// request = request.annotated(with: Player.books.count) - public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { - annotated(with: aggregates) - } - - /// Creates a request which appends *aggregates* to the current selection. - /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// var request = Player.all() - /// request = request.annotated(with: [Player.books.count]) - public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { - aggregates.reduce(self) { request, aggregate in - request.annotated(with: aggregate) - } - } - - /// Creates a request which appends the provided aggregate *predicate* to - /// the eventual set of already applied predicates. - /// - /// // SELECT player.* - /// // FROM player LEFT JOIN book ... - /// // HAVING COUNT(DISTINCT book.id) = 0 - /// var request = Player.all() - /// request = request.having(Player.books.isEmpty) - public func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { - var request = self - let expressionPromise = predicate.prepare(&request) - return request.having(expressionPromise.resolve) - } -} - // MARK: - Batch Delete extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 347206c29..4be01a31d 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -591,3 +591,56 @@ extension JoinableRequest { /// The base protocol for all requests that can be refined. public protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { } + +// MARK: - AggregateJoinableRequest + +/// The base protocol for all requests that can use association aggregates. +public protocol AggregateJoinableRequest: AggregatingRequest & JoinableRequest & SelectionRequest & TableRequest { } + +extension AggregateJoinableRequest { + private func annotated(with aggregate: AssociationAggregate) -> Self { + var request = self + let expressionPromise = aggregate.prepare(&request) + if let key = aggregate.key { + return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] }) + } else { + return request.annotated(with: { db in try [expressionPromise.resolve(db)] }) + } + } + + /// Creates a request which appends *aggregates* to the current selection. + /// + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM player LEFT JOIN book ... + /// var request = Player.all() + /// request = request.annotated(with: Player.books.count) + public func annotated(with aggregates: AssociationAggregate...) -> Self { + annotated(with: aggregates) + } + + /// Creates a request which appends *aggregates* to the current selection. + /// + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM player LEFT JOIN book ... + /// var request = Player.all() + /// request = request.annotated(with: [Player.books.count]) + public func annotated(with aggregates: [AssociationAggregate]) -> Self { + aggregates.reduce(self) { request, aggregate in + request.annotated(with: aggregate) + } + } + + /// Creates a request which appends the provided aggregate *predicate* to + /// the eventual set of already applied predicates. + /// + /// // SELECT player.* + /// // FROM player LEFT JOIN book ... + /// // HAVING COUNT(DISTINCT book.id) = 0 + /// var request = Player.all() + /// request = request.having(Player.books.isEmpty) + public func having(_ predicate: AssociationAggregate) -> Self { + var request = self + let expressionPromise = predicate.prepare(&request) + return request.having(expressionPromise.resolve) + } +} From 9c6ff6a1c058635691d358012d47c108e2023c26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 19:36:08 +0100 Subject: [PATCH 16/60] Simplifly association aggregates We don't need any promise. We used to, but SQLExpression.fastPrimaryKey has been introduced since then. --- .../Association/AssociationAggregate.swift | 67 +++++++------------ .../Request/RequestProtocols.swift | 10 +-- 2 files changed, 30 insertions(+), 47 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 78aaf6b04..371a77e8c 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -1,15 +1,8 @@ import Foundation extension AssociationToMany { - private func makeAggregate(_ expressionPromise: DatabasePromise) - -> AssociationAggregate - { - AssociationAggregate(preparation: BasePreparation(association: self, expressionPromise: expressionPromise)) - } - - // Convenience private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate { - makeAggregate(DatabasePromise(value: expression)) + AssociationAggregate(preparation: BasePreparation(association: self, expression: expression)) } /// The number of associated records. @@ -190,8 +183,7 @@ public struct AssociationAggregate { var key: String? = nil /// Extends the request with the associated records used to compute the - /// aggregate, and returns an expression promise which resolves to the - /// aggregated value. + /// aggregate, and returns the aggregated expression. /// /// For example: /// @@ -203,7 +195,7 @@ public struct AssociationAggregate { /// var request = Author.all() /// /// let aggregate = Author.books.count - /// let expressionPromise = aggregate.prepare(&request) + /// let expression = aggregate.prepare(&request) /// /// // The request has been extended with associated records: /// // @@ -215,19 +207,18 @@ public struct AssociationAggregate { /// // The aggregated value: /// // /// // COUNT(DISTINCT book.id) - /// try expressionPromise.resolve(db) + /// expression /// - /// The aggregated value is not right away embedded in the extended request: + /// The aggregated expression is not embedded in the extended request: /// - /// - We don't know yet if the aggregated value will be used in the + /// - We don't know yet if the aggregated expression will be used in the /// SQL selection, or in the HAVING clause. /// - It helps implementing aggregate operators such as `&&`, `+`, etc. - func prepare(_ request: inout Request) -> DatabasePromise + func prepare(_ request: inout Request) -> SQLExpression where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder { preparation.prepare(&request) } - } extension AssociationAggregate: Refinable { @@ -270,8 +261,7 @@ extension AssociationAggregate: Refinable { /// /// It only exists as support for `AssociationAggregate.prepare(_:)`. private class AssociationAggregatePreparation { - func prepare(_ request: inout Request) - -> DatabasePromise + func prepare(_ request: inout Request) -> SQLExpression where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder { fatalError("subclass must override") @@ -283,49 +273,47 @@ private class BasePreparation: AssociationAggregatePreparation { private let association: Association - private let expressionPromise: DatabasePromise + private let expression: SQLExpression - init(association: Association, expressionPromise: DatabasePromise) { + init(association: Association, expression: SQLExpression) { self.association = association - self.expressionPromise = expressionPromise + self.expression = expression } - override func prepare(_ request: inout Request) - -> DatabasePromise + override func prepare(_ request: inout Request) -> SQLExpression where Request: AggregateJoinableRequest, Request.RowDecoder == Association.OriginRowDecoder { let tableAlias = TableAlias() request = request .joining(optional: association.aliased(tableAlias)) .groupByPrimaryKey() - return expressionPromise.map { tableAlias[$0] } + return expression.qualified(with: tableAlias) } } /// Transforms the expression of an aggregate. private class MapPreparation: AssociationAggregatePreparation { private let base: AssociationAggregatePreparation - private let transform: (SQLExpression) throws -> SQLExpression + private let transform: (SQLExpression) -> SQLExpression init( base: AssociationAggregatePreparation, - transform: @escaping (SQLExpression) throws -> SQLExpression) + transform: @escaping (SQLExpression) -> SQLExpression) { self.base = base self.transform = transform } - override func prepare(_ request: inout Request) - -> DatabasePromise + override func prepare(_ request: inout Request) -> SQLExpression where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder { - base.prepare(&request).map(transform) + transform(base.prepare(&request)) } } extension AssociationAggregate { /// Transforms the expression, and does not preserve key. - fileprivate func map(_ transform: @escaping (SQLExpression) throws -> SQLExpression) -> Self { + fileprivate func map(_ transform: @escaping (SQLExpression) -> SQLExpression) -> Self { AssociationAggregate(preparation: MapPreparation(base: preparation, transform: transform)) } } @@ -334,29 +322,24 @@ extension AssociationAggregate { private class CombinePreparation: AssociationAggregatePreparation { private let lhs: AssociationAggregatePreparation private let rhs: AssociationAggregatePreparation - private let combine: (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression + private let combine: (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression init( _ lhs: AssociationAggregatePreparation, _ rhs: AssociationAggregatePreparation, - combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) + combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression) { self.lhs = lhs self.rhs = rhs self.combine = combine } - override func prepare(_ request: inout Request) - -> DatabasePromise + override func prepare(_ request: inout Request) -> SQLExpression where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder { - let lhsPromise = lhs.prepare(&request) - let rhsPromise = rhs.prepare(&request) - return DatabasePromise { [combine] db in - try combine( - lhsPromise.resolve(db), - rhsPromise.resolve(db)) - } + let lhsExpression = lhs.prepare(&request) + let rhsExpression = rhs.prepare(&request) + return combine(lhsExpression, rhsExpression) } } @@ -364,7 +347,7 @@ private class CombinePreparation: AssociationAggregatePreparation( _ lhs: AssociationAggregate, _ rhs: AssociationAggregate, - with combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression) + with combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression) -> AssociationAggregate { AssociationAggregate(preparation: CombinePreparation(lhs.preparation, rhs.preparation, combine: combine)) diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 4be01a31d..de3af7149 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -600,11 +600,11 @@ public protocol AggregateJoinableRequest: AggregatingRequest & JoinableRequest & extension AggregateJoinableRequest { private func annotated(with aggregate: AssociationAggregate) -> Self { var request = self - let expressionPromise = aggregate.prepare(&request) + let expression = aggregate.prepare(&request) if let key = aggregate.key { - return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] }) + return request.annotated(with: expression.forKey(key)) } else { - return request.annotated(with: { db in try [expressionPromise.resolve(db)] }) + return request.annotated(with: expression) } } @@ -640,7 +640,7 @@ extension AggregateJoinableRequest { /// request = request.having(Player.books.isEmpty) public func having(_ predicate: AssociationAggregate) -> Self { var request = self - let expressionPromise = predicate.prepare(&request) - return request.having(expressionPromise.resolve) + let expression = predicate.prepare(&request) + return request.having(expression) } } From d2a22ddd97f2746fd9d05dee00b798b9fff5afbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 19:56:04 +0100 Subject: [PATCH 17/60] Make sure joined associations do not use prefetched to-many features One can't join a distinct, grouped, or limited association. --- GRDB/QueryInterface/SQL/SQLRelation.swift | 31 ++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 75896a9c0..18455d4da 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -120,6 +120,31 @@ struct SQLRelation { } } + init(kind: SQLRelation.Child.Kind, condition: SQLAssociationCondition, relation: SQLRelation) { + switch kind { + case .oneOptional, .oneRequired, .bridge: + if relation.isDistinct { + fatalError("Can't join an association that selects DISTINCT rows") + } + if relation.groupPromise != nil || relation.havingExpressionPromise != nil { + fatalError("Can't join an association with a GROUP BY clause") + } + if relation.limit != nil { + fatalError("Can't join an association with a LIMIT clause") + } + if relation.ctes.isEmpty == false { + // TODO: maybe we could lift ctes up to the base relation + fatalError("Not implemented: joining an association that embeds a common table expression") + } + case .all: + break + } + + self.kind = kind + self.condition = condition + self.relation = relation + } + fileprivate func makeAssociationForKey(_ key: String) -> _SQLAssociation { let key = SQLAssociationKey.fixed(key) @@ -146,9 +171,9 @@ struct SQLRelation { var ordering: SQLRelation.Ordering = SQLRelation.Ordering() var children: OrderedDictionary = [:] - // Properties below MUST NOT be used when joining to-one associations - #warning("TODO: make sure a precondition failure prevents those to be defined on to-one associations") - var isDistinct: Bool = false + // Properties below MUST NOT be used when joining to-one associations. + // This is guaranteed by Child.init(). + var isDistinct = false var groupPromise: DatabasePromise<[SQLExpression]>? var havingExpressionPromise: DatabasePromise? var limit: SQLLimit? From 092b0d0e44b4890350cbbba22255f32a44529fde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 19:58:15 +0100 Subject: [PATCH 18/60] Move with(cte) methods to the file it belongs to --- .../Request/CommonTableExpression.swift | 80 ------------------- .../Request/QueryInterfaceRequest.swift | 37 +++++++++ .../TableRecord+QueryInterfaceRequest.swift | 37 +++++++++ 3 files changed, 74 insertions(+), 80 deletions(-) diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index b83650e4f..612c2544b 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -406,83 +406,3 @@ extension CommonTableExpression { JoinAssociation(to: Destination.relationForAll, condition: .none) } } - -// MARK: - With - -extension QueryInterfaceRequest { - /// Returns a request which embeds the common table expression. - /// - /// If a common table expression with the same table name had already been - /// embedded, it is replaced by the new one. - /// - /// For example, you can build a request that fetches all chats with their - /// latest message: - /// - /// let latestMessageRequest = Message - /// .annotated(with: max(Column("date"))) - /// .group(Column("chatID")) - /// - /// let latestMessageCTE = CommonTableExpression( - /// named: "latestMessage", - /// request: latestMessageRequest) - /// - /// let latestMessage = Chat.association( - /// to: latestMessageCTE, - /// on: { chat, latestMessage in - /// chat[Column("id")] == latestMessage[Column("chatID")] - /// }) - /// - /// // WITH latestMessage AS - /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) - /// // SELECT chat.*, latestMessage.* - /// // FROM chat - /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID - /// let request = Chat.all() - /// .with(latestMessageCTE) - /// .including(optional: latestMessage) - /// - /// - parameter cte: A common table expression. - /// - returns: A request. - public func with(_ cte: CommonTableExpression) -> Self { - with(\.relation.ctes[cte.tableName], cte.cte) - } -} - -extension TableRecord { - /// Returns a request which embeds the common table expression. - /// - /// If a common table expression with the same table name had already been - /// embedded, it is replaced by the new one. - /// - /// For example, you can build a request that fetches all chats with their - /// latest post: - /// - /// let latestMessageRequest = Message - /// .annotated(with: max(Column("date"))) - /// .group(Column("chatID")) - /// - /// let latestMessageCTE = CommonTableExpression( - /// named: "latestMessage", - /// request: latestMessageRequest) - /// - /// let latestMessage = Chat.association( - /// to: latestMessageCTE, - /// on: { chat, latestMessage in - /// chat[Column("id")] == latestMessage[Column("chatID")] - /// }) - /// - /// // WITH latestMessage AS - /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) - /// // SELECT chat.*, latestMessage.* - /// // FROM chat - /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID - /// let request = Chat - /// .with(latestMessageCTE) - /// .including(optional: latestMessage) - /// - /// - parameter cte: A common table expression. - /// - returns: A request. - public static func with(_ cte: CommonTableExpression) -> QueryInterfaceRequest { - all().with(cte) - } -} diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 1e91e60ec..50a303612 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -326,6 +326,43 @@ extension QueryInterfaceRequest { with(\.relation.limit, SQLLimit(limit: limit, offset: offset)) } + /// Returns a request which embeds the common table expression. + /// + /// If a common table expression with the same table name had already been + /// embedded, it is replaced by the new one. + /// + /// For example, you can build a request that fetches all chats with their + /// latest message: + /// + /// let latestMessageRequest = Message + /// .annotated(with: max(Column("date"))) + /// .group(Column("chatID")) + /// + /// let latestMessageCTE = CommonTableExpression( + /// named: "latestMessage", + /// request: latestMessageRequest) + /// + /// let latestMessage = Chat.association( + /// to: latestMessageCTE, + /// on: { chat, latestMessage in + /// chat[Column("id")] == latestMessage[Column("chatID")] + /// }) + /// + /// // WITH latestMessage AS + /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) + /// // SELECT chat.*, latestMessage.* + /// // FROM chat + /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID + /// let request = Chat.all() + /// .with(latestMessageCTE) + /// .including(optional: latestMessage) + /// + /// - parameter cte: A common table expression. + /// - returns: A request. + public func with(_ cte: CommonTableExpression) -> Self { + with(\.relation.ctes[cte.tableName], cte.cte) + } + /// Creates a request bound to type RowDecoder. /// /// The returned request can fetch if the type RowDecoder is fetchable (Row, diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index e0f1f2ac7..a0793ce6b 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -373,4 +373,41 @@ extension TableRecord { public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { all().aliased(alias) } + + /// Returns a request which embeds the common table expression. + /// + /// If a common table expression with the same table name had already been + /// embedded, it is replaced by the new one. + /// + /// For example, you can build a request that fetches all chats with their + /// latest post: + /// + /// let latestMessageRequest = Message + /// .annotated(with: max(Column("date"))) + /// .group(Column("chatID")) + /// + /// let latestMessageCTE = CommonTableExpression( + /// named: "latestMessage", + /// request: latestMessageRequest) + /// + /// let latestMessage = Chat.association( + /// to: latestMessageCTE, + /// on: { chat, latestMessage in + /// chat[Column("id")] == latestMessage[Column("chatID")] + /// }) + /// + /// // WITH latestMessage AS + /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) + /// // SELECT chat.*, latestMessage.* + /// // FROM chat + /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID + /// let request = Chat + /// .with(latestMessageCTE) + /// .including(optional: latestMessage) + /// + /// - parameter cte: A common table expression. + /// - returns: A request. + public static func with(_ cte: CommonTableExpression) -> QueryInterfaceRequest { + all().with(cte) + } } From f0aec270958c36d878bdeab497ed50c0c0bdab50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 20:25:30 +0100 Subject: [PATCH 19/60] AssociationToMany: distinct(), limit(_:offset:), with(_:) --- .../Request/Association/Association.swift | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 90a796792..a7fb1563c 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -336,4 +336,23 @@ extension AssociationToMany { let associationKey = SQLAssociationKey.fixedPlural(key) return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) } + + /// Creates an association for returns distinct rows. + public func distinct() -> Self { + mapDestinationRelation { $0.with(\.isDistinct, true) } + } + + /// Creates an association that fetches *limit* rows, starting at *offset*. + /// + /// Any previous limit is replaced. + public func limit(_ limit: Int, offset: Int? = nil) -> Self { + mapDestinationRelation { $0.with(\.limit, SQLLimit(limit: limit, offset: offset)) } + } + + /// Returns an association that embeds the common table expression. + /// + /// See `QueryInterfaceRequest.with(_:)` for more information. + public func with(_ cte: CommonTableExpression) -> Self { + mapDestinationRelation { $0.with(\.ctes[cte.tableName], cte.cte) } + } } From 6b733cfc0a4a2f2ba5cbeca65ff4c2add88c167e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Mar 2021 20:27:10 +0100 Subject: [PATCH 20/60] Tests for including(all:) with distinct, limited, grouped, and cte-decorated associations --- .../AssociationPrefetchingSQLTests.swift | 199 ++++++++++++++++++ 1 file changed, 199 insertions(+) diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 6401c8438..52b17be15 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -1720,6 +1720,205 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } + func testAggregate() throws { + struct Award: TableRecord { } + struct Player: TableRecord { + static let awards = hasMany(Award.self) + } + struct Team: TableRecord { + static let players = hasMany(Player.self) + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("teamId") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("playerId") + t.column("parentId", .integer).references("team") + t.column("score") + t.column("category") + } + try db.create(table: "award") { t in + t.autoIncrementedPrimaryKey("awardId") + t.column("playerId", .integer).references("player") + } + try db.execute(sql: "INSERT INTO team DEFAULT VALUES") + + do { + // Group an association + sqlQueries.removeAll() + let association = Team.players.select(max(Column("score"))).group(Column("category")) + let request = Team.including(all: association) + _ = try Row.fetchAll(db, request) + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "team" + """, + """ + SELECT MAX("score"), "parentId" AS "grdb_parentId" \ + FROM "player" \ + WHERE "parentId" = 1 \ + GROUP BY "category" + """]) + } + + do { + // Filter an association with an association aggregate + sqlQueries.removeAll() + let association = Team.players.having(Player.awards.isEmpty) + let request = Team.including(all: association) + _ = try Row.fetchAll(db, request) + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "team" + """, + """ + SELECT "player".*, "player"."parentId" AS "grdb_parentId" \ + FROM "player" \ + LEFT JOIN "award" ON "award"."playerId" = "player"."playerId" \ + WHERE "player"."parentId" = 1 \ + GROUP BY "player"."playerId" \ + HAVING COUNT(DISTINCT "award"."awardId") = 0 + """]) + } + + do { + // Annotate an association with an association aggregate + sqlQueries.removeAll() + let association = Team.players.annotated(with: Player.awards.count) + let request = Team.including(all: association) + _ = try Row.fetchAll(db, request) + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "team" + """, + """ + SELECT "player".*, COUNT(DISTINCT "award"."awardId") AS "awardCount", "player"."parentId" AS "grdb_parentId" \ + FROM "player" \ + LEFT JOIN "award" ON "award"."playerId" = "player"."playerId" \ + WHERE "player"."parentId" = 1 \ + GROUP BY "player"."playerId" + """]) + } + } + } + + func testDistinct() throws { + struct Player: TableRecord { } + struct Team: TableRecord { + static let players = hasMany(Player.self) + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("teamId") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("playerId") + t.column("parentId", .integer).references("team") + } + try db.execute(sql: "INSERT INTO team DEFAULT VALUES") + + do { + sqlQueries.removeAll() + let association = Team.players.distinct() + let request = Team.including(all: association) + _ = try Row.fetchAll(db, request) + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "team" + """, + """ + SELECT DISTINCT *, "parentId" AS "grdb_parentId" \ + FROM "player" \ + WHERE "parentId" = 1 + """]) + } + } + } + + func testLimit() throws { + struct Player: TableRecord { } + struct Team: TableRecord { + static let players = hasMany(Player.self) + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("teamId") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("playerId") + t.column("parentId", .integer).references("team") + } + try db.execute(sql: "INSERT INTO team DEFAULT VALUES") + + do { + sqlQueries.removeAll() + let association = Team.players.limit(10, offset: 5) + let request = Team.including(all: association) + _ = try Row.fetchAll(db, request) + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "team" + """, + """ + SELECT *, "parentId" AS "grdb_parentId" \ + FROM "player" \ + WHERE "parentId" = 1 \ + LIMIT 10 OFFSET 5 + """]) + } + } + } + + func testCTE() throws { + struct Player: TableRecord { } + struct Team: TableRecord { + static let players = hasMany(Player.self) + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("teamId") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("playerId") + t.column("parentId", .integer).references("team") + } + try db.execute(sql: "INSERT INTO team DEFAULT VALUES") + + do { + sqlQueries.removeAll() + let cte = CommonTableExpression(named: "cte", sql: "SELECT 42") + let association = Team.players.with(cte).filter(Column("playerId") == cte.all()) + let request = Team.including(all: association) + _ = try Row.fetchAll(db, request) + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "team" + """, + """ + WITH "cte" AS (SELECT 42) \ + SELECT *, "parentId" AS "grdb_parentId" \ + FROM "player" \ + WHERE ("playerId" = (SELECT * FROM "cte")) AND ("parentId" = 1) + """]) + } + } + } + // Return SELECT queries, but omit schema queries. private func isSelectQuery(_ query: String) -> Bool { return query.contains("SELECT") && !query.contains("sqlite_") && !query.contains("pragma_table_xinfo") From f9b554d00a137274a7b6bbc95b604e88e46018a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 07:55:20 +0100 Subject: [PATCH 21/60] Merge AggregateJoinableRequest into DerivableRequest Also put distinct(), limit(_:offset:) and with(_:) into DerivableRequest --- .../Request/Association/Association.swift | 48 ++++++------ .../Association/AssociationAggregate.swift | 10 +-- .../Request/QueryInterfaceRequest.swift | 60 ++------------- .../Request/RequestProtocols.swift | 75 +++++++++++++++++-- 4 files changed, 103 insertions(+), 90 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index a7fb1563c..105e3ca48 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -314,29 +314,7 @@ extension Association where Self: AggregatingRequest { } } -// MARK: - AssociationToOne - -/// The base protocol for all associations that define a one-to-one connection. -public protocol AssociationToOne: Association { } - -extension AssociationToOne { - public func forKey(_ key: String) -> Self { - let associationKey = SQLAssociationKey.fixedSingular(key) - return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) - } -} - -// MARK: - AssociationToMany - -/// The base protocol for all associations that define a one-to-many connection. -public protocol AssociationToMany: Association, AggregateJoinableRequest { } - -extension AssociationToMany { - public func forKey(_ key: String) -> Self { - let associationKey = SQLAssociationKey.fixedPlural(key) - return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) - } - +extension Association where Self: DerivableRequest { /// Creates an association for returns distinct rows. public func distinct() -> Self { mapDestinationRelation { $0.with(\.isDistinct, true) } @@ -356,3 +334,27 @@ extension AssociationToMany { mapDestinationRelation { $0.with(\.ctes[cte.tableName], cte.cte) } } } + +// MARK: - AssociationToOne + +/// The base protocol for all associations that define a one-to-one connection. +public protocol AssociationToOne: Association { } + +extension AssociationToOne { + public func forKey(_ key: String) -> Self { + let associationKey = SQLAssociationKey.fixedSingular(key) + return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) + } +} + +// MARK: - AssociationToMany + +/// The base protocol for all associations that define a one-to-many connection. +public protocol AssociationToMany: Association { } + +extension AssociationToMany { + public func forKey(_ key: String) -> Self { + let associationKey = SQLAssociationKey.fixedPlural(key) + return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) + } +} diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 371a77e8c..1118f8648 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -215,7 +215,7 @@ public struct AssociationAggregate { /// SQL selection, or in the HAVING clause. /// - It helps implementing aggregate operators such as `&&`, `+`, etc. func prepare(_ request: inout Request) -> SQLExpression - where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + where Request: DerivableRequest, Request.RowDecoder == RowDecoder { preparation.prepare(&request) } @@ -262,7 +262,7 @@ extension AssociationAggregate: Refinable { /// It only exists as support for `AssociationAggregate.prepare(_:)`. private class AssociationAggregatePreparation { func prepare(_ request: inout Request) -> SQLExpression - where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + where Request: DerivableRequest, Request.RowDecoder == RowDecoder { fatalError("subclass must override") } @@ -281,7 +281,7 @@ private class BasePreparation: } override func prepare(_ request: inout Request) -> SQLExpression - where Request: AggregateJoinableRequest, Request.RowDecoder == Association.OriginRowDecoder + where Request: DerivableRequest, Request.RowDecoder == Association.OriginRowDecoder { let tableAlias = TableAlias() request = request @@ -305,7 +305,7 @@ private class MapPreparation: AssociationAggregatePreparation(_ request: inout Request) -> SQLExpression - where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + where Request: DerivableRequest, Request.RowDecoder == RowDecoder { transform(base.prepare(&request)) } @@ -335,7 +335,7 @@ private class CombinePreparation: AssociationAggregatePreparation(_ request: inout Request) -> SQLExpression - where Request: AggregateJoinableRequest, Request.RowDecoder == RowDecoder + where Request: DerivableRequest, Request.RowDecoder == RowDecoder { let lhsExpression = lhs.prepare(&request) let rhsExpression = rhs.prepare(&request) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 50a303612..0ec8e991c 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -298,71 +298,21 @@ extension QueryInterfaceRequest: TableRequest { } } -extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { } -extension QueryInterfaceRequest: AggregateJoinableRequest where RowDecoder: TableRecord { } - -extension QueryInterfaceRequest { - /// Creates a request which returns distinct rows. - /// - /// // SELECT DISTINCT * FROM player - /// var request = Player.all() - /// request = request.distinct() - /// - /// // SELECT DISTINCT name FROM player - /// var request = Player.select(Column("name")) - /// request = request.distinct() +extension QueryInterfaceRequest: DerivableRequest { public func distinct() -> QueryInterfaceRequest { with(\.relation.isDistinct, true) } - /// Creates a request which fetches *limit* rows, starting at *offset*. - /// - /// // SELECT * FROM player LIMIT 1 - /// var request = Player.all() - /// request = request.limit(1) - /// - /// Any previous limit is replaced. - public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { + public func limit(_ limit: Int, offset: Int?) -> QueryInterfaceRequest { with(\.relation.limit, SQLLimit(limit: limit, offset: offset)) } - /// Returns a request which embeds the common table expression. - /// - /// If a common table expression with the same table name had already been - /// embedded, it is replaced by the new one. - /// - /// For example, you can build a request that fetches all chats with their - /// latest message: - /// - /// let latestMessageRequest = Message - /// .annotated(with: max(Column("date"))) - /// .group(Column("chatID")) - /// - /// let latestMessageCTE = CommonTableExpression( - /// named: "latestMessage", - /// request: latestMessageRequest) - /// - /// let latestMessage = Chat.association( - /// to: latestMessageCTE, - /// on: { chat, latestMessage in - /// chat[Column("id")] == latestMessage[Column("chatID")] - /// }) - /// - /// // WITH latestMessage AS - /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) - /// // SELECT chat.*, latestMessage.* - /// // FROM chat - /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID - /// let request = Chat.all() - /// .with(latestMessageCTE) - /// .including(optional: latestMessage) - /// - /// - parameter cte: A common table expression. - /// - returns: A request. public func with(_ cte: CommonTableExpression) -> Self { with(\.relation.ctes[cte.tableName], cte.cte) } - +} + +extension QueryInterfaceRequest { /// Creates a request bound to type RowDecoder. /// /// The returned request can fetch if the type RowDecoder is fetchable (Row, diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index de3af7149..c926c0a05 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -590,14 +590,75 @@ extension JoinableRequest { // MARK: - DerivableRequest /// The base protocol for all requests that can be refined. -public protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { } +public protocol DerivableRequest: AggregatingRequest, FilteredRequest, + JoinableRequest, OrderedRequest, + SelectionRequest, TableRequest +{ + /// Creates a request which returns distinct rows. + /// + /// // SELECT DISTINCT * FROM player + /// var request = Player.all() + /// request = request.distinct() + /// + /// // SELECT DISTINCT name FROM player + /// var request = Player.select(Column("name")) + /// request = request.distinct() + func distinct() -> Self + + /// Creates a request which fetches *limit* rows, starting at *offset*. + /// + /// // SELECT * FROM player LIMIT 10 OFFSET 20 + /// var request = Player.all() + /// request = request.limit(10, offset: 20) + /// + /// Any previous limit is replaced. + func limit(_ limit: Int, offset: Int?) -> Self + + /// Returns a request which embeds the common table expression. + /// + /// If a common table expression with the same table name had already been + /// embedded, it is replaced by the new one. + /// + /// For example, you can build a request that fetches all chats with their + /// latest message: + /// + /// let latestMessageRequest = Message + /// .annotated(with: max(Column("date"))) + /// .group(Column("chatID")) + /// + /// let latestMessageCTE = CommonTableExpression( + /// named: "latestMessage", + /// request: latestMessageRequest) + /// + /// let latestMessage = Chat.association( + /// to: latestMessageCTE, + /// on: { chat, latestMessage in + /// chat[Column("id")] == latestMessage[Column("chatID")] + /// }) + /// + /// // WITH latestMessage AS + /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) + /// // SELECT chat.*, latestMessage.* + /// // FROM chat + /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID + /// let request = Chat.all() + /// .with(latestMessageCTE) + /// .including(optional: latestMessage) + func with(_ cte: CommonTableExpression) -> Self +} -// MARK: - AggregateJoinableRequest - -/// The base protocol for all requests that can use association aggregates. -public protocol AggregateJoinableRequest: AggregatingRequest & JoinableRequest & SelectionRequest & TableRequest { } - -extension AggregateJoinableRequest { +extension DerivableRequest { + /// Creates a request which fetches *limit* rows. + /// + /// // SELECT * FROM player LIMIT 1 + /// var request = Player.all() + /// request = request.limit(1) + /// + /// Any previous limit is replaced. + public func limit(_ limit: Int) -> Self { + self.limit(limit, offset: nil) + } + private func annotated(with aggregate: AssociationAggregate) -> Self { var request = self let expression = aggregate.prepare(&request) From d4fc1d9566d2539e6e5f2184ce26fd963277cb8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 08:15:40 +0100 Subject: [PATCH 22/60] Update documentation for the new Association/DerivableRequest powers --- Documentation/AssociationsBasics.md | 46 ++++++++++- .../GoodPracticesForDesigningRecordTypes.md | 78 +++++-------------- 2 files changed, 66 insertions(+), 58 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 45bfc6b5c..ec89dd9f7 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -25,6 +25,7 @@ GRDB Associations - [Filtering Associations] - [Sorting Associations] - [Ordered Associations] + - [Further Refinements to Asssociations to Many] - [Columns Selected by an Association] - [Table Aliases] - [Refining Association Requests] @@ -780,6 +781,7 @@ Fetch requests do not visit the database until you fetch values from them. This - [Filtering Associations] - [Sorting Associations] - [Ordered Associations] +- [Further Refinements to Asssociations to Many] - [Columns Selected by an Association] - [Table Aliases] - [Refining Association Requests] @@ -855,14 +857,22 @@ Before we describe them in detail, let's see a few requests they can build: let request = Author .including(all: Author.books) +/// All authors with their three most popular books +let request = Author + .including(all: Author.books.order(Column("popularity").desc).limit(3)) + +/// All authors with their awarded books +let request = Author + .including(all: Author.books.having(Book.awards.isEmpty == false)) + /// All books with their respective author let request = Book .including(required: Book.author) /// All books with their respective author, sorted by title let request = Book - .order(Column("title")) .including(required: Book.author) + .order(Column("title")) /// All books written by a French author let request = Book @@ -1235,6 +1245,39 @@ let teamInfos = try Team .fetchAll(db) ``` +## Further Refinements to Asssociations to Many + +Associations included with the `including(all:)` method support more refinements: + +```swift +struct AuthorInfo: FetchableRecord, Decodable { + var author: Author + var books: [Book] +} + +// Limit +let authorInfos = try Author + .including(all: Author.books.order(Column("popularity").desc).limit(3)) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) + +// Association aggregates +let authorInfos = try Author + .including(all: Author.books.having(Book.awards.isEmpty == false)) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) + +// Common table expressions +let cte = CommonTableExpression(...) +let authorInfos = try Author + .including(all: Author.books.with(cte)...) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) +``` + +See [Association Aggregates] and [common table expressions] for more information. + +> :warning: **Warning**: Those refinements are only available with `including(all:)`. You will get a fatal error if you use them with other joining methods (`including(required:)`, etc.) ## Columns Selected by an Association @@ -2447,6 +2490,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone [Self Joins]: #self-joins [Ordered Associations]: #ordered-associations +[Further Refinements to Asssociations to Many]: #further-refinements-to-asssociations-to-many [The Types of Associations]: #the-types-of-associations [FetchableRecord]: ../README.md#fetchablerecord-protocols [migration]: Migrations.md diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 9c20bfac7..1717ebc8b 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -166,7 +166,7 @@ extension Author { } ``` -Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol: +Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol: ```swift // For a non-codable record @@ -180,29 +180,30 @@ extension Author { > :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol. -The `DerivableRequest` protocol generally lets you filter, sort, and join or include associations (we'll talk about associations in the [Compose Records] chapter below). - -Here is how you define those requests: +The `DerivableRequest` protocol generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc. ```swift -// Some requests of Author --------------------v +// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~ extension DerivableRequest where RowDecoder == Author { - - /// Returns a request for all authors ordered by name, in a localized - /// case-insensitive fashion + /// Order authors by name, in a localized case-insensitive fashion func orderByName() -> Self { let name = Author.Columns.name return order(name.collating(.localizedCaseInsensitiveCompare)) } - /// Returns a request for all authors from a country + /// Filters authors from a country func filter(country: String) -> Self { filter(Author.Columns.country == country) } + + /// Filters authors with at least one book + func havingBooks() -> Self { + having(Author.books.isEmpty == false) + } } ``` -Those methods defined on the `DerivableRequest` protocol hide intimate database details. They allow you to compose database requests in a fluent style: +Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style: ```swift try dbQueue.read { db in @@ -214,72 +215,35 @@ try dbQueue.read { db in .filter(country: "France") .fetchAll(db) - let sortedSpanishAuthors: [Author] = try Author.all() + let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all() .filter(country: "Spain") + .havingBooks() .orderByName() .fetchAll(db) } ``` -Those customized request methods are also available on record associations, because associations conform to the `DerivableRequest` protocol: +Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate `Author` requests, as in the examples just above, but also associations to `Author`: ```swift -// Some requests of Book +// Book requests extension DerivableRequest where RowDecoder == Book { - /// Returns a request for all books from a country - func filter(authorCountry: String) -> Self { + /// Filters books from a country + func filter(country: String) -> Self { // A book is from a country if it can be - // joined with an author from that country: - // ---------------------------v + // joined to an author from that country: + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ joining(required: Book.author.filter(country: authorCountry)) } } try dbQueue.read { db in - let italianBooks = try Book.all() - .filter(authorCountry: "Italy") + let italianBooks: [Book] = try Book.all() + .filter(country: "Italy") .fetchAll(db) } ``` -Not *every requests* can be expressed on `DerivableRequest`. For example, [Association Aggregates] are out of scope. When this happens, define your requests in a constrained extension to `QueryInterfaceRequest`: - -```swift -// More requests of Author -------------------------v -extension QueryInterfaceRequest where RowDecoder == Author { - /// Returns a request for all authors with at least one book - func havingBooks() -> QueryInterfaceRequest { - having(Author.books.isEmpty == false) - } -} -``` - -Those requests defined on `QueryInterfaceRequest` still compose fluently: - -```swift -try dbQueue.read { db in - let sortedFrenchAuthorsHavingBooks = try Author.all() - .filter(country: "France") - .havingBooks() // <- - .orderByName() - .fetchAll(db) -} -``` - -Finally, when it happens that a request only makes sense when defined on the Record type itself, just go ahead and define a static method or property of your Record type: - -```swift -extension MySingletonRecord { - /// The one any only record stored in the database - static let shared = all().limit(1) -} - -let singleton = try dbQueue.read { db - try MySingletonRecord.shared.fetchOne(db) -} -``` - - ## Compose Records We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author. From a655974eb0e96127cf84b8e08aa35884f0f0112e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 14:10:10 +0100 Subject: [PATCH 23/60] Let joined associations use CTEs --- GRDB/QueryInterface/SQL/SQLRelation.swift | 22 ++++++--- .../SQLGeneration/SQLQueryGenerator.swift | 2 +- GRDB/Utils/OrderedDictionary.swift | 46 +++++++++++++------ 3 files changed, 48 insertions(+), 22 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 18455d4da..b1a18ec49 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -132,10 +132,6 @@ struct SQLRelation { if relation.limit != nil { fatalError("Can't join an association with a LIMIT clause") } - if relation.ctes.isEmpty == false { - // TODO: maybe we could lift ctes up to the base relation - fatalError("Not implemented: joining an association that embeds a common table expression") - } case .all: break } @@ -169,6 +165,7 @@ struct SQLRelation { #warning("TODO: turn into DatabasePromise<[SQLExpression]>? like havingExpressionPromise") var filterPromise: DatabasePromise = DatabasePromise(value: nil) var ordering: SQLRelation.Ordering = SQLRelation.Ordering() + var ctes: OrderedDictionary = [:] // See also `allCTEs` var children: OrderedDictionary = [:] // Properties below MUST NOT be used when joining to-one associations. @@ -177,7 +174,6 @@ struct SQLRelation { var groupPromise: DatabasePromise<[SQLExpression]>? var havingExpressionPromise: DatabasePromise? var limit: SQLLimit? - var ctes: OrderedDictionary = [:] } extension SQLRelation { @@ -309,6 +305,18 @@ extension SQLRelation { } } + /// All common table expressions, including those of joined children. + var allCTEs: OrderedDictionary { + children.values.reduce(into: ctes) { (ctes, child) in + switch child.kind { + case .all, .bridge: + break + case .oneOptional, .oneRequired: + ctes.merge(child.relation.allCTEs, uniquingKeysWith: { (_, new) in new }) + } + } + } + /// Returns a relation extended with an association. /// /// This method provides support for public joining methods such @@ -1032,12 +1040,12 @@ extension SQLRelation { selectionPromise: mergedSelectionPromise, filterPromise: mergedFilterPromise, ordering: mergedOrdering, + ctes: mergedCTEs, children: mergedChildren, isDistinct: mergedDistinct, groupPromise: mergedGroupPromise, havingExpressionPromise: mergedHavingExpressionPromise, - limit: mergedLimit, - ctes: mergedCTEs) + limit: mergedLimit) } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 61bee4b80..869cbda07 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -588,7 +588,7 @@ private struct SQLQualifiedRelation { // Copy other flags limit = relation.limit isDistinct = relation.isDistinct - ctes = relation.ctes + ctes = relation.allCTEs } /// See SQLQueryGenerator.rowAdapter(_:) diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index 0d82ba25c..4e2b6dfa5 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -119,6 +119,36 @@ struct OrderedDictionary { return OrderedDictionary(keys: keys, dictionary: dictionary) } + mutating func merge( + _ other: S, + uniquingKeysWith combine: (Value, Value) throws -> Value) + rethrows + where S: Sequence, S.Element == (Key, Value) + { + for (key, value) in other { + if let current = self[key] { + self[key] = try combine(current, value) + } else { + self[key] = value + } + } + } + + mutating func merge( + _ other: S, + uniquingKeysWith combine: (Value, Value) throws -> Value) + rethrows + where S: Sequence, S.Element == (key: Key, value: Value) + { + for (key, value) in other { + if let current = self[key] { + self[key] = try combine(current, value) + } else { + self[key] = value + } + } + } + func merging( _ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value) @@ -126,13 +156,7 @@ struct OrderedDictionary { where S: Sequence, S.Element == (Key, Value) { var result = self - for (key, value) in other { - if let current = result[key] { - result[key] = try combine(current, value) - } else { - result[key] = value - } - } + try result.merge(other, uniquingKeysWith: combine) return result } @@ -143,13 +167,7 @@ struct OrderedDictionary { where S: Sequence, S.Element == (key: Key, value: Value) { var result = self - for (key, value) in other { - if let current = result[key] { - result[key] = try combine(current, value) - } else { - result[key] = value - } - } + try result.merge(other, uniquingKeysWith: combine) return result } } From 4583bbfa9095800a6e4587d59745acd296578497 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 14:10:43 +0100 Subject: [PATCH 24/60] Test for joined associations that use CTEs --- .../CommonTableExpressionTests.swift | 160 ++++++++++++++++++ 1 file changed, 160 insertions(+) diff --git a/Tests/GRDBTests/CommonTableExpressionTests.swift b/Tests/GRDBTests/CommonTableExpressionTests.swift index a204b7e07..0689d0105 100644 --- a/Tests/GRDBTests/CommonTableExpressionTests.swift +++ b/Tests/GRDBTests/CommonTableExpressionTests.swift @@ -619,4 +619,164 @@ class CommonTableExpressionTests: GRDBTestCase { """) } } + + func testAssociation() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamId", .integer).references("team") + } + try db.create(table: "award") { t in + t.autoIncrementedPrimaryKey("id") + t.column("playerId", .integer).references("player") + } + struct Team: TableRecord { } + struct Player: TableRecord { + static let team = belongsTo(Team.self) + } + struct Award: TableRecord { + static let player = belongsTo(Player.self) + static let team = hasOne(Team.self, through: player, using: Player.team) + } + + do { + // CTE on association + let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") + let request = Award + .joining(optional: Award.player.with(cte)) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, """ + WITH "cte" AS (SELECT 1) \ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerId" + """) + } + + do { + // CTE on hasOneThrough association + let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") + let request = Award + .joining(optional: Award.team.with(cte)) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, """ + WITH "cte" AS (SELECT 1) \ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerId" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamId" + """) + } + + do { + // CTE on pivot of hasOneThrough association + let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") + let team = Award.hasOne(Team.self, through: Award.player.with(cte), using: Player.team) + let request = Award + .joining(optional: team) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, """ + WITH "cte" AS (SELECT 1) \ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerId" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamId" + """) + } + + do { + // Distinct CTEs on association and main request + let cte1 = CommonTableExpression(named: "cte1", sql: "SELECT 1") + let cte2 = CommonTableExpression(named: "cte2", sql: "SELECT 2") + let request = Award + .with(cte1) + .joining(optional: Award.player.with(cte2)) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, """ + WITH "cte1" AS (SELECT 1), \ + "cte2" AS (SELECT 2) \ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerId" + """) + } + + do { + // Conflicting CTEs. The rule is: the last one wins. + + do { + // Conflicting CTE on association and main request + let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1") + let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2") + let request = Award + .with(cte1) + .joining(optional: Award.player.with(cte2)) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, """ + WITH "cte" AS (SELECT 2) \ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerId" + """) + } + + do { + // Conflicting CTE on two associations + let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1") + let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2") + let request = Award + .joining(optional: Award.player.with(cte1)) + .joining(optional: Award.team.with(cte2)) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, """ + WITH "cte" AS (SELECT 2) \ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerId" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamId" + """) + } + + do { + // Conflicting CTE on two associations + let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1") + let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2") + let request = Award + .joining(optional: Award.team.with(cte1)) + .joining(optional: Award.player.with(cte2)) + _ = try Row.fetchAll(db, request) + // There's a trick here. The last CTE wins, and the last cte + // is cte1: it is plugged on top of Award.player, where cte2 + // is attached. + XCTAssertEqual(lastSQLQuery, """ + WITH "cte" AS (SELECT 1) \ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerId" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamId" + """) + } + + do { + // Conflicting CTE on two associations + let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1") + let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2") + let request = Award + .joining(optional: Award.player.forKey("player1").with(cte1)) + .joining(optional: Award.player.forKey("player2").with(cte2)) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, """ + WITH "cte" AS (SELECT 2) \ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" "player1" ON "player1"."id" = "award"."playerId" \ + LEFT JOIN "player" "player2" ON "player2"."id" = "award"."playerId" + """) + } + } + } + } } From 4dd804289402eefeffdd43f328b5d9e11ee13642 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 14:21:35 +0100 Subject: [PATCH 25/60] Make it possible to decode arrays of scalars from including(all:) --- GRDB/Record/FetchableRecord+Decodable.swift | 3 +- ...ciationPrefetchingCodableRecordTests.swift | 80 +++++++++++++++++++ .../AssociationPrefetchingSQLTests.swift | 31 +++++++ 3 files changed, 113 insertions(+), 1 deletion(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index bdfd96c45..6437d4e1e 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -51,7 +51,8 @@ private struct _RowDecoder: Decoder { func singleValueContainer() throws -> SingleValueDecodingContainer { guard let key = codingPath.last else { - fatalError("single value decoding from database row is not supported") + // Decoding an array of scalars from rows: pick the first column + return ColumnDecoder(row: row, columnIndex: 0, codingPath: codingPath) } guard let index = row.index(forColumn: key.stringValue) else { // Don't use DecodingError.keyNotFound: diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index 64cfea4d9..3c800ccd0 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -230,6 +230,86 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { } } + func testIncludingAllHasManyScalar() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + // Plain request + do { + let request = A + .including(all: A + .hasMany(B.self) + .select(Column("colb2")) + .distinct() + .order(Column("colb2"))) + .orderByPrimaryKey() + + // Array + do { + struct Record: FetchableRecord, Decodable, Equatable { + var a: A + var bs: [Int64] + } + + // Record.fetchAll + do { + let records = try Record.fetchAll(db, request) + XCTAssertEqual(records, [ + Record( + a: A(row: ["cola1": 1, "cola2": "a1"]), + bs: [1]), + Record( + a: A(row: ["cola1": 2, "cola2": "a2"]), + bs: [2]), + Record( + a: A(row: ["cola1": 3, "cola2": "a3"]), + bs: []), + ]) + } + + // Record.fetchOne + do { + let record = try Record.fetchOne(db, request)! + XCTAssertEqual(record, Record( + a: A(row: ["cola1": 1, "cola2": "a1"]), + bs: [1])) + } + } + + // Set + do { + struct Record: FetchableRecord, Decodable, Equatable { + var a: A + var bs: Set + } + + // Record.fetchAll + do { + let records = try Record.fetchAll(db, request) + XCTAssertEqual(records, [ + Record( + a: A(row: ["cola1": 1, "cola2": "a1"]), + bs: [1]), + Record( + a: A(row: ["cola1": 2, "cola2": "a2"]), + bs: [2]), + Record( + a: A(row: ["cola1": 3, "cola2": "a3"]), + bs: []), + ]) + } + + // Record.fetchOne + do { + let record = try Record.fetchOne(db, request)! + XCTAssertEqual(record, Record( + a: A(row: ["cola1": 1, "cola2": "a1"]), + bs: [1])) + } + } + } + } + } + func testIncludingAllHasManyIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 52b17be15..6666ed177 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -157,6 +157,37 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } + func testIncludingAllHasManyScalar() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + // Plain request + do { + let request = A + .including(all: A + .hasMany(B.self) + .select(Column("colb2")) + .distinct() + .order(Column("colb2"))) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "a" ORDER BY "cola1" + """, + """ + SELECT DISTINCT "colb2", "colb2" AS "grdb_colb2" \ + FROM "b" \ + WHERE "colb2" IN (1, 2, 3) \ + ORDER BY "colb2" + """]) + } + } + } + func testIncludingAllHasManyWithCompoundForeignKey() throws { // We can use the CTE technique let dbQueue = try makeDatabaseQueue() From f4b7d99aab022d462d5d9d442f00d0a1bacfd2d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 19:59:47 +0100 Subject: [PATCH 26/60] Remove warning about associations that use CTEs --- Documentation/AssociationsBasics.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index ec89dd9f7..f9ddac789 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -25,7 +25,7 @@ GRDB Associations - [Filtering Associations] - [Sorting Associations] - [Ordered Associations] - - [Further Refinements to Asssociations to Many] + - [Further Refinements to Associations] - [Columns Selected by an Association] - [Table Aliases] - [Refining Association Requests] @@ -781,7 +781,7 @@ Fetch requests do not visit the database until you fetch values from them. This - [Filtering Associations] - [Sorting Associations] - [Ordered Associations] -- [Further Refinements to Asssociations to Many] +- [Further Refinements to Associations] - [Columns Selected by an Association] - [Table Aliases] - [Refining Association Requests] @@ -1245,9 +1245,9 @@ let teamInfos = try Team .fetchAll(db) ``` -## Further Refinements to Asssociations to Many +## Further Refinements to Associations -Associations included with the `including(all:)` method support more refinements: +Associations support more refinements: ```swift struct AuthorInfo: FetchableRecord, Decodable { @@ -1255,13 +1255,13 @@ struct AuthorInfo: FetchableRecord, Decodable { var books: [Book] } -// Limit +// Limit: all authors with their three most popular books let authorInfos = try Author .including(all: Author.books.order(Column("popularity").desc).limit(3)) .asRequest(of: AuthorInfo.self) .fetchAll(db) -// Association aggregates +// Association aggregates: all authors with their awarded books let authorInfos = try Author .including(all: Author.books.having(Book.awards.isEmpty == false)) .asRequest(of: AuthorInfo.self) @@ -1277,7 +1277,7 @@ let authorInfos = try Author See [Association Aggregates] and [common table expressions] for more information. -> :warning: **Warning**: Those refinements are only available with `including(all:)`. You will get a fatal error if you use them with other joining methods (`including(required:)`, etc.) +> :warning: **Warning**: associations refined with `limit`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc. ## Columns Selected by an Association @@ -2490,7 +2490,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone [Self Joins]: #self-joins [Ordered Associations]: #ordered-associations -[Further Refinements to Asssociations to Many]: #further-refinements-to-asssociations-to-many +[Further Refinements to Associations]: #further-refinements-to-associations [The Types of Associations]: #the-types-of-associations [FetchableRecord]: ../README.md#fetchablerecord-protocols [migration]: Migrations.md From e08df854ddc8b7f3afd3a9769d9f010dbb711406 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 20:50:17 +0100 Subject: [PATCH 27/60] Lower the tone about record responsabilities --- Documentation/GoodPracticesForDesigningRecordTypes.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 1717ebc8b..4d8b51270 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -139,11 +139,7 @@ That's it. The `Author` type can read and write in the `author` database table. > } > ``` -Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*. - -Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type". - -> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table. +Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table! ## Define Record Requests @@ -660,7 +656,6 @@ Instead, have a look at [Database Observation]: [Django]: https://docs.djangoproject.com/en/2.0/topics/db/ [record protocols]: ../README.md#record-protocols-overview [Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns -[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle [Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth [Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule [Why Adopt GRDB?]: WhyAdoptGRDB.md From 42718db49d5ccec289751a6448a6cbc2bdf6bbce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 21:11:36 +0100 Subject: [PATCH 28/60] Documentation --- .../Association/AssociationAggregate.swift | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 1118f8648..2cdc2ea6e 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -257,9 +257,16 @@ extension AssociationAggregate: Refinable { // MARK: - AssociationAggregatePreparation -/// An abstract class that workarounds the lack of generic closures in Swift. +/// An abstract class that only exists as support for +/// `AssociationAggregate.prepare(_:)`, which needs to prepare both query +/// interface requests and associations through their conformance +/// to `DerivableRequest`: /// -/// It only exists as support for `AssociationAggregate.prepare(_:)`. +/// aggregate.prepare(&request) +/// aggregate.prepare(&association) +/// +/// We could have used a generic closure instead of this class... if only Swift +/// would support generic closures. private class AssociationAggregatePreparation { func prepare(_ request: inout Request) -> SQLExpression where Request: DerivableRequest, Request.RowDecoder == RowDecoder @@ -269,6 +276,7 @@ private class AssociationAggregatePreparation { } // swiftlint:disable:next colon +/// Prepares a request so that it can use association aggregates. private class BasePreparation: AssociationAggregatePreparation { @@ -283,10 +291,19 @@ private class BasePreparation: override func prepare(_ request: inout Request) -> SQLExpression where Request: DerivableRequest, Request.RowDecoder == Association.OriginRowDecoder { + // The fundamental request that supports association aggregate: + // + // SELECT parent.* + // LEFT JOIN child ON child.parentID = parent.id + // GROUP BY parent.id let tableAlias = TableAlias() request = request .joining(optional: association.aliased(tableAlias)) .groupByPrimaryKey() + + // The fundamental request can now be annotated, or filtered in the + // having clause, with the association aggregate expression: + // MIN(child.score), COUNT(DISTINCT child.id), etc. return expression.qualified(with: tableAlias) } } From 4521e6b37ded8a840e559c83a08a6c262e018df6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 21:25:27 +0100 Subject: [PATCH 29/60] Make filterPromise an optional promise instead of a promise of optional This way, filterPromise and havingExpressionPromise have the same type --- GRDB/QueryInterface/SQL/SQLRelation.swift | 19 +++++++++++-------- .../SQLGeneration/SQLQueryGenerator.swift | 12 ++++++------ 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index b1a18ec49..eefd8827c 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -162,8 +162,7 @@ struct SQLRelation { var source: SQLSource var selectionPromise: DatabasePromise<[SQLSelection]> - #warning("TODO: turn into DatabasePromise<[SQLExpression]>? like havingExpressionPromise") - var filterPromise: DatabasePromise = DatabasePromise(value: nil) + var filterPromise: DatabasePromise? var ordering: SQLRelation.Ordering = SQLRelation.Ordering() var ctes: OrderedDictionary = [:] // See also `allCTEs` var children: OrderedDictionary = [:] @@ -231,7 +230,7 @@ extension SQLRelation: Refinable { func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { map(\.filterPromise) { promise in DatabasePromise { db in - if let filter = try promise.resolve(db) { + if let filter = try promise?.resolve(db) { return try filter && predicate(db) } else { return try predicate(db) @@ -972,12 +971,16 @@ extension SQLRelation { } // Filter: merge with AND - let mergedFilterPromise = DatabasePromise { db in - switch try (self.filterPromise.resolve(db), other.filterPromise.resolve(db)) { - case let (lhs?, rhs?): return lhs && rhs - case let (nil, expr?), let (expr?, nil): return expr - case (nil, nil): return nil + let mergedFilterPromise: DatabasePromise? + switch (filterPromise, other.filterPromise) { + case let (lhs?, rhs?): + mergedFilterPromise = DatabasePromise { + try lhs.resolve($0) && rhs.resolve($0) } + case let (nil, promise?), let (promise?, nil): + mergedFilterPromise = promise + case (nil, nil): + mergedFilterPromise = nil } // Children: merge recursively diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 869cbda07..3ab6480c4 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -46,7 +46,7 @@ struct SQLQueryGenerator: Refinable { } } - let filter = try relation.filterPromise.resolve(context.db) + let filter = try relation.filterPromise?.resolve(context.db) if let filter = filter { sql += " WHERE " sql += try filter.sql(context) @@ -157,7 +157,7 @@ struct SQLQueryGenerator: Refinable { } // The filter knows better - guard let filter = try relation.filterPromise.resolve(db), + guard let filter = try relation.filterPromise?.resolve(db), let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias) else { return selectedRegion @@ -213,7 +213,7 @@ struct SQLQueryGenerator: Refinable { var sql = try commonTableExpressionsPrefix(context) sql += try "DELETE FROM " + relation.source.sql(context) - if let filter = try relation.filterPromise.resolve(db) { + if let filter = try relation.filterPromise?.resolve(db) { sql += " WHERE " sql += try filter.sql(context) } @@ -299,7 +299,7 @@ struct SQLQueryGenerator: Refinable { .map { try $0.sql(context) } .joined(separator: ", ") - if let filter = try relation.filterPromise.resolve(db) { + if let filter = try relation.filterPromise?.resolve(db) { sql += " WHERE " sql += try filter.sql(context) } @@ -538,7 +538,7 @@ private struct SQLQualifiedRelation { } } - let filterPromise: DatabasePromise + let filterPromise: DatabasePromise? /// The ordering of source, not including ordering of joined relations private let sourceOrdering: SQLRelation.Ordering @@ -761,7 +761,7 @@ private struct SQLQualifiedJoin: Refinable { conditions.append(expression) } - if let filter = try relation.filterPromise.resolve(context.db) { + if let filter = try relation.filterPromise?.resolve(context.db) { conditions.append(filter.qualified(with: rightAlias)) } From ed3d1e1ac413396774e031d447dc0290f17bafc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 21:36:09 +0100 Subject: [PATCH 30/60] selectOnly() clears the isDistinct flag --- GRDB/QueryInterface/SQL/SQLRelation.swift | 4 +++- .../SQLGeneration/SQLQueryGenerator.swift | 18 +++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index eefd8827c..a3f9b3b60 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -203,10 +203,12 @@ extension SQLRelation: Refinable { select { _ in expressions.map { .expression($0) } } } - /// Removes all selections from chidren + /// Sets the selection, removes all selections from chidren, and clears the + /// `isDistinct` flag. func selectOnly(_ selection: [SQLSelection]) -> Self { self .select(selection) + .with(\.isDistinct, false) .map(\.children) { children in children.mapValues { child in child.map(\.relation) { $0.selectOnly([]) } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 3ab6480c4..20c854d6b 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -524,8 +524,7 @@ private struct SQLQualifiedRelation { /// The selection from source, not including selection of joined relations private var sourceSelectionPromise: DatabasePromise<[SQLSelection]> - #warning("TODO: decide if selectOnly() should reset this flag") - let isDistinct: Bool + var isDistinct: Bool /// The full selection, including selection of joined relations var selectionPromise: DatabasePromise<[SQLSelection]> { @@ -651,14 +650,20 @@ private struct SQLQualifiedRelation { return (adapter: adapter, endIndex: endIndex) } - /// Removes all selections from joins + /// Sets the selection, removes all selections from joins, and clears the + /// `isDistinct` flag. func selectOnly(_ selection: [SQLSelection]) -> Self { let sourceSelectionPromise = DatabasePromise(value: selection.map { $0.qualified(with: source.alias) }) return self .with(\.sourceSelectionPromise, sourceSelectionPromise) - .map(\.joins, { $0.mapValues { $0.selectOnly([]) } }) + .with(\.isDistinct, false) + .map(\.joins, { joins in + joins.mapValues { join in + join.map(\.relation) { $0.selectOnly([]) } + } + }) } } @@ -720,11 +725,6 @@ private struct SQLQualifiedJoin: Refinable { try sql(context, leftAlias: leftAlias, allowingInnerJoin: true) } - /// Removes all selections from joins - func selectOnly(_ selection: [SQLSelection]) -> SQLQualifiedJoin { - map(\.relation) { $0.selectOnly(selection) } - } - private func sql( _ context: SQLGenerationContext, leftAlias: TableAlias, From b22afd7f17b0ac67675d3742ff291a2ce9ef030e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Mar 2021 21:56:47 +0100 Subject: [PATCH 31/60] CHANGELOG --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 123824552..c5ce50ee9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,8 +75,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Development Branch - **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases + - **Fixed**: [#934](https://github.com/groue/GRDB.swift/pull/934): Fix a crash in the ValueObservation publisher +- **New**: [#936](https://github.com/groue/GRDB.swift/pull/936): Complete Associations and the DerivableRequest Protocol + +- **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936). + +- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a simpler [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions. + ## 5.5.0 Released March 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0) From 1f27e724c9a3839b70ab549cbb5a68490a028bc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Mar 2021 07:21:43 +0100 Subject: [PATCH 32/60] Open a door --- GRDB/QueryInterface/SQL/SQLRelation.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index a3f9b3b60..9439d6c30 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -127,7 +127,7 @@ struct SQLRelation { fatalError("Can't join an association that selects DISTINCT rows") } if relation.groupPromise != nil || relation.havingExpressionPromise != nil { - fatalError("Can't join an association with a GROUP BY clause") + fatalError("Not implemented: join an association with a GROUP BY clause") } if relation.limit != nil { fatalError("Can't join an association with a LIMIT clause") From 04d35381a61ea55d8733cae5b1023bc132c2fca4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Mar 2021 07:57:57 +0100 Subject: [PATCH 33/60] Documentation --- Documentation/AssociationsBasics.md | 132 +++++++++++++++++++++++----- 1 file changed, 108 insertions(+), 24 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index f9ddac789..9e6a1e472 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1249,35 +1249,118 @@ let teamInfos = try Team Associations support more refinements: -```swift -struct AuthorInfo: FetchableRecord, Decodable { - var author: Author - var books: [Book] -} +- `limit` + + Fetch all authors with their three most popular books: + + ```swift + struct AuthorInfo: FetchableRecord, Decodable { + var author: Author + var books: [Book] + } + + let mostPopularBooks = Author.books + .order(Column("popularity").desc) + .limit(3) + + let authorInfos: [AuthorInfo] = try Author + .including(all: mostPopularBooks) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) + ``` -// Limit: all authors with their three most popular books -let authorInfos = try Author - .including(all: Author.books.order(Column("popularity").desc).limit(3)) - .asRequest(of: AuthorInfo.self) - .fetchAll(db) +- `distinct` + + Fetch all authors with the kinds of books they write (novels, poems, plays, etc): + + ```swift + struct AuthorInfo: Decodable, FetchableRecord { + var author: Author + var bookKinds: Set + } + + let distinctBookKinds = Author.books + .select(Column("kind")) + .distinct() + .forKey("bookKinds") + + let authorInfos: [AuthorInfo] = try Author + .including(all: distinctBookKinds) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) + ``` -// Association aggregates: all authors with their awarded books -let authorInfos = try Author - .including(all: Author.books.having(Book.awards.isEmpty == false)) - .asRequest(of: AuthorInfo.self) - .fetchAll(db) +- `group`, `having` + + Fetch all authors with the year of their latest book for each kind (novels, poems, plays, etc): + + ```swift + struct BookKindInfo: Decodable, FetchableRecord { + var kind: Book.Kind + var maxYear: Int + } + + struct AuthorInfo: Decodable, FetchableRecord { + var author: Author + var bookKindInfos: [BookKindInfo] + } + + let bookKindInfos = Author.books + .select( + Column("kind"), + max(Column("year")).forKey("maxYear")) + .group(Column("kind")) + .forKey("bookKindInfos") + + let authorInfos: [AuthorInfo] = try Author + .including(all: bookKindInfos) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) + ``` -// Common table expressions -let cte = CommonTableExpression(...) -let authorInfos = try Author - .including(all: Author.books.with(cte)...) - .asRequest(of: AuthorInfo.self) - .fetchAll(db) -``` +- [Association Aggregates] + + Fetch all authors with their awarded books: + + ```swift + struct AuthorInfo: FetchableRecord, Decodable { + var author: Author + var awardedBooks: [Book] + } + + let awardedBooks = Author.books + .having(Book.awards.isEmpty == false) + .forKey("awardedBooks") + + let authorInfos: [AuthorInfo] = try Author + .including(all: awardedBooks) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) + ``` -See [Association Aggregates] and [common table expressions] for more information. +- [Common Table Expressions] + + Association can use their own CTEs: + + ```swift + struct AuthorInfo: FetchableRecord, Decodable { + var author: Author + var specialBooks: [Book] + } + + let specialCTE = CommonTableExpression(...) + let specialBooks = Author.books + .with(specialCTE) + ... // use the CTE in the book association + .forKey("specialBooks") + + let authorInfos = try Author + .including(all: specialBooks) + .asRequest(of: AuthorInfo.self) + .fetchAll(db) + ``` -> :warning: **Warning**: associations refined with `limit`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc. +> :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc. ## Columns Selected by an Association @@ -2541,4 +2624,5 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [ValueObservation]: ../README.md#valueobservation [FAQ]: ../README.md#faq-associations [common table expressions]: CommonTableExpressions.md +[Common Table Expressions]: CommonTableExpressions.md [Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions From 9bda5fc41bab7908c202fe9d838925dd9994bcc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Mar 2021 08:27:29 +0100 Subject: [PATCH 34/60] Move the Further Refinements to Associations chapter --- Documentation/AssociationsBasics.md | 55 +++++++++++++++-------------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 9e6a1e472..744db01e4 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -25,8 +25,8 @@ GRDB Associations - [Filtering Associations] - [Sorting Associations] - [Ordered Associations] - - [Further Refinements to Associations] - [Columns Selected by an Association] + - [Further Refinements to Associations] - [Table Aliases] - [Refining Association Requests] - [Fetching Values from Associations] @@ -781,8 +781,8 @@ Fetch requests do not visit the database until you fetch values from them. This - [Filtering Associations] - [Sorting Associations] - [Ordered Associations] -- [Further Refinements to Associations] - [Columns Selected by an Association] +- [Further Refinements to Associations] - [Table Aliases] - [Refining Association Requests] @@ -1245,6 +1245,32 @@ let teamInfos = try Team .fetchAll(db) ``` +## Columns Selected by an Association + +By default, associated records include all their columns: + +```swift +// SELECT book.*, author.* +// FROM book +// JOIN author ON author.id = book.authorId +let request = Book.including(required: Book.author) +``` + +**The selection can be changed for each individual request, or for all requests including a given type.** + +To specify the selection of an associated record in a specific request, use the `select` method: + +```swift +// SELECT book.*, author.id, author.name +// FROM book +// JOIN author ON author.id = book.authorId +let restrictedAuthor = Book.author.select(Column("id"), Column("name")) +let request = Book.including(required: restrictedAuthor) +``` + +To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request). + + ## Further Refinements to Associations Associations support more refinements: @@ -1362,31 +1388,6 @@ Associations support more refinements: > :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc. -## Columns Selected by an Association - -By default, associated records include all their columns: - -```swift -// SELECT book.*, author.* -// FROM book -// JOIN author ON author.id = book.authorId -let request = Book.including(required: Book.author) -``` - -**The selection can be changed for each individual request, or for all requests including a given type.** - -To specify the selection of an associated record in a specific request, use the `select` method: - -```swift -// SELECT book.*, author.id, author.name -// FROM book -// JOIN author ON author.id = book.authorId -let restrictedAuthor = Book.author.select(Column("id"), Column("name")) -let request = Book.including(required: restrictedAuthor) -``` - -To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request). - ## Table Aliases From cdbca5d2150b487d00184ce4b96b31ae70ee1197 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Mar 2021 08:29:14 +0100 Subject: [PATCH 35/60] Fix sample code --- Documentation/AssociationsBasics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 744db01e4..1456abede 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1321,7 +1321,7 @@ Associations support more refinements: Fetch all authors with the year of their latest book for each kind (novels, poems, plays, etc): ```swift - struct BookKindInfo: Decodable, FetchableRecord { + struct BookKindInfo: Decodable { var kind: Book.Kind var maxYear: Int } From 5e61d38272061ac220e2919fbfad7a0ba53d1a0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 08:56:53 +0100 Subject: [PATCH 36/60] Add a Record Types Hide Intimate Database Details chapter --- CHANGELOG.md | 2 + .../GoodPracticesForDesigningRecordTypes.md | 47 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5ce50ee9..06c95b472 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,6 +84,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a simpler [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions. +- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a simpler [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details) chapter. + ## 5.5.0 Released March 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 4d8b51270..ecce17065 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -9,6 +9,7 @@ To support this guide, we'll design a simple library application that lets the u - [Trust SQLite More Than Yourself] - [Persistable Record Types are Responsible for Their Tables] +- [Record Types Hide Intimate Database Details] - [Define Record Requests] - [Compose Records] - [How to Design Database Managers] @@ -142,6 +143,51 @@ That's it. The `Author` type can read and write in the `author` database table. Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table! +## Record Types Hide Intimate Database Details + +The application uses `Book` and `Author` as regular structs, using their properties. In our case, it happens that each of those properties matches a column in the database: `Book.title`, `Author.id`, etc. + +It happens that raw database columns are not a very good fit. For example, GPS coordinates are stored in two distinct latitude and longitude columns, but the standard way to deal with such coordinatee is a single `CLLocationCoordinate2D` struct. + +When this happens, keep column properties private, and provide sensible accessors instead: + +```swift +struct Place: Codable { + var id: Int64? + var name: String + private var latitude: CLLocationDegrees + private var longitude: CLLocationDegrees + + var coordinate: CLLocationCoordinate2D { + get { + CLLocationCoordinate2D(latitude: latitude, longitude: longitude) + } + set { + latitude = newValue.latitude + longitude = newValue.longitude + } + } +} +``` + +Such encapsulation of raw columns can happen in many other cases. A second example? The record blow exposes a `price: Decimal` ($12.00), and hides the integer column that stores a quantity of cents (1200) (this allows SQLite to compute exact sums of prices): + +```swift +struct Product: Codable { + var id: Int64? + var name: String + private var priceCents: Int + + var price: Decimal { + get { Decimal(priceCents) / 100 } + set { cents = NSDecimalNumber(decimal: newValue * 100).intValue } + } +} +``` + +Record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. + + ## Define Record Requests Now that we have record types that are able to read and write in the database, we'd like to put them to good use. @@ -672,6 +718,7 @@ Instead, have a look at [Database Observation]: [TransactionObserver]: ../README.md#transactionobserver-protocol [Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself [Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables +[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details [Define Record Requests]: #define-record-requests [Compose Records]: #compose-records [How to Design Database Managers]: #how-to-design-database-managers From 609fcf6a6d7b4b8d13a6e17777b4afb3619de87a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 08:57:46 +0100 Subject: [PATCH 37/60] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06c95b472..ce5be3524 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,7 +84,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a simpler [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions. -- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a simpler [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details) chapter. +- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details). ## 5.5.0 From 9e974a4c96084a3d68018550ddddad1e084492f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 08:58:39 +0100 Subject: [PATCH 38/60] Fix typo --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index ecce17065..d13a3dbff 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -170,7 +170,7 @@ struct Place: Codable { } ``` -Such encapsulation of raw columns can happen in many other cases. A second example? The record blow exposes a `price: Decimal` ($12.00), and hides the integer column that stores a quantity of cents (1200) (this allows SQLite to compute exact sums of prices): +Such encapsulation of raw columns can happen in many other cases. A second example? The record below exposes a `price: Decimal` ($12.00), and hides the integer column that stores a quantity of cents (1200) (this allows SQLite to compute exact sums of prices): ```swift struct Product: Codable { From eb0983facd3da700d539382c1356f8e41c54c330 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 08:59:40 +0100 Subject: [PATCH 39/60] Wording --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index d13a3dbff..c8daaaa6d 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -170,7 +170,7 @@ struct Place: Codable { } ``` -Such encapsulation of raw columns can happen in many other cases. A second example? The record below exposes a `price: Decimal` ($12.00), and hides the integer column that stores a quantity of cents (1200) (this allows SQLite to compute exact sums of prices): +Such encapsulation of raw columns can happen in many other cases. A second example? The record below exposes a `price: Decimal` ($12.00), and hides the integer column that stores a quantity of cents (1200). Integer columns allow SQLite to compute exact sums of prices when needed: ```swift struct Product: Codable { From 850040c51e06913f8dedfdcf6ae0f28a61d65c33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 09:02:00 +0100 Subject: [PATCH 40/60] Fix typo --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index c8daaaa6d..3b1facd2f 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -147,7 +147,7 @@ Now that `Author` and `Book` can read and write in their own database tables, th The application uses `Book` and `Author` as regular structs, using their properties. In our case, it happens that each of those properties matches a column in the database: `Book.title`, `Author.id`, etc. -It happens that raw database columns are not a very good fit. For example, GPS coordinates are stored in two distinct latitude and longitude columns, but the standard way to deal with such coordinatee is a single `CLLocationCoordinate2D` struct. +It happens that raw database columns are not a very good fit. For example, GPS coordinates are stored in two distinct latitude and longitude columns, but the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct. When this happens, keep column properties private, and provide sensible accessors instead: From 4de5059373d3c8667e38ce1c0b0a5b93e05008d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 12:55:25 +0100 Subject: [PATCH 41/60] Improve "Record Types Hide Intimate Database Details" --- .../GoodPracticesForDesigningRecordTypes.md | 124 ++++++++++++------ 1 file changed, 82 insertions(+), 42 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 3b1facd2f..0f2f1795a 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -145,47 +145,84 @@ Now that `Author` and `Book` can read and write in their own database tables, th ## Record Types Hide Intimate Database Details -The application uses `Book` and `Author` as regular structs, using their properties. In our case, it happens that each of those properties matches a column in the database: `Book.title`, `Author.id`, etc. +The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.) -It happens that raw database columns are not a very good fit. For example, GPS coordinates are stored in two distinct latitude and longitude columns, but the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct. +Sometimes, it happens that raw database columns name and types are not a very good fit for the application. -When this happens, keep column properties private, and provide sensible accessors instead: +Let's look at three examples: -```swift -struct Place: Codable { - var id: Int64? - var name: String - private var latitude: CLLocationDegrees - private var longitude: CLLocationDegrees +1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.): + + ```swift + try db.create(table: "book") { t in + ... + t.column("kind", .text).notNull() + } + ``` - var coordinate: CLLocationCoordinate2D { - get { - CLLocationCoordinate2D(latitude: latitude, longitude: longitude) + In Swift, it is not a good practice to use `String` for the type of the `Book.kind` property. We want an enum instead: + + ```swift + struct Book: Codable { + enum Kind: String, Codable { + case novel, poems, essay, play } - set { - latitude = newValue.latitude - longitude = newValue.longitude + var id: Int64? + var authorId: Int64 + var title: String + var kind: Kind + } + ``` + + In order to make it possible to use `Book.Kind` in book requests, we add this conformance: + + ```swift + extension Book.Kind: DatabaseValueConvertible { } + ``` + + > :bulb: Thanks to the enum property, it is impossible to store unknown book kinds into the database. + +2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct. + + When this happens, keep column properties private, and provide sensible accessors instead: + + ```swift + struct Place: Codable { + var id: Int64? + var name: String + private var latitude: CLLocationDegrees + private var longitude: CLLocationDegrees + + var coordinate: CLLocationCoordinate2D { + get { + CLLocationCoordinate2D(latitude: latitude, longitude: longitude) + } + set { + latitude = newValue.latitude + longitude = newValue.longitude + } } } -} -``` + ``` + + > :bulb: Thanks to the `coordinate` property, the application -Such encapsulation of raw columns can happen in many other cases. A second example? The record below exposes a `price: Decimal` ($12.00), and hides the integer column that stores a quantity of cents (1200). Integer columns allow SQLite to compute exact sums of prices when needed: +3. The record below exposes a `price: Decimal` ($12.00), and hides the integer column that stores a quantity of cents (1200). Integer columns allow SQLite to compute exact sums of prices when needed: -```swift -struct Product: Codable { - var id: Int64? - var name: String - private var priceCents: Int - - var price: Decimal { - get { Decimal(priceCents) / 100 } - set { cents = NSDecimalNumber(decimal: newValue * 100).intValue } + ```swift + struct Product: Codable { + var id: Int64? + var name: String + private var priceCents: Int + + var price: Decimal { + get { Decimal(priceCents) / 100 } + set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue } + } } -} -``` + ``` -Record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. +> :bulb: Record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. ## Define Record Requests @@ -243,6 +280,20 @@ extension DerivableRequest where RowDecoder == Author { having(Author.books.isEmpty == false) } } + +// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~ +extension DerivableRequest where RowDecoder == Book { + /// Filters books by kind + func filter(kind: Book.Kind) -> Self { + filter(Book.Columns.kind == kind) + } + + /// Filters books from a country + func filter(country: String) -> Self { + // Books have no country column. But their author does: + joining(required: Book.author.filter(country: authorCountry)) + } +} ``` Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style: @@ -265,20 +316,9 @@ try dbQueue.read { db in } ``` -Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate `Author` requests, as in the examples just above, but also associations to `Author`: +Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(country:)` for books, above, uses the `filter(country:)` for authors. ```swift -// Book requests -extension DerivableRequest where RowDecoder == Book { - /// Filters books from a country - func filter(country: String) -> Self { - // A book is from a country if it can be - // joined to an author from that country: - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - joining(required: Book.author.filter(country: authorCountry)) - } -} - try dbQueue.read { db in let italianBooks: [Book] = try Book.all() .filter(country: "Italy") From 1d5604815da03c0152a45ba36571cec4ad9f7a7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 13:05:11 +0100 Subject: [PATCH 42/60] Improve "Record Types Hide Intimate Database Details" --- .../GoodPracticesForDesigningRecordTypes.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 0f2f1795a..cdb91f176 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -147,7 +147,7 @@ Now that `Author` and `Book` can read and write in their own database tables, th The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.) -Sometimes, it happens that raw database columns name and types are not a very good fit for the application. +Sometimes, it happens that raw database column names and types are not a very good fit for the application. Let's look at three examples: @@ -180,7 +180,7 @@ Let's look at three examples: extension Book.Kind: DatabaseValueConvertible { } ``` - > :bulb: Thanks to the enum property, it is impossible to store unknown book kinds into the database. + > :bulb: Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database. 2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct. @@ -205,9 +205,9 @@ Let's look at three examples: } ``` - > :bulb: Thanks to the `coordinate` property, the application + > :bulb: Private properties make it possible to hide raw columns from the rest of the application. -3. The record below exposes a `price: Decimal` ($12.00), and hides the integer column that stores a quantity of cents (1200). Integer columns allow SQLite to compute exact sums of prices when needed: +3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices. ```swift struct Product: Codable { @@ -221,8 +221,10 @@ Let's look at three examples: } } ``` + + > :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface. -> :bulb: Record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. +**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. ## Define Record Requests From de2a37fb89d8ea8ef59d5ab2bcdb66914692ca2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 13:06:05 +0100 Subject: [PATCH 43/60] Improve "Record Types Hide Intimate Database Details" --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index cdb91f176..197ce9d88 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -160,7 +160,7 @@ Let's look at three examples: } ``` - In Swift, it is not a good practice to use `String` for the type of the `Book.kind` property. We want an enum instead: + In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead: ```swift struct Book: Codable { From 1a2a6898eba2818ed50e7645c91f46b7c4b41814 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 13:07:16 +0100 Subject: [PATCH 44/60] Improve "Record Types Hide Intimate Database Details" --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 197ce9d88..8db2002ba 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -174,7 +174,7 @@ Let's look at three examples: } ``` - In order to make it possible to use `Book.Kind` in book requests, we add this conformance: + In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance: ```swift extension Book.Kind: DatabaseValueConvertible { } From fe437fb7e3d4a0d7e56e74cb9d23905548d24dc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 13:21:25 +0100 Subject: [PATCH 45/60] Improve "Record Types Hide Intimate Database Details" --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 8db2002ba..240796e53 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -224,7 +224,7 @@ Let's look at three examples: > :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface. -**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. +**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database. ## Define Record Requests From 464b77bdcdd66ac5a180b564141e2bd5f45dc715 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 10 Mar 2021 13:25:25 +0100 Subject: [PATCH 46/60] Improve "Record Types Hide Intimate Database Details" --- Documentation/GoodPracticesForDesigningRecordTypes.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 240796e53..6cd1117ec 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -180,7 +180,7 @@ Let's look at three examples: extension Book.Kind: DatabaseValueConvertible { } ``` - > :bulb: Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database. + > :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database. 2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct. @@ -775,3 +775,4 @@ Instead, have a look at [Database Observation]: [Codable Record]: ../README.md#codable-records [CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types [Combine Support]: Combine.md +[Value]: ../README.md#values From 8388486289b917b6d7bdb8d3b4878223367ee0fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 08:32:32 +0100 Subject: [PATCH 47/60] TODO --- TODO.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO.md b/TODO.md index e03a53130..3beeb13a2 100644 --- a/TODO.md +++ b/TODO.md @@ -15,6 +15,8 @@ ## Features +- [ ] Property wrapper that decodes dictionaries (but how to tell the key column?) +- [ ] Talk about singletons - [X] See if SQLITE_FCNTL_DATA_VERSION could help working around the lack of snapshots in order to avoid double initial fetch of ValueObservation. Result: no, it does not look it returns values that are comparable between two distinct SQLite connections (from the initial reader, and from the writer thhat starts the observation) - [ ] Grab all FTS tokens in a string - [ ] GRDB 6: decoding errors From 8b1efb2c80a30a7d46c996833b3bd5b3041eb544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 11:31:32 +0100 Subject: [PATCH 48/60] Single-Row Tables guide --- CHANGELOG.md | 4 +- .../GoodPracticesForDesigningRecordTypes.md | 9 + Documentation/SingleRowTables.md | 240 ++++++++++++++++++ TODO.md | 1 - 4 files changed, 252 insertions(+), 2 deletions(-) create mode 100644 Documentation/SingleRowTables.md diff --git a/CHANGELOG.md b/CHANGELOG.md index ce5be3524..c21ff372b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -82,10 +82,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936). -- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a simpler [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions. +- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has an updated [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions. - **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details). +- **Documentation update**: A new [Single-Row Tables](Documentation/SingleRowTables.md) guide provides guidance for designing tables that store configuration values, user preferences, and generally some global application state. + ## 5.5.0 Released March 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 6cd1117ec..12a2c11ee 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -10,6 +10,7 @@ To support this guide, we'll design a simple library application that lets the u - [Trust SQLite More Than Yourself] - [Persistable Record Types are Responsible for Their Tables] - [Record Types Hide Intimate Database Details] +- [Singleton Records] - [Define Record Requests] - [Compose Records] - [How to Design Database Managers] @@ -227,6 +228,13 @@ Let's look at three examples: **Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database. +## Singleton Records + +**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row. + +The recommended setup for such records is described in the [Single-Row Tables](SingleRowTables.md) guide. Go check it, and come back after! + + ## Define Record Requests Now that we have record types that are able to read and write in the database, we'd like to put them to good use. @@ -761,6 +769,7 @@ Instead, have a look at [Database Observation]: [Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself [Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables [Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details +[Singleton Records]: #singleton-records [Define Record Requests]: #define-record-requests [Compose Records]: #compose-records [How to Design Database Managers]: #how-to-design-database-managers diff --git a/Documentation/SingleRowTables.md b/Documentation/SingleRowTables.md new file mode 100644 index 000000000..e7a0fe51c --- /dev/null +++ b/Documentation/SingleRowTables.md @@ -0,0 +1,240 @@ +Single-Row Tables +================= + +Let's talk about database tables that should contain a single row. + +Such tables can store configuration values, user preferences, and generally some global application state. They are a suitable alternative to `UserDefaults` in some applications, especially when configuration refers to values found in other database tables, and database integrity is a concern. + +This guide helps you implementing a single-row table with GRDB, with recommendations on the database schema, migrations, and the design of a [record] type. + +- [The Single-Row Table] +- [The Single-Row Record] +- [Wrap-Up] + + +## The Single-Row Table + +As always with GRDB, everything starts at level of the database schema. Putting the robust SQLite on our side is always a good idea, because we have to write less code, and this helps shipping less bugs. + +We want to instruct SQLite that our table must never contain more than one row. We will never have to wonder what to do if we were unlucky enough to find two rows with conflicting values in this table. + +SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, either it contains a row. + +Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app perform an insert in case of a failed update (in the [The Single-Row Record] chapter). And we instruct SQLite to just replace the eventual existing row in case of conflicting inserts: + +```swift +// CREATE TABLE appConfiguration ( +// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1), +// flag BOOLEAN NOT NULL, +// ...) +try db.create(table: "appConfiguration") { t in + // Single row guarantee + t.column("id", .integer) + // Have inserts replace the existing row + .primaryKey(onConflict: .replace) + // Make sure the id column is always 1 + .check { $0 == 1 } + + // The configuration colums + t.column("flag", .boolean).notNull() + // ... other columns +} +``` + +When you use [migrations], you may wonder if it is a good idea or not to perform an initial insert just after the table is created. Well, this is not recommended: + +```swift +// NOT RECOMMENDED +migrator.registerMigration("appConfiguration") { db in + try db.create(table: "appConfiguration") { t in + // Single row guarantee + t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 } + + // Define sensible defaults for each column + t.column("flag", .boolean).notNull() + .defaults(to: false) + // ... other columns + } + + // Populate the table + try db.execute(sql: "INSERT INTO appConfiguration DEFAULT VALUES") +} +``` + +It is not a good idea to populate the table in a migration, for two reasons: + +1. This is not a hard guarantee that the table will never be empty. As a consequence, this won't prevent your Swift code from dealing with the possibility of a missing row. On top of that, the Swift code that deals with the missing row may not use the same default values as the SQLite schema (a [DRY] violation), with unclear consequences. + +2. Migrations that are shipped in the wild should *never* change, because you want to control the state of the databases installed on your users' devices, regardless of the application version they install first, regardless of how many application versions are skipped when they download an upgrade, etc. By inserting an initial row in a migration, you make it difficult for your application to adjust the sensible default values in the future, while keeping a clear idea of the various installation and upgrade scenarios. + +The recommended migration creates the table, nothing more: + +```swift +// RECOMMENDED +migrator.registerMigration("appConfiguration") { db in + try db.create(table: "appConfiguration") { t in + // Single row guarantee + t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 } + + // The configuration colums + t.column("flag", .boolean).notNull() + // ... other columns + } +} +``` + + +## The Single-Row Record + +Now that the database schema has been defined, we can define the [record] type that will help the application access the single row: + +```swift +struct AppConfiguration: Codable { + // Support for the single row guarantee + private var id = 1 + + // The configuration properties + var flag: Bool + // ... other properties +} +``` + +In case the database table would be empty, we need a default configuration: + +```swift +extension AppConfiguration { + /// The default configuration + static let `default` = AppConfiguration(flag: false, ...) +} +``` + +We make our record able to access the database: + +```swift +extension AppConfiguration: FetchableRecord, PersistableRecord { +``` + +We have seen in the [The Single-Row Table] chapter that by default, updates throw an error if the database table is empty. To avoid this error, we instruct GRDB to perform an insert in case of a failed update (see [Persistence Methods] for more information): + +```swift + // Customize the default PersistableRecord behavior + func update(_ db: Database, columns: Set) throws { + do { + try performUpdate(db, columns: columns) + } catch PersistenceError.recordNotFound { + // No row was updated: perform an insert + try performInsert(db) + } + } +``` + +The standard GRDB method `fetchOne` returns an optional which is nil when the database table is empty. As a convenience, let's define a method that returns a non-optional (replacing the missing row with `default`): + +```swift + /// Returns the persisted configuration, or the default one if the + /// database table is empty. + static func fetch(_ db: Database) throws -> AppConfiguration { + try fetchOne(db) ?? .default + } +} +``` + +And that's it! Now we can use our singleton record: + +```swift +// READ +let config = try dbQueue.read { db in + try AppConfiguration.fetch(db) +} +if config.flag { + // ... +} + +// WRITE +try dbQueue.write { db in + var config = try AppConfiguration.fetch(db) + + // Update some config values + try config.updateChanges(db) { + $0.flag = true + } + + // Other possible ways to write config: + try config.update(db) + try config.save(db) + try config.insert(db) +} +``` + +The three `update`, `save` and `insert` methods can be used interchangeably: all three make sure the configuration is stored in the database. + +The `updateChanges` method only updates the values changed by its closure argument (and performs an insert if the database table is empty). + +See [Persistence Methods] for more information. + + +## Wrap-Up + +We all love to copy and paste, don't we? Just customize the template code below: + +```swift +// Table creation +try db.create(table: "appConfiguration") { t in + // Single row guarantee + t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 } + + // The configuration colums + t.column("flag", .boolean).notNull() + // ... other columns +} +``` + +```swift +// +// AppConfiguration.swift +// + +import GRDB + +struct AppConfiguration: Codable { + // Support for the single row guarantee + private var id = 1 + + // The configuration properties + var flag: Bool + // ... other properties +} + +extension AppConfiguration { + /// The default configuration + static let `default` = AppConfiguration(flag: false, ...) +} + +// Database Access +extension AppConfiguration: FetchableRecord, PersistableRecord { + // Customize the default PersistableRecord behavior + func update(_ db: Database, columns: Set) throws { + do { + try performUpdate(db, columns: columns) + } catch PersistenceError.recordNotFound { + // No row was updated: perform an insert + try performInsert(db) + } + } + + /// Returns the persisted configuration, or the default one if the + /// database table is empty. + static func fetch(_ db: Database) throws -> AppConfiguration { + try fetchOne(db) ?? .default + } +} +``` + + +[migrations]: Migrations.md +[record]: ../README.md#records +[The Single-Row Table]: #the-single-row-table +[The Single-Row Record]: #the-single-row-record +[Wrap-Up]: #wrap-up +[DRY]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself +[Persistence Methods]: ../README.md#persistence-methods diff --git a/TODO.md b/TODO.md index 3beeb13a2..4b5798cae 100644 --- a/TODO.md +++ b/TODO.md @@ -16,7 +16,6 @@ ## Features - [ ] Property wrapper that decodes dictionaries (but how to tell the key column?) -- [ ] Talk about singletons - [X] See if SQLITE_FCNTL_DATA_VERSION could help working around the lack of snapshots in order to avoid double initial fetch of ValueObservation. Result: no, it does not look it returns values that are comparable between two distinct SQLite connections (from the initial reader, and from the writer thhat starts the observation) - [ ] Grab all FTS tokens in a string - [ ] GRDB 6: decoding errors From 6e7555514a82dfe248a31843c7a1c938663a99df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 13:48:25 +0100 Subject: [PATCH 49/60] More collection initializers from cursors - support for minimumCapacity - support for Dictionary (cursors with unique keys) --- CHANGELOG.md | 2 + GRDB/Core/Cursor.swift | 169 ++++++++++++++++++++++++++---- README.md | 38 ++++++- Tests/GRDBTests/CursorTests.swift | 58 ++++++++++ 4 files changed, 241 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c21ff372b..0f6330788 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,6 +80,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#936](https://github.com/groue/GRDB.swift/pull/936): Complete Associations and the DerivableRequest Protocol +- **New**: Database cursors can feed more standard Swift collections: `Array(cursor, minimumCapacity: ...)`, `Dictionary(uniqueKeysWithValues: cursor)`, etc` (see [Cursors](README.md#cursors)). + - **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936). - **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has an updated [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions. diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index a2d27d0f7..20219c60c 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -9,13 +9,16 @@ // //===----------------------------------------------------------------------===// -// MARK: - Array, Sequence, Dictionary, Set extensions +// MARK: - RangeReplaceableCollection, Sequence, Dictionary, Set extensions -extension Array { - /// Creates an array containing the elements of a cursor. +extension RangeReplaceableCollection { + /// Creates a collection containing the elements of a cursor. /// - /// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'") - /// let strings = try Array(cursor) // ["foo", "bar"] + /// // [String] + /// let cursor = try String.fetchCursor(db, ...) + /// let strings = try Array(cursor) + /// + /// - parameter cursor: The cursor whose elements feed the collection. @inlinable public init(_ cursor: C) throws where C.Element == Element { self.init() @@ -23,24 +26,161 @@ extension Array { append(element) } } + + /// Creates a collection containing the elements of a cursor. + /// + /// // [String] + /// let cursor = try String.fetchCursor(db, ...) + /// let strings = try Array(cursor, minimumCapacity: 100) + /// + /// - parameter cursor: The cursor whose elements feed the collection. + /// - parameter minimumCapacity: Prepares the returned collection to store + /// the specified number of elements. + @inlinable + public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { + self.init() + reserveCapacity(minimumCapacity) + while let element = try cursor.next() { + append(element) + } + } } extension Dictionary { /// Creates a new dictionary whose keys are the groupings returned by the /// given closure and whose values are arrays of the elements that returned /// each key. - public init(grouping values: C, by keyForValue: (C.Element) throws -> Key) + /// + /// // [Int64: [Player]] + /// let cursor = try Player.fetchCursor(db) + /// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID }) + /// + /// - parameter cursor: A cursor of values to group into a dictionary. + /// - parameter keyForValue: A closure that returns a key for each element + /// in the cursor. + public init(grouping cursor: C, by keyForValue: (C.Element) throws -> Key) throws where Value == [C.Element] { self.init() - while let value = try values.next() { + while let value = try cursor.next() { try self[keyForValue(value), default: []].append(value) } } + + /// Creates a new dictionary whose keys are the groupings returned by the + /// given closure and whose values are arrays of the elements that returned + /// each key. + /// + /// // [Int64: [Player]] + /// let cursor = try Player.fetchCursor(db) + /// let dictionary = try Dictionary( + /// minimumCapacity: 100, + /// grouping: cursor, + /// by: { $0.teamID }) + /// + /// - parameter minimumCapacity: The minimum number of key-value pairs that + /// the newly created dictionary should be able to store without + /// reallocating its storage buffer. + /// - parameter cursor: A cursor of values to group into a dictionary. + /// - parameter keyForValue: A closure that returns a key for each element + /// in the cursor. + public init(minimumCapacity: Int, grouping cursor: C, by keyForValue: (C.Element) throws -> Key) + throws where Value == [C.Element] + { + self.init(minimumCapacity: minimumCapacity) + while let value = try cursor.next() { + try self[keyForValue(value), default: []].append(value) + } + } + + /// Creates a new dictionary from the key-value pairs in the given cursor. + /// + /// You use this initializer to create a dictionary when you have a cursor + /// of key-value tuples with unique keys. Passing a cursor with duplicate + /// keys to this initializer results in a fatal error. + /// + /// // [Int64: Player] + /// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) } + /// let playerByID = try Dictionary(uniqueKeysWithValues: cursor) + /// + /// - parameter keysAndValues: A cursor of key-value pairs to use for the + /// new dictionary. Every key in `keysAndValues` must be unique. + /// - precondition: The cursor must not have duplicate keys. + public init(uniqueKeysWithValues keysAndValues: C) + throws where C.Element == (Key, Value) + { + self.init() + while let (key, value) = try keysAndValues.next() { + if updateValue(value, forKey: key) != nil { + fatalError("Duplicate values for key: '\(String(describing: key))'") + } + } + } + + /// Creates a new dictionary from the key-value pairs in the given cursor. + /// + /// You use this initializer to create a dictionary when you have a cursor + /// of key-value tuples with unique keys. Passing a cursor with duplicate + /// keys to this initializer results in a fatal error. + /// + /// // [Int64: Player] + /// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) } + /// let playerByID = try Dictionary( + /// minimumCapacity: 100, + /// uniqueKeysWithValues: cursor) + /// + /// - parameter minimumCapacity: The minimum number of key-value pairs that + /// the newly created dictionary should be able to store without + /// reallocating its storage buffer. + /// - parameter keysAndValues: A cursor of key-value pairs to use for the + /// new dictionary. Every key in `keysAndValues` must be unique. + /// - precondition: The cursor must not have duplicate keys. + public init(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: C) + throws where C.Element == (Key, Value) + { + self.init(minimumCapacity: minimumCapacity) + while let (key, value) = try keysAndValues.next() { + if updateValue(value, forKey: key) != nil { + fatalError("Duplicate values for key: '\(String(describing: key))'") + } + } + } +} + +extension Set { + /// Creates a set containing the elements of a cursor. + /// + /// // Set + /// let cursor = try String.fetchCursor(db, ...) + /// let strings = try Set(cursor) + /// + /// - parameter cursor: A cursor of values to gather into a set. + public init(_ cursor: C) throws where C.Element == Element { + self.init() + while let element = try cursor.next() { + insert(element) + } + } + + /// Creates a set containing the elements of a cursor. + /// + /// // Set + /// let cursor = try String.fetchCursor(db, ...) + /// let strings = try Set(cursor, minimumCapacity: 100) + /// + /// - parameter cursor: A cursor of values to gather into a set. + /// - parameter minimumCapacity: The minimum number of elements that the + /// newly created set should be able to store without reallocating its + /// storage buffer. + public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { + self.init(minimumCapacity: minimumCapacity) + while let element = try cursor.next() { + insert(element) + } + } } extension Sequence { - /// Returns a cursor over the concatenated results of mapping transform /// over self. public func flatMap( @@ -51,19 +191,6 @@ extension Sequence { } } -extension Set { - /// Creates a set containing the elements of a cursor. - /// - /// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'foo'") - /// let strings = try Set(cursor) // ["foo"] - public init(_ cursor: C) throws where C.Element == Element { - self.init() - while let element = try cursor.next() { - insert(element) - } - } -} - // MARK: - Cursor /// A type that supplies the values of some external resource, one at a time. diff --git a/README.md b/README.md index f1e3f4ddc..90b14381f 100644 --- a/README.md +++ b/README.md @@ -815,6 +815,38 @@ try dbQueue.read { db in - **Cursors are granted with direct access to SQLite,** unlike arrays and sets that have to take the time to copy database values. If you look after extra performance, you may prefer cursors. +- **Cursors can feed Swift collections**: + + Arrays and all types conforming to `RangeReplaceableCollection`: + + ```swift + // [String] + let cursor = try String.fetchCursor(db, ...) + let array = try Array(cursor) + ``` + + Sets: + + ```swift + // Set + let cursor = try Int.fetchCursor(db, ...) + let set = try Set(cursor) + ``` + + Dictionaries: + + ```swift + // [Int64: [Player]] + let cursor = try Player.fetchCursor(db) + let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID }) + + // [Int64: Player] + let cursor = try Player.fetchCursor(db).map { ($0.id, $0) } + let dictionary = try Dictionary(uniqueKeysWithValues: cursor) + ``` + + > :bulb: **Tip**: all those initializers accept an extra `minimumCapacity` argument which helps optimizing your app when you have an idea of the number of elements fetched by the cursor. + - **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.5/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 @@ -830,12 +862,8 @@ try dbQueue.read { db in .map { row in CLLocationCoordinate2D(latitude: row[0], longitude: row[1]) } - - // Turn cursors into arrays or sets: - let array = try Array(cursor) - let set = try Set(cursor) ``` - + - **Cursors are not Swift sequences.** That's because Swift sequences can't handle iteration errors, when reading SQLite results may fail at any time. - **Cursors require a little care**: diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index f2a8b6c3a..be78267a9 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -171,6 +171,46 @@ class CursorTests: GRDBTestCase { } } + func testRangeReplaceableCollection() throws { + func collect(_ cursor: Cur) throws -> Col + where Col: RangeReplaceableCollection, Cur: Cursor, Col.Element == Cur.Element + { + try Col(cursor) + } + + func collect(_ cursor: Cur, minimumCapacity: Int) throws -> Col + where Col: RangeReplaceableCollection, Cur: Cursor, Col.Element == Cur.Element + { + try Col(cursor, minimumCapacity: minimumCapacity) + } + + do { + let cursor = AnyCursor([1, 2, 1, 3]) + let collection: [Int] = try collect(cursor) + XCTAssertEqual(collection, [1, 2, 1, 3]) + } + + do { + let cursor = AnyCursor([1, 2, 1, 3]) + let collection: [Int] = try collect(cursor, minimumCapacity: 100) + XCTAssertEqual(collection, [1, 2, 1, 3]) + } + } + + func testSet() throws { + do { + let cursor = AnyCursor([1, 2, 1, 3]) + let set = try Set(cursor) + XCTAssertEqual(set, [1, 2, 3]) + } + + do { + let cursor = AnyCursor([1, 2, 1, 3]) + let set = try Set(cursor, minimumCapacity: 100) + XCTAssertEqual(set, [1, 2, 3]) + } + } + func testDictionaryGrouping() throws { do { let cursor = AnyCursor([]) @@ -187,5 +227,23 @@ class CursorTests: GRDBTestCase { let dictionary = try Dictionary(grouping: cursor, by: { $0 % 2 }) XCTAssertEqual(dictionary, [0: [4, 2], 1: [5, 3, 1]]) } + do { + let cursor = AnyCursor([1, 2, 3, 4, 5]) + let dictionary = try Dictionary(minimumCapacity: 100, grouping: cursor, by: { $0 % 2 }) + XCTAssertEqual(dictionary, [0: [2, 4], 1: [1, 3, 5]]) + } + } + + func testDictionaryUniqueKeysWithValues() throws { + do { + let cursor = AnyCursor([(1, "a"), (2, "b"), (3, "a")]) + let dictionary = try Dictionary(uniqueKeysWithValues: cursor) + XCTAssertEqual(dictionary, [1: "a", 2: "b", 3: "a"]) + } + do { + let cursor = AnyCursor([(1, "a"), (2, "b"), (3, "a")]) + let dictionary = try Dictionary(minimumCapacity: 100, uniqueKeysWithValues: cursor) + XCTAssertEqual(dictionary, [1: "a", 2: "b", 3: "a"]) + } } } From cb8611587cf7e2a2b139e90055f100e2e77deedf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 13:48:41 +0100 Subject: [PATCH 50/60] Fix Swiftlint warning --- .../Request/Association/AssociationAggregate.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 2cdc2ea6e..97820b2f8 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -275,10 +275,9 @@ private class AssociationAggregatePreparation { } } -// swiftlint:disable:next colon /// Prepares a request so that it can use association aggregates. private class BasePreparation: - AssociationAggregatePreparation + AssociationAggregatePreparation // swiftlint:disable:previous colon { private let association: Association private let expression: SQLExpression From 33174fce8e05b447f9ea42a71ab694f536fd2af5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 14:00:31 +0100 Subject: [PATCH 51/60] Documentation --- CHANGELOG.md | 2 +- README.md | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f6330788..27aacfc85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,7 +80,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#936](https://github.com/groue/GRDB.swift/pull/936): Complete Associations and the DerivableRequest Protocol -- **New**: Database cursors can feed more standard Swift collections: `Array(cursor, minimumCapacity: ...)`, `Dictionary(uniqueKeysWithValues: cursor)`, etc` (see [Cursors](README.md#cursors)). +- **New**: Database cursors can feed more standard Swift collections: `Array(cursor, minimumCapacity: ...)`, `Dictionary(uniqueKeysWithValues: cursor)`, etc (see [Cursors](README.md#cursors)). - **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936). diff --git a/README.md b/README.md index 90b14381f..a5807ae0e 100644 --- a/README.md +++ b/README.md @@ -815,9 +815,11 @@ try dbQueue.read { db in - **Cursors are granted with direct access to SQLite,** unlike arrays and sets that have to take the time to copy database values. If you look after extra performance, you may prefer cursors. -- **Cursors can feed Swift collections**: +- **Cursors can feed Swift collections.** - Arrays and all types conforming to `RangeReplaceableCollection`: + You will most of the time use `fetchAll` or `fetchSet` when you want an array or a set. For more specific needs, you may prefer one of the initializers below. All of them accept an extra optional `minimumCapacity` argument which helps optimizing your app when you have an idea of the number of elements in a cursor (the built-in `fetchAll` and `fetchSet` do not perform such an optimization). + + **Arrays** and all types conforming to `RangeReplaceableCollection`: ```swift // [String] @@ -825,7 +827,7 @@ try dbQueue.read { db in let array = try Array(cursor) ``` - Sets: + **Sets**: ```swift // Set @@ -833,7 +835,7 @@ try dbQueue.read { db in let set = try Set(cursor) ``` - Dictionaries: + **Dictionaries**: ```swift // [Int64: [Player]] @@ -844,8 +846,6 @@ try dbQueue.read { db in let cursor = try Player.fetchCursor(db).map { ($0.id, $0) } let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` - - > :bulb: **Tip**: all those initializers accept an extra `minimumCapacity` argument which helps optimizing your app when you have an idea of the number of elements fetched by the cursor. - **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.5/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`: From cc93f43ee4fae1c69c415d1730cae13a48f64f5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 14:24:47 +0100 Subject: [PATCH 52/60] Better introduction to DerivableRequest Also reintroduce extensions to QueryInterfaceRequest --- .../GoodPracticesForDesigningRecordTypes.md | 75 ++++++++++++++----- 1 file changed, 58 insertions(+), 17 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 12a2c11ee..aee684901 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -267,9 +267,34 @@ extension Author { } ``` +Those columns let you define more interesting requests: + +```swift +try dbQueue.read { db in + // Order authors by name, in a localized case-insensitive fashion + let sortedAuthors: [Author] = try Author.all() + .order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare)) + .fetchAll(db) + + // French authors + let frenchAuthors: [Author] = try Author.all() + .filter(Author.Columns.country == "France") + .fetchAll(db) + + // French authors who wrote at least one book, ordered by name + let frenchAuthors: [Author] = try Author.all() + .filter(Author.Columns.country == "France") + .having(Author.books.isEmpty == false) + .order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare)) + .fetchAll(db) +} +``` + > :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol. -The `DerivableRequest` protocol generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc. +When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable testability. + +To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc: ```swift // Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -290,20 +315,6 @@ extension DerivableRequest where RowDecoder == Author { having(Author.books.isEmpty == false) } } - -// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~ -extension DerivableRequest where RowDecoder == Book { - /// Filters books by kind - func filter(kind: Book.Kind) -> Self { - filter(Book.Columns.kind == kind) - } - - /// Filters books from a country - func filter(country: String) -> Self { - // Books have no country column. But their author does: - joining(required: Book.author.filter(country: authorCountry)) - } -} ``` Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style: @@ -326,16 +337,46 @@ try dbQueue.read { db in } ``` -Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(country:)` for books, above, uses the `filter(country:)` for authors. +Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors: ```swift +// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~ +extension DerivableRequest where RowDecoder == Book { + /// Filters books by kind + func filter(kind: Book.Kind) -> Self { + filter(Book.Columns.kind == kind) + } + + /// Filters books from a country + func filter(authorCountry: String) -> Self { + // Books do not have any country column. But their author has one. + // A book is from a country if it can be joined to an author from this country: + joining(required: Book.author.filter(country: authorCountry)) + } +} + try dbQueue.read { db in let italianBooks: [Book] = try Book.all() - .filter(country: "Italy") + .filter(authorCountry: "Italy") .fetchAll(db) } ``` +Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example: + +```swift +// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~ +extension QueryInterfaceRequest where RowDecoder == Author { + // Selects author ids + func id() -> QueryInterfaceRequest { + select(Author.Columns.id) + } +} + +// IDs of French authors +let ids: [Int64] = try Author.all().filter(country: "France").id().fetchAll(db) +``` + ## Compose Records We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author. From e1c71507140aed69b585cc388953626f17b3845b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 14:26:43 +0100 Subject: [PATCH 53/60] Documentation --- Documentation/GoodPracticesForDesigningRecordTypes.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index aee684901..52455c782 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -356,7 +356,8 @@ extension DerivableRequest where RowDecoder == Book { } try dbQueue.read { db in - let italianBooks: [Book] = try Book.all() + let italianNovels: [Book] = try Book.all() + .filter(kind: .novel) .filter(authorCountry: "Italy") .fetchAll(db) } From 65beb24d410c423be579ebc550b8ed64ae57ae98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 14:33:01 +0100 Subject: [PATCH 54/60] Simplify --- Documentation/GoodPracticesForDesigningRecordTypes.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 52455c782..e60e2bfe2 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -267,7 +267,7 @@ extension Author { } ``` -Those columns let you define more interesting requests: +Those columns let you define requests: ```swift try dbQueue.read { db in @@ -280,13 +280,6 @@ try dbQueue.read { db in let frenchAuthors: [Author] = try Author.all() .filter(Author.Columns.country == "France") .fetchAll(db) - - // French authors who wrote at least one book, ordered by name - let frenchAuthors: [Author] = try Author.all() - .filter(Author.Columns.country == "France") - .having(Author.books.isEmpty == false) - .order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare)) - .fetchAll(db) } ``` From 48e214b4b3c94a1bd427137f2edd61f2165644a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 14:42:51 +0100 Subject: [PATCH 55/60] Link to demo app tests --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index e60e2bfe2..43a521d74 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -285,7 +285,7 @@ try dbQueue.read { db in > :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol. -When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable testability. +When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift). To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc: From b331a715eff6442dd8844c01334834f59d57afe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 15:30:31 +0100 Subject: [PATCH 56/60] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27aacfc85..d182e4c61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,7 +86,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has an updated [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions. -- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details). +- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter of good practices: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details). - **Documentation update**: A new [Single-Row Tables](Documentation/SingleRowTables.md) guide provides guidance for designing tables that store configuration values, user preferences, and generally some global application state. From cab795a4a9883b4f0d99e9acf21825d2080e9ffb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 15:32:00 +0100 Subject: [PATCH 57/60] Wording --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 43a521d74..a2d0dd082 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -232,7 +232,7 @@ Let's look at three examples: **Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row. -The recommended setup for such records is described in the [Single-Row Tables](SingleRowTables.md) guide. Go check it, and come back after! +The recommended setup for such records is described in the [Single-Row Tables](SingleRowTables.md) guide. Go check it, and come back when you're done! ## Define Record Requests From ba9b4db197a35a84f7ddcbde40511291d82c2c1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 15:33:35 +0100 Subject: [PATCH 58/60] Fix typo --- Documentation/SingleRowTables.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/SingleRowTables.md b/Documentation/SingleRowTables.md index e7a0fe51c..b20516950 100644 --- a/Documentation/SingleRowTables.md +++ b/Documentation/SingleRowTables.md @@ -14,7 +14,7 @@ This guide helps you implementing a single-row table with GRDB, with recommendat ## The Single-Row Table -As always with GRDB, everything starts at level of the database schema. Putting the robust SQLite on our side is always a good idea, because we have to write less code, and this helps shipping less bugs. +As always with GRDB, everything starts at the level of the database schema. Putting the robust SQLite on our side is always a good idea, because we have to write less code, and this helps shipping less bugs. We want to instruct SQLite that our table must never contain more than one row. We will never have to wonder what to do if we were unlucky enough to find two rows with conflicting values in this table. From daab7aef2c8bc86586e83b90efcf0f2e76fb9870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 15:37:29 +0100 Subject: [PATCH 59/60] Fix typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a5807ae0e..7c56c9ee6 100644 --- a/README.md +++ b/README.md @@ -4455,8 +4455,8 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli SQLite arithmetic operators are derived from their Swift equivalent: ```swift - // SELECT ((temperature * 1.8) + 32) AS farenheit FROM planet - Planet.select((temperatureColumn * 1.8 + 32).forKey("farenheit")) + // SELECT ((temperature * 1.8) + 32) AS fahrenheit FROM planet + Planet.select((temperatureColumn * 1.8 + 32).forKey("fahrenheit")) ``` > :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. From 8548d7a72771605ee8102174823689df6ee640f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 12 Mar 2021 17:12:41 +0100 Subject: [PATCH 60/60] v5.6.0 --- CHANGELOG.md | 6 +++-- Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++--- README.md | 40 ++++++++++++++++----------------- Support/Info.plist | 2 +- 7 files changed, 32 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d182e4c61..19327d6a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases -- [Development Branch](#development-branch) +- `5.6.x` Releases - [5.6.0](#560) - `5.5.x` Releases - [5.5.0](#550) - `5.4.x` Releases - [5.4.0](#540) - `5.3.x` Releases - [5.3.0](#530) @@ -72,7 +72,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... -## Development Branch +## 5.6.0 + +Released March 12, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.5.0...v5.6.0) - **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 641a637ba..3bfe8ec22 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 532631aaf..a72b8720e 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -68,7 +68,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.5/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.6/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 319b5ad68..8183df08f 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.5.0' + s.version = '5.6.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 4275bd3ff..9f7b3bc6e 100644 --- a/Makefile +++ b/Makefile @@ -431,10 +431,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/v5.5.0 \ - --module-version 5.5.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.6.0 \ + --module-version 5.6.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.5/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.6/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 7c56c9ee6..b9c55fb40 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: March 3, 2021 • version 5.5.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: March 12, 2021 • version 5.6.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.2+ / Xcode 11.4+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.2+** | **v5.5.0** | +| **Swift 5.2+** | **v5.6.0** | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -278,7 +278,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.5/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.6/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -472,7 +472,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.6/Structs/Configuration.html) for more details. ## Database Pools @@ -552,7 +552,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.6/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -612,7 +612,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/5.5/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/5.6/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -847,7 +847,7 @@ try dbQueue.read { db in let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.5/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/5.6/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 @@ -926,7 +926,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/5.5/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/5.6/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: @@ -1211,7 +1211,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/5.5/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1620,7 +1620,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/5.5/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.6/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1734,7 +1734,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/5.5/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/5.6/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -2511,7 +2511,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.6/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()`. @@ -2892,7 +2892,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.6/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.6/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.6/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). @@ -4357,7 +4357,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -5044,7 +5044,7 @@ try Player.customRequest().fetchAll(db) // [Player] - 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/5.5/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.6/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -6218,7 +6218,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.5/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/5.6/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. @@ -6228,7 +6228,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/5.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.6/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7348,7 +7348,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.5/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.5/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.6/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.6/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: @@ -8023,7 +8023,7 @@ When this is the case, there are two possible explanations: try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) ``` -For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.6/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8185,4 +8185,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.5/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.6/Structs/SQLRequest.html diff --git a/Support/Info.plist b/Support/Info.plist index dfcf4dcd8..869d97c6a 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.5.0 + 5.6.0 CFBundleSignature ???? CFBundleVersion