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 01/34] 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 02/34] 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 03/34] 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 04/34] 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 05/34] 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 06/34] 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 07/34] 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 08/34] 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 09/34] 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 10/34] 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 11/34] 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 12/34] 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 13/34] 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 14/34] 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 15/34] 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 16/34] 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 17/34] 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 18/34] 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 19/34] 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 20/34] 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 21/34] 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 22/34] 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 23/34] 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 24/34] 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 25/34] 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 26/34] 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 27/34] 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 28/34] 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 29/34] 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 30/34] 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 31/34] 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 32/34] 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 33/34] 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 34/34] 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