From b180fc37bbf43a982e7c1b97a046ad922bccc49d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 10:38:47 +0100 Subject: [PATCH 01/26] Trim associations --- GRDB.xcodeproj/project.pbxproj | 24 ++-- .../Association/Association.swift | 131 ++++++++++-------- .../Association/AssociationRequest.swift | 49 ------- .../Association/BelongsToAssociation.swift | 49 ++++--- .../Association/HasManyAssociation.swift | 47 ++++--- .../Association/HasOneAssociation.swift | 49 ++++--- ...AssociationQuery.swift => JoinQuery.swift} | 37 ++--- GRDB/QueryInterface/QueryInterfaceQuery.swift | 30 ++-- .../QueryInterfaceRequest+Association.swift | 19 +-- .../QueryInterfaceRequest.swift | 4 +- GRDB/QueryInterface/QueryOrdering.swift | 2 +- GRDBCipher.xcodeproj/project.pbxproj | 18 +-- GRDBCustom.xcodeproj/project.pbxproj | 18 +-- 13 files changed, 231 insertions(+), 246 deletions(-) delete mode 100644 GRDB/QueryInterface/Association/AssociationRequest.swift rename GRDB/QueryInterface/Association/{AssociationQuery.swift => JoinQuery.swift} (88%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 0240ba7cc..22a639917 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -271,12 +271,9 @@ 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; - 5653EB0F20944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; - 5653EB1020944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; - 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; - 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; - 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; - 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; + 5653EB1520944C7C00F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* JoinQuery.swift */; }; + 5653EB1620944C7C00F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* JoinQuery.swift */; }; + 5653EB1720944C7C00F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* JoinQuery.swift */; }; 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; 5653EB1920944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; @@ -1011,8 +1008,7 @@ 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; 5653EAFA20944C7B00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; - 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; - 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; + 5653EAFE20944C7C00F46237 /* JoinQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinQuery.swift; sourceTree = ""; }; 5653EAFF20944C7C00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; @@ -1607,13 +1603,12 @@ children = ( 5653EAFA20944C7B00F46237 /* Association.swift */, 563EF42C2161180D007DAACD /* AssociationAggregate.swift */, - 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */, - 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */, 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */, 5653EAFF20944C7C00F46237 /* ForeignKey.swift */, 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */, 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */, 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */, + 5653EAFE20944C7C00F46237 /* JoinQuery.swift */, ); path = Association; sourceTree = ""; @@ -2521,7 +2516,6 @@ 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5613ED4121A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */, - 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */, C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, @@ -2592,7 +2586,7 @@ 565490CB1D5AE252005622CB /* (null) in Sources */, 563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, - 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */, + 5653EB1720944C7C00F46237 /* JoinQuery.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, @@ -2673,12 +2667,11 @@ 56A8C2331D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D321DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, - 5653EB1020944C7C00F46237 /* AssociationRequest.swift in Sources */, 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, - 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */, + 5653EB1620944C7C00F46237 /* JoinQuery.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, @@ -3204,10 +3197,9 @@ 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D361DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, - 5653EB0F20944C7C00F46237 /* AssociationRequest.swift in Sources */, 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */, + 5653EB1520944C7C00F46237 /* JoinQuery.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 57e49d7a8..373ad9721 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -5,7 +5,20 @@ public protocol Association: DerivableRequest { associatedtype OriginRowDecoder associatedtype RowDecoder - + associatedtype _Impl: _AssociationImpl + var _impl: _Impl { get set } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// :nodoc: +public protocol _AssociationImpl { + var key: String { get set } + func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> Self + func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest + func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery +} + +extension Association { /// The association key defines how rows fetched from this association /// should be consumed. /// @@ -30,7 +43,9 @@ public protocol Association: DerivableRequest { /// for row in Row.fetchAll(db, request) { /// let team: Team = row["custom"] /// } - var key: String { get } + public var key: String { + return _impl.key + } /// Creates an association with the given key. /// @@ -46,19 +61,18 @@ public protocol Association: DerivableRequest { /// for row in Row.fetchAll(db, request) { /// let team: Team = row["custom"] /// } - func forKey(_ key: String) -> Self + public func forKey(_ key: String) -> Self { + var association = self + association._impl.key = key + return association + } - /// :nodoc: - var request: AssociationRequest { get } + private func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> Self { + var association = self + association._impl = _impl.mapQuery(transform) + return association + } - /// :nodoc: - var joinCondition: JoinCondition { get } - - /// :nodoc: - func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self -} - -extension Association { /// Creates an association which selects *selection*. /// /// struct Player: TableRecord { @@ -81,7 +95,7 @@ extension Association { /// .select([Column("color")]) /// var request = Player.including(required: association) public func select(_ selection: [SQLSelectable]) -> Self { - return mapRequest { $0.select(selection) } + return mapQuery { $0.select(selection) } } /// Creates an association with the provided *predicate promise* added to @@ -97,7 +111,7 @@ extension Association { /// let association = Player.team.filter { db in true } /// var request = Player.including(required: association) public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - return mapRequest { $0.filter(predicate) } + return mapQuery { $0.filter(predicate) } } /// Creates an association with the provided *orderings promise*. @@ -125,7 +139,7 @@ extension Association { /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { - return mapRequest { $0.order(orderings) } + return mapQuery { $0.order(orderings) } } /// Creates an association that reverses applied orderings. @@ -149,7 +163,7 @@ extension Association { /// let association = Player.team.reversed() /// var request = Player.including(required: association) public func reversed() -> Self { - return mapRequest { $0.reversed() } + return mapQuery { $0.reversed() } } /// Creates an association with the given key. @@ -207,7 +221,7 @@ extension Association { /// .including(required: Player.team.aliased(teamAlias)) /// .filter(sql: "custom.color = ?", arguments: ["red"]) public func aliased(_ alias: TableAlias) -> Self { - return mapRequest { $0.aliased(alias) } + return mapQuery { $0.qualified(with: alias) } } } @@ -230,6 +244,8 @@ extension Association { /// let request = Book /// .include(required: Book.author) /// .include(required: Book.author) +/// TODO: Hide if possible +/// :nodoc: public struct JoinCondition: Equatable { var foreignKeyRequest: ForeignKeyRequest var originIsLeft: Bool @@ -254,28 +270,28 @@ extension Association { /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRequest { $0.joining(.optional, association) } + return mapQuery { association._impl.joinedQuery($0, joinOperator: .optional) } } /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRequest { $0.joining(.required, association) } + return mapQuery { association._impl.joinedQuery($0, joinOperator: .required) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRequest { $0.joining(.optional, association.select([])) } + return mapQuery { association.select([])._impl.joinedQuery($0, joinOperator: .optional) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRequest { $0.joining(.required, association.select([])) } + return mapQuery { association.select([])._impl.joinedQuery($0, joinOperator: .required) } } } @@ -294,38 +310,43 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] func request(from record: OriginRowDecoder) -> QueryInterfaceRequest { - // Goal: turn `JOIN association ON association.recordId = record.id` - // into a regular request `SELECT * FROM association WHERE association.recordId = 123` - - // We need table aliases to build the joining condition - let associationAlias = TableAlias() - let recordAlias = TableAlias() - - // Turn the association request into a query interface request: - // JOIN association -> SELECT FROM association - return QueryInterfaceRequest(request) - - // Turn the JOIN condition into a regular WHERE condition - .filter { db in - // Build a join condition: `association.recordId = record.id` - // We still need to replace `record.id` with the actual record id. - guard let joinExpression = try self.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { - fatalError("Can't request from record without join condition") - } - - // Serialize record: ["id": 123, ...] - // We do it as late as possible, when request is about to be - // executed, in order to support long-lived reference types. - let container = PersistenceContainer(record) - - // Replace `record.id` with 123 - return joinExpression.resolvedExpression(inContext: [recordAlias: container]) - } - - // We just added a condition qualified with associationAlias. Don't - // risk introducing conflicting aliases that would prevent the user - // from setting a custom alias name: force the same alias for the - // whole request. - .aliased(associationAlias) + let query = QueryInterfaceQuery( + source: .table(tableName: "TODO", alias: nil), + selection: [AllColumns()]) + return QueryInterfaceRequest(query: query) +// fatalError("not implemented") +// // Goal: turn `JOIN association ON association.recordId = record.id` +// // into a regular request `SELECT * FROM association WHERE association.recordId = 123` +// +// // We need table aliases to build the joining condition +// let associationAlias = TableAlias() +// let recordAlias = TableAlias() +// +// // Turn the association query into a query interface request: +// // JOIN association -> SELECT FROM association +// return QueryInterfaceRequest(query: query) +// +// // Turn the JOIN condition into a regular WHERE condition +// .filter { db in +// // Build a join condition: `association.recordId = record.id` +// // We still need to replace `record.id` with the actual record id. +// guard let joinExpression = try self.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { +// fatalError("Can't request from record without join condition") +// } +// +// // Serialize record: ["id": 123, ...] +// // We do it as late as possible, when request is about to be +// // executed, in order to support long-lived reference types. +// let container = PersistenceContainer(record) +// +// // Replace `record.id` with 123 +// return joinExpression.resolvedExpression(inContext: [recordAlias: container]) +// } +// +// // We just added a condition qualified with associationAlias. Don't +// // risk introducing conflicting aliases that would prevent the user +// // from setting a custom alias name: force the same alias for the +// // whole request. +// .aliased(associationAlias) } } diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift deleted file mode 100644 index 5eede5d33..000000000 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ /dev/null @@ -1,49 +0,0 @@ -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// In `SELECT a.*, b.* FROM a JOIN b ON b.aid = a.id AND b.name = 'foo'`, -/// the AssociationRequest is (`b.*` + `b.name = 'foo'`). -/// :nodoc: -public struct AssociationRequest { - let query: AssociationQuery - - init(query: AssociationQuery) { - self.query = query - } - - init(_ request: QueryInterfaceRequest) { - self.init(query: AssociationQuery(request.query)) - } -} - -extension AssociationRequest { - func select(_ selection: [SQLSelectable]) -> AssociationRequest { - return AssociationRequest(query: query.select(selection)) - } - - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationRequest { - return AssociationRequest(query: query.filter(predicate)) - } - - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> AssociationRequest { - return AssociationRequest(query: query.order(orderings)) - } - - func reversed() -> AssociationRequest { - return AssociationRequest(query: query.reversed()) - } - - func aliased(_ alias: TableAlias) -> AssociationRequest { - return AssociationRequest(query: query.qualified(with: alias)) - } - - func joining(_ joinOperator: AssociationJoinOperator, _ association: A) - -> AssociationRequest - where A.OriginRowDecoder == T - { - let join = AssociationJoin( - joinOperator: joinOperator, - joinCondition: association.joinCondition, - query: association.request.query) - return AssociationRequest(query: query.appendingJoin(join, forKey: association.key)) - } -} diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 97b2bbaa8..7671c0253 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -65,25 +65,38 @@ public struct BelongsToAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination - public var key: String - /// :nodoc: - public let joinCondition: JoinCondition - - /// :nodoc: - public var request: AssociationRequest + public var _impl: _BelongsToAssociationImpl +} - public func forKey(_ key: String) -> BelongsToAssociation { - var association = self - association.key = key - return association +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// :nodoc: +public struct _BelongsToAssociationImpl: _AssociationImpl { + public var key: String + let joinCondition: JoinCondition + var query: JoinQuery + + public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> _BelongsToAssociationImpl { + var impl = self + impl.query = transform(query) + return impl } - /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { - var association = self - association.request = transform(request) - return association + public func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { + let join = Join( + joinOperator: joinOperator, + joinCondition: joinCondition, + query: query) + return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) + } + + public func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery { + let join = Join( + joinOperator: joinOperator, + joinCondition: joinCondition, + query: self.query) + return query.appendingJoin(join, forKey: key) } } @@ -165,10 +178,10 @@ extension TableRecord { let joinCondition = JoinCondition( foreignKeyRequest: foreignKeyRequest, originIsLeft: true) - - return BelongsToAssociation( + + return BelongsToAssociation(_impl: _BelongsToAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - request: AssociationRequest(Destination.all())) + query: JoinQuery(Destination.all().query))) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index d61c8e48d..69c5b5e1a 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -65,25 +65,38 @@ public struct HasManyAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination + /// :nodoc: + public var _impl: _HasManyAssociationImpl +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// :nodoc: +public struct _HasManyAssociationImpl: _AssociationImpl { public var key: String + let joinCondition: JoinCondition + var query: JoinQuery - /// :nodoc: - public let joinCondition: JoinCondition - - /// :nodoc: - public var request: AssociationRequest - - public func forKey(_ key: String) -> HasManyAssociation { - var association = self - association.key = key - return association + public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> _HasManyAssociationImpl { + var impl = self + impl.query = transform(query) + return impl } - /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { - var association = self - association.request = transform(request) - return association + public func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { + let join = Join( + joinOperator: joinOperator, + joinCondition: joinCondition, + query: query) + return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) + } + + public func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery { + let join = Join( + joinOperator: joinOperator, + joinCondition: joinCondition, + query: self.query) + return query.appendingJoin(join, forKey: key) } } @@ -255,9 +268,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasManyAssociation( + return HasManyAssociation(_impl: _HasManyAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - request: AssociationRequest(Destination.all())) + query: JoinQuery(Destination.all().query))) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index e795ae494..18e313e73 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -66,26 +66,39 @@ public struct HasOneAssociation : Association { /// :nodoc: public typealias RowDecoder = Destination - + + /// :nodoc: + public var _impl: _HasOneAssociationImpl +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// :nodoc: +public struct _HasOneAssociationImpl: _AssociationImpl { public var key: String + let joinCondition: JoinCondition + var query: JoinQuery - /// :nodoc: - public let joinCondition: JoinCondition - - /// :nodoc: - public var request: AssociationRequest - - public func forKey(_ key: String) -> HasOneAssociation { - var association = self - association.key = key - return association + public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> _HasOneAssociationImpl { + var impl = self + impl.query = transform(query) + return impl } - /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { - var association = self - association.request = transform(request) - return association + public func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { + let join = Join( + joinOperator: joinOperator, + joinCondition: joinCondition, + query: query) + return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) + } + + public func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery { + let join = Join( + joinOperator: joinOperator, + joinCondition: joinCondition, + query: self.query) + return query.appendingJoin(join, forKey: key) } } @@ -168,9 +181,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasOneAssociation( + return HasOneAssociation(_impl: _HasOneAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - request: AssociationRequest(Destination.all())) + query: JoinQuery(Destination.all().query))) } } diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/JoinQuery.swift similarity index 88% rename from GRDB/QueryInterface/Association/AssociationQuery.swift rename to GRDB/QueryInterface/Association/JoinQuery.swift index 90e696438..1c6b0c45a 100644 --- a/GRDB/QueryInterface/Association/AssociationQuery.swift +++ b/GRDB/QueryInterface/Association/JoinQuery.swift @@ -1,16 +1,19 @@ -struct AssociationQuery { +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// TODO: Hide if possible +/// :nodoc: +public struct JoinQuery { var source: SQLSource var selection: [SQLSelectable] var filterPromise: DatabasePromise var ordering: QueryOrdering - var joins: OrderedDictionary + var joins: OrderedDictionary var alias: TableAlias? { return source.alias } } -extension AssociationQuery { +extension JoinQuery { init(_ query: QueryInterfaceQuery) { GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries") @@ -26,14 +29,14 @@ extension AssociationQuery { } } -extension AssociationQuery { - func select(_ selection: [SQLSelectable]) -> AssociationQuery { +extension JoinQuery { + func select(_ selection: [SQLSelectable]) -> JoinQuery { var query = self query.selection = selection return query } - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationQuery { + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> JoinQuery { var query = self query.filterPromise = query.filterPromise.map { (db, filter) in if let filter = filter { @@ -45,21 +48,21 @@ extension AssociationQuery { return query } - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> AssociationQuery { + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> JoinQuery { return order(QueryOrdering(orderings: orderings)) } - func reversed() -> AssociationQuery { + func reversed() -> JoinQuery { return order(ordering.reversed) } - private func order(_ ordering: QueryOrdering) -> AssociationQuery { + private func order(_ ordering: QueryOrdering) -> JoinQuery { var query = self query.ordering = ordering return query } - func appendingJoin(_ join: AssociationJoin, forKey key: String) -> AssociationQuery { + func appendingJoin(_ join: Join, forKey key: String) -> JoinQuery { var query = self if let existingJoin = query.joins.removeValue(forKey: key) { guard let mergedJoin = existingJoin.merged(with: join) else { @@ -73,16 +76,16 @@ extension AssociationQuery { return query } - func qualified(with alias: TableAlias) -> AssociationQuery { + func qualified(with alias: TableAlias) -> JoinQuery { var query = self query.source = source.qualified(with: alias) return query } } -extension AssociationQuery { +extension JoinQuery { /// A finalized query is ready for SQL generation - var finalizedQuery: AssociationQuery { + var finalizedQuery: JoinQuery { var query = self let alias = TableAlias() @@ -144,9 +147,9 @@ extension AssociationQuery { } } -extension AssociationQuery { +extension JoinQuery { /// Returns nil if queries can't be merged (conflict in source, joins...) - func merged(with other: AssociationQuery) -> AssociationQuery? { + func merged(with other: JoinQuery) -> JoinQuery? { guard let mergedSource = source.merged(with: other.source) else { // can't merge return nil @@ -161,7 +164,7 @@ extension AssociationQuery { return expressions.joined(operator: .and) } - var mergedJoins: OrderedDictionary = [:] + var mergedJoins: OrderedDictionary = [:] for (key, join) in joins { if let otherJoin = other.joins[key] { guard let mergedJoin = join.merged(with: otherJoin) else { @@ -183,7 +186,7 @@ extension AssociationQuery { // replace ordering unless empty let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering - return AssociationQuery( + return JoinQuery( source: mergedSource, selection: mergedSelection, filterPromise: mergedFilterPromise, diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 0dc8eec85..32dd101b5 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -25,7 +25,7 @@ struct QueryInterfaceQuery { var ordering: QueryOrdering var havingExpression: SQLExpression? var limit: SQLLimit? - var joins: OrderedDictionary + var joins: OrderedDictionary init( source: SQLSource, @@ -36,7 +36,7 @@ struct QueryInterfaceQuery { ordering: QueryOrdering = QueryOrdering(), havingExpression: SQLExpression? = nil, limit: SQLLimit? = nil, - joins: OrderedDictionary = [:]) + joins: OrderedDictionary = [:]) { self.source = source self.selection = selection @@ -49,7 +49,7 @@ struct QueryInterfaceQuery { self.joins = joins } - init(_ query: AssociationQuery) { + init(_ query: JoinQuery) { self.init( source: query.source, selection: query.selection, @@ -136,7 +136,7 @@ extension QueryInterfaceQuery { return query } - func appendingJoin(_ join: AssociationJoin, forKey key: String) -> QueryInterfaceQuery { + func appendingJoin(_ join: Join, forKey key: String) -> QueryInterfaceQuery { var query = self if let existingJoin = query.joins.removeValue(forKey: key) { guard let mergedJoin = existingJoin.merged(with: join) else { @@ -420,11 +420,11 @@ extension QueryInterfaceQuery { } } -// MARK: - AssociationJoin +// MARK: - Join /// Not to be mismatched with SQL join operators (inner join, left join). /// -/// AssociationJoinOperator is designed to be hierarchically nested, unlike +/// JoinOperator is designed to be hierarchically nested, unlike /// SQL join operators. /// /// Consider the following request for (A, B, C) tuples: @@ -465,16 +465,18 @@ extension QueryInterfaceQuery { /// /// // what is my meaning? /// A.including(optional: A.b.including(required: B.c)) -enum AssociationJoinOperator { +/// TODO: Hide if possible +/// :nodoc: +public enum JoinOperator { case required, optional } -struct AssociationJoin { - var joinOperator: AssociationJoinOperator +struct Join { + var joinOperator: JoinOperator var joinCondition: JoinCondition - var query: AssociationQuery + var query: JoinQuery - var finalizedJoin: AssociationJoin { + var finalizedJoin: Join { var join = self join.query = query.finalizedQuery return join @@ -531,7 +533,7 @@ struct AssociationJoin { } /// Returns nil if joins can't be merged (conflict in condition, query...) - func merged(with other: AssociationJoin) -> AssociationJoin? { + func merged(with other: Join) -> Join? { guard joinCondition == other.joinCondition else { // can't merge return nil @@ -542,7 +544,7 @@ struct AssociationJoin { return nil } - let mergedJoinOperator: AssociationJoinOperator + let mergedJoinOperator: JoinOperator switch (joinOperator, other.joinOperator) { case (.required, _), (_, .required): mergedJoinOperator = .required @@ -550,7 +552,7 @@ struct AssociationJoin { mergedJoinOperator = .optional } - return AssociationJoin( + return Join( joinOperator: mergedJoinOperator, joinCondition: joinCondition, query: mergedQuery) diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 42031bae9..46072f51e 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -1,43 +1,32 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { - func joining(_ joinOperator: AssociationJoinOperator, _ association: A) - -> QueryInterfaceRequest - where A.OriginRowDecoder == RowDecoder - { - let join = AssociationJoin( - joinOperator: joinOperator, - joinCondition: association.joinCondition, - query: association.request.query) - return QueryInterfaceRequest(query: query.appendingJoin(join, forKey: association.key)) - } - // MARK: - Associations /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return joining(.optional, association) + return association._impl.joinedRequest(self, joinOperator: .optional) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return joining(.required, association) + return association._impl.joinedRequest(self, joinOperator: .required) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return joining(.optional, association.select([])) + return association.select([])._impl.joinedRequest(self, joinOperator: .optional) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return joining(.required, association.select([])) + return association.select([])._impl.joinedRequest(self, joinOperator: .required) } // MARK: - Association Aggregates diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index bd9eb60d5..beea64f0d 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -8,8 +8,8 @@ public struct QueryInterfaceRequest { self.query = query } - init(_ request: AssociationRequest) { - self.query = QueryInterfaceQuery(request.query) + init(query: JoinQuery) { + self.query = QueryInterfaceQuery(query) } } diff --git a/GRDB/QueryInterface/QueryOrdering.swift b/GRDB/QueryInterface/QueryOrdering.swift index d9f199aac..73c4e421a 100644 --- a/GRDB/QueryInterface/QueryOrdering.swift +++ b/GRDB/QueryInterface/QueryOrdering.swift @@ -1,5 +1,5 @@ /// QueryOrdering provides the order clause to QueryInterfaceQuery -/// and AssociationQuery. +/// and JoinQuery. struct QueryOrdering { private enum Element { case orderingTerms((Database) throws -> [SQLOrderingTerm]) diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 3f14b05e5..5c8445238 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -296,16 +296,14 @@ 5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */; }; 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; - 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* AssociationQuery.swift */; }; - 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* AssociationQuery.swift */; }; + 5653EB9320961FC000F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* JoinQuery.swift */; }; + 5653EB9420961FC000F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* JoinQuery.swift */; }; 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8920961FBF00F46237 /* ForeignKey.swift */; }; 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8920961FBF00F46237 /* ForeignKey.swift */; }; 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */; }; 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */; }; - 5653EB9B20961FC000F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */; }; - 5653EB9C20961FC000F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */; }; 5653EB9D20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; 5653EB9E20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; 5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; @@ -1106,11 +1104,10 @@ 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; - 5653EB8720961FBF00F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; + 5653EB8720961FBF00F46237 /* JoinQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinQuery.swift; sourceTree = ""; }; 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; 5653EB8920961FBF00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; - 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; 5653EB8C20961FBF00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; @@ -1667,13 +1664,12 @@ children = ( 5653EB8C20961FBF00F46237 /* Association.swift */, 563EF43A2161183E007DAACD /* AssociationAggregate.swift */, - 5653EB8720961FBF00F46237 /* AssociationQuery.swift */, - 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */, 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */, 5653EB8920961FBF00F46237 /* ForeignKey.swift */, 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */, 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */, 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */, + 5653EB8720961FBF00F46237 /* JoinQuery.swift */, ); path = Association; sourceTree = ""; @@ -2328,7 +2324,6 @@ 563EF4502161F1A8007DAACD /* Inflections.swift in Sources */, 566B910A1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91241FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 5653EB9B20961FC000F46237 /* AssociationRequest.swift in Sources */, 56CEB5121EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4911EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2400,7 +2395,7 @@ 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, - 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */, + 5653EB9320961FC000F46237 /* JoinQuery.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, 5659F4891EA8D94E004A4992 /* Utils.swift in Sources */, 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */, @@ -2816,7 +2811,6 @@ 563EF4512161F1A8007DAACD /* Inflections.swift in Sources */, 566B910D1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91271FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 5653EB9C20961FC000F46237 /* AssociationRequest.swift in Sources */, 56CEB5151EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4941EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2888,7 +2882,7 @@ 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, - 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */, + 5653EB9420961FC000F46237 /* JoinQuery.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, 5659F48C1EA8D94E004A4992 /* Utils.swift in Sources */, 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 91458697c..644402f28 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -121,16 +121,14 @@ 5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */; }; 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; - 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* AssociationQuery.swift */; }; - 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* AssociationQuery.swift */; }; + 5653EB4520961F6100F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* JoinQuery.swift */; }; + 5653EB4620961F6100F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* JoinQuery.swift */; }; 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3B20961F6000F46237 /* ForeignKey.swift */; }; 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3B20961F6000F46237 /* ForeignKey.swift */; }; 5653EB4B20961F6100F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */; }; 5653EB4C20961F6100F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */; }; - 5653EB4D20961F6100F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3D20961F6100F46237 /* AssociationRequest.swift */; }; - 5653EB4E20961F6100F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3D20961F6100F46237 /* AssociationRequest.swift */; }; 5653EB4F20961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; 5653EB5020961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; 5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; @@ -741,11 +739,10 @@ 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; 5653EB3820961F6000F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; - 5653EB3920961F6000F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; + 5653EB3920961F6000F46237 /* JoinQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinQuery.swift; sourceTree = ""; }; 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; 5653EB3B20961F6000F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; - 5653EB3D20961F6100F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; 5653EB3E20961F6100F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; @@ -1275,13 +1272,12 @@ children = ( 5653EB3E20961F6100F46237 /* Association.swift */, 563EF4362161182C007DAACD /* AssociationAggregate.swift */, - 5653EB3920961F6000F46237 /* AssociationQuery.swift */, - 5653EB3D20961F6100F46237 /* AssociationRequest.swift */, 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */, 5653EB3B20961F6000F46237 /* ForeignKey.swift */, 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */, 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */, 5653EB3820961F6000F46237 /* HasOneAssociation.swift */, + 5653EB3920961F6000F46237 /* JoinQuery.swift */, ); path = Association; sourceTree = ""; @@ -1965,7 +1961,6 @@ 563EF44E2161F196007DAACD /* Inflections.swift in Sources */, 566B910E1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91281FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 5653EB4E20961F6100F46237 /* AssociationRequest.swift in Sources */, 56CEB5161EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2036,7 +2031,7 @@ F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, - 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */, + 5653EB4620961F6100F46237 /* JoinQuery.swift in Sources */, F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, @@ -2273,7 +2268,6 @@ 563EF44D2161F196007DAACD /* Inflections.swift in Sources */, 566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 5653EB4D20961F6100F46237 /* AssociationRequest.swift in Sources */, 56CEB5131EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2344,7 +2338,7 @@ F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, - 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */, + 5653EB4520961F6100F46237 /* JoinQuery.swift in Sources */, F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, From 77fd2b84110f7b103326a0c8804487b21ff44c5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 10:51:33 +0100 Subject: [PATCH 02/26] Restore failing tests --- .../Association/Association.swift | 101 +++++++++++------- .../Association/BelongsToAssociation.swift | 4 +- .../Association/HasManyAssociation.swift | 4 +- .../Association/HasOneAssociation.swift | 4 +- 4 files changed, 70 insertions(+), 43 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 373ad9721..4bf5b8975 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -3,9 +3,28 @@ /// The base protocol for all associations that define a connection between two /// record types. public protocol Association: DerivableRequest { + /// The record type at the origin of the association. + /// + /// In the sample code below, it is Book: + /// + /// struct Book: FetchableRecord, TableRecord { + /// static let author = belongsTo(Author.self) + /// } associatedtype OriginRowDecoder + + /// The associated record type. + /// + /// In the sample code below, it is Author: + /// + /// struct Book: FetchableRecord, TableRecord { + /// static let author = belongsTo(Author.self) + /// } associatedtype RowDecoder + + /// :nodoc: associatedtype _Impl: _AssociationImpl + + /// :nodoc: var _impl: _Impl { get set } } @@ -16,6 +35,14 @@ public protocol _AssociationImpl { func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> Self func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery + + // TODO: remove those properties. + // + // They prevent has-one-through and has-many-through from being implemented. + // + // But they are currently used by Association.request(from:) below. + var query: JoinQuery { get } + var joinCondition: JoinCondition { get } } extension Association { @@ -310,43 +337,43 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] func request(from record: OriginRowDecoder) -> QueryInterfaceRequest { - let query = QueryInterfaceQuery( - source: .table(tableName: "TODO", alias: nil), - selection: [AllColumns()]) - return QueryInterfaceRequest(query: query) -// fatalError("not implemented") -// // Goal: turn `JOIN association ON association.recordId = record.id` -// // into a regular request `SELECT * FROM association WHERE association.recordId = 123` -// -// // We need table aliases to build the joining condition -// let associationAlias = TableAlias() -// let recordAlias = TableAlias() -// -// // Turn the association query into a query interface request: -// // JOIN association -> SELECT FROM association +// let query = QueryInterfaceQuery( +// source: .table(tableName: "TODO", alias: nil), +// selection: [AllColumns()]) // return QueryInterfaceRequest(query: query) -// -// // Turn the JOIN condition into a regular WHERE condition -// .filter { db in -// // Build a join condition: `association.recordId = record.id` -// // We still need to replace `record.id` with the actual record id. -// guard let joinExpression = try self.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { -// fatalError("Can't request from record without join condition") -// } -// -// // Serialize record: ["id": 123, ...] -// // We do it as late as possible, when request is about to be -// // executed, in order to support long-lived reference types. -// let container = PersistenceContainer(record) -// -// // Replace `record.id` with 123 -// return joinExpression.resolvedExpression(inContext: [recordAlias: container]) -// } -// -// // We just added a condition qualified with associationAlias. Don't -// // risk introducing conflicting aliases that would prevent the user -// // from setting a custom alias name: force the same alias for the -// // whole request. -// .aliased(associationAlias) +// fatalError("not implemented") + // Goal: turn `JOIN association ON association.recordId = record.id` + // into a regular request `SELECT * FROM association WHERE association.recordId = 123` + + // We need table aliases to build the joining condition + let associationAlias = TableAlias() + let recordAlias = TableAlias() + + // Turn the association query into a query interface request: + // JOIN association -> SELECT FROM association + return QueryInterfaceRequest(query: _impl.query) + + // Turn the JOIN condition into a regular WHERE condition + .filter { db in + // Build a join condition: `association.recordId = record.id` + // We still need to replace `record.id` with the actual record id. + guard let joinExpression = try self._impl.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { + fatalError("Can't request from record without join condition") + } + + // Serialize record: ["id": 123, ...] + // We do it as late as possible, when request is about to be + // executed, in order to support long-lived reference types. + let container = PersistenceContainer(record) + + // Replace `record.id` with 123 + return joinExpression.resolvedExpression(inContext: [recordAlias: container]) + } + + // We just added a condition qualified with associationAlias. Don't + // risk introducing conflicting aliases that would prevent the user + // from setting a custom alias name: force the same alias for the + // whole request. + .aliased(associationAlias) } } diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 7671c0253..22f44017c 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -74,8 +74,8 @@ public struct BelongsToAssociation: Association { /// :nodoc: public struct _BelongsToAssociationImpl: _AssociationImpl { public var key: String - let joinCondition: JoinCondition - var query: JoinQuery + public /* TODO: make internal when no longer required by _AssociationImpl */ let joinCondition: JoinCondition + public /* TODO: make internal when no longer required by _AssociationImpl */ var query: JoinQuery public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> _BelongsToAssociationImpl { var impl = self diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 69c5b5e1a..b1c4e5b4a 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -74,8 +74,8 @@ public struct HasManyAssociation: Association { /// :nodoc: public struct _HasManyAssociationImpl: _AssociationImpl { public var key: String - let joinCondition: JoinCondition - var query: JoinQuery + public /* TODO: make internal when no longer required by _AssociationImpl */ let joinCondition: JoinCondition + public /* TODO: make internal when no longer required by _AssociationImpl */ var query: JoinQuery public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> _HasManyAssociationImpl { var impl = self diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 18e313e73..65ab8cefd 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -76,8 +76,8 @@ public struct HasOneAssociation : Association { /// :nodoc: public struct _HasOneAssociationImpl: _AssociationImpl { public var key: String - let joinCondition: JoinCondition - var query: JoinQuery + public /* TODO: make internal when no longer required by _AssociationImpl */ let joinCondition: JoinCondition + public /* TODO: make internal when no longer required by _AssociationImpl */ var query: JoinQuery public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> _HasOneAssociationImpl { var impl = self From 1e7840f0e4242c2bec479e10eb89e81f06480460 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 11:38:27 +0100 Subject: [PATCH 03/26] More trimming --- .../Association/Association.swift | 83 +++++++------------ .../Association/BelongsToAssociation.swift | 31 ++++--- .../Association/HasManyAssociation.swift | 31 ++++--- .../Association/HasOneAssociation.swift | 31 ++++--- .../QueryInterfaceRequest+Association.swift | 8 +- 5 files changed, 89 insertions(+), 95 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 4bf5b8975..da474fbab 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -1,8 +1,27 @@ +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The protocol for associations implementation details. +/// +/// :nodoc: +public protocol _Association { + func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> Self + func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest + func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery + + // TODO: remove those properties. + // + // They prevent has-one-through and has-many-through from being implemented. + // + // But they are currently used by Association.request(from:) below. + var query: JoinQuery { get } + var joinCondition: JoinCondition { get } +} + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The base protocol for all associations that define a connection between two /// record types. -public protocol Association: DerivableRequest { +public protocol Association: _Association, DerivableRequest { /// The record type at the origin of the association. /// /// In the sample code below, it is Book: @@ -21,31 +40,6 @@ public protocol Association: DerivableRequest { /// } associatedtype RowDecoder - /// :nodoc: - associatedtype _Impl: _AssociationImpl - - /// :nodoc: - var _impl: _Impl { get set } -} - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// :nodoc: -public protocol _AssociationImpl { - var key: String { get set } - func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> Self - func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest - func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery - - // TODO: remove those properties. - // - // They prevent has-one-through and has-many-through from being implemented. - // - // But they are currently used by Association.request(from:) below. - var query: JoinQuery { get } - var joinCondition: JoinCondition { get } -} - -extension Association { /// The association key defines how rows fetched from this association /// should be consumed. /// @@ -70,9 +64,7 @@ extension Association { /// for row in Row.fetchAll(db, request) { /// let team: Team = row["custom"] /// } - public var key: String { - return _impl.key - } + var key: String { get } /// Creates an association with the given key. /// @@ -88,18 +80,10 @@ extension Association { /// for row in Row.fetchAll(db, request) { /// let team: Team = row["custom"] /// } - public func forKey(_ key: String) -> Self { - var association = self - association._impl.key = key - return association - } - - private func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> Self { - var association = self - association._impl = _impl.mapQuery(transform) - return association - } - + func forKey(_ key: String) -> Self +} + +extension Association { /// Creates an association which selects *selection*. /// /// struct Player: TableRecord { @@ -297,28 +281,28 @@ extension Association { /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapQuery { association._impl.joinedQuery($0, joinOperator: .optional) } + return mapQuery { association.joinedQuery($0, joinOperator: .optional) } } /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapQuery { association._impl.joinedQuery($0, joinOperator: .required) } + return mapQuery { association.joinedQuery($0, joinOperator: .required) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapQuery { association.select([])._impl.joinedQuery($0, joinOperator: .optional) } + return mapQuery { association.select([]).joinedQuery($0, joinOperator: .optional) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapQuery { association.select([])._impl.joinedQuery($0, joinOperator: .required) } + return mapQuery { association.select([]).joinedQuery($0, joinOperator: .required) } } } @@ -337,11 +321,6 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] func request(from record: OriginRowDecoder) -> QueryInterfaceRequest { -// let query = QueryInterfaceQuery( -// source: .table(tableName: "TODO", alias: nil), -// selection: [AllColumns()]) -// return QueryInterfaceRequest(query: query) -// fatalError("not implemented") // Goal: turn `JOIN association ON association.recordId = record.id` // into a regular request `SELECT * FROM association WHERE association.recordId = 123` @@ -351,13 +330,13 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { // Turn the association query into a query interface request: // JOIN association -> SELECT FROM association - return QueryInterfaceRequest(query: _impl.query) + return QueryInterfaceRequest(query: query) // Turn the JOIN condition into a regular WHERE condition .filter { db in // Build a join condition: `association.recordId = record.id` // We still need to replace `record.id` with the actual record id. - guard let joinExpression = try self._impl.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { + guard let joinExpression = try self.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { fatalError("Can't request from record without join condition") } diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 22f44017c..f3fe443b3 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -65,24 +65,28 @@ public struct BelongsToAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination - /// :nodoc: - public var _impl: _BelongsToAssociationImpl -} - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// :nodoc: -public struct _BelongsToAssociationImpl: _AssociationImpl { public var key: String - public /* TODO: make internal when no longer required by _AssociationImpl */ let joinCondition: JoinCondition - public /* TODO: make internal when no longer required by _AssociationImpl */ var query: JoinQuery + + /// :nodoc: + public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition - public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> _BelongsToAssociationImpl { + /// :nodoc: + public /* TODO: make internal when no longer required by Association */ var query: JoinQuery + + public func forKey(_ key: String) -> BelongsToAssociation { + var assoc = self + assoc.key = key + return assoc + } + + /// :nodoc: + public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> BelongsToAssociation { var impl = self impl.query = transform(query) return impl } + /// :nodoc: public func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { let join = Join( joinOperator: joinOperator, @@ -91,6 +95,7 @@ public struct _BelongsToAssociationImpl: _AssociationImpl { return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) } + /// :nodoc: public func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery { let join = Join( joinOperator: joinOperator, @@ -179,9 +184,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: true) - return BelongsToAssociation(_impl: _BelongsToAssociationImpl( + return BelongsToAssociation( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - query: JoinQuery(Destination.all().query))) + query: JoinQuery(Destination.all().query)) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index b1c4e5b4a..f86524f72 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -65,24 +65,28 @@ public struct HasManyAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination - /// :nodoc: - public var _impl: _HasManyAssociationImpl -} - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// :nodoc: -public struct _HasManyAssociationImpl: _AssociationImpl { public var key: String - public /* TODO: make internal when no longer required by _AssociationImpl */ let joinCondition: JoinCondition - public /* TODO: make internal when no longer required by _AssociationImpl */ var query: JoinQuery + + /// :nodoc: + public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition - public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> _HasManyAssociationImpl { + /// :nodoc: + public /* TODO: make internal when no longer required by Association */ var query: JoinQuery + + public func forKey(_ key: String) -> HasManyAssociation { + var assoc = self + assoc.key = key + return assoc + } + + /// :nodoc: + public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> HasManyAssociation { var impl = self impl.query = transform(query) return impl } + /// :nodoc: public func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { let join = Join( joinOperator: joinOperator, @@ -91,6 +95,7 @@ public struct _HasManyAssociationImpl: _AssociationImpl { return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) } + /// :nodoc: public func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery { let join = Join( joinOperator: joinOperator, @@ -268,9 +273,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasManyAssociation(_impl: _HasManyAssociationImpl( + return HasManyAssociation( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - query: JoinQuery(Destination.all().query))) + query: JoinQuery(Destination.all().query)) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 65ab8cefd..7f96b8254 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -67,24 +67,28 @@ public struct HasOneAssociation : Association { /// :nodoc: public typealias RowDecoder = Destination - /// :nodoc: - public var _impl: _HasOneAssociationImpl -} - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// :nodoc: -public struct _HasOneAssociationImpl: _AssociationImpl { public var key: String - public /* TODO: make internal when no longer required by _AssociationImpl */ let joinCondition: JoinCondition - public /* TODO: make internal when no longer required by _AssociationImpl */ var query: JoinQuery + + /// :nodoc: + public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition - public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> _HasOneAssociationImpl { + /// :nodoc: + public /* TODO: make internal when no longer required by Association */ var query: JoinQuery + + public func forKey(_ key: String) -> HasOneAssociation { + var assoc = self + assoc.key = key + return assoc + } + + /// :nodoc: + public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> HasOneAssociation { var impl = self impl.query = transform(query) return impl } + /// :nodoc: public func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { let join = Join( joinOperator: joinOperator, @@ -93,6 +97,7 @@ public struct _HasOneAssociationImpl: _AssociationImpl { return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) } + /// :nodoc: public func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery { let join = Join( joinOperator: joinOperator, @@ -181,9 +186,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasOneAssociation(_impl: _HasOneAssociationImpl( + return HasOneAssociation( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - query: JoinQuery(Destination.all().query))) + query: JoinQuery(Destination.all().query)) } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 46072f51e..df7c4dcbc 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -5,28 +5,28 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association._impl.joinedRequest(self, joinOperator: .optional) + return association.joinedRequest(self, joinOperator: .optional) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association._impl.joinedRequest(self, joinOperator: .required) + return association.joinedRequest(self, joinOperator: .required) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association.select([])._impl.joinedRequest(self, joinOperator: .optional) + return association.select([]).joinedRequest(self, joinOperator: .optional) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association.select([])._impl.joinedRequest(self, joinOperator: .required) + return association.select([]).joinedRequest(self, joinOperator: .required) } // MARK: - Association Aggregates From 20d067c826bbe9ba8804cc8c0b2568c68deb34b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 13:11:00 +0100 Subject: [PATCH 04/26] Documentation --- .../Association/Association.swift | 108 ++++++++++++++---- .../Association/JoinQuery.swift | 4 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 4 +- 3 files changed, 91 insertions(+), 25 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index da474fbab..1c0a5d6a6 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -4,15 +4,40 @@ /// /// :nodoc: public protocol _Association { + /// Returns a transformed association. + /// + /// This method provides fundamental support for association derivation: + /// + /// // Invokes Book.author.mapQuery { $0.filter(...) } + /// Book.author.filter(...) func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> Self + + /// Returns a request joined with self. + /// + /// This method provides fundamental support for joining methods: + /// + /// // Invokes Book.author.joinedRequest(Book.all(), .required) + /// Book.including(required: Book.author) func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest + + /// Returns a query joined with self. + /// + /// This method provides fundamental support for joining methods: + /// + /// // Invokes Book.author.mapQuery { Author.country.joinedQuery($0, .optional) } + /// Book.including(required: Book.author.including(optional: Author.country) func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery - // TODO: remove those properties. + // TODO: remove query & joinCondition properties. // - // They prevent has-one-through and has-many-through from being implemented. + // They assume that an association is implemented as a direct join to an + // associated table. This is limiting: has-one-through and has-many-through + // associations can't be implemented in such context. // - // But they are currently used by Association.request(from:) below. + // Their impact is limited yet. Those propertise are currently only used by + // Association.request(from:). When this method gets a new implementation + // that does not need a direct join to an associated table, we'll be able to + // remove those properties. var query: JoinQuery { get } var joinCondition: JoinCondition { get } } @@ -24,18 +49,20 @@ public protocol _Association { public protocol Association: _Association, DerivableRequest { /// The record type at the origin of the association. /// - /// In the sample code below, it is Book: + /// In the `belongsTo` association below, it is Book: /// - /// struct Book: FetchableRecord, TableRecord { + /// struct Book: TableRecord { + /// // BelongsToAssociation /// static let author = belongsTo(Author.self) /// } associatedtype OriginRowDecoder /// The associated record type. /// - /// In the sample code below, it is Author: + /// In the `belongsTo` association below, it is Author: /// - /// struct Book: FetchableRecord, TableRecord { + /// struct Book: TableRecord { + /// // BelongsToAssociation /// static let author = belongsTo(Author.self) /// } associatedtype RowDecoder @@ -238,29 +265,49 @@ extension Association { /// The condition that links two joined tables. /// -/// We only support one kind of join condition, today: foreign keys. +/// Currently, we only support one kind of join condition: foreign keys. /// -/// SELECT ... -/// FROM book -/// JOIN author ON author.id = book.authorId -/// <--the join condition---> +/// SELECT ... FROM book JOIN author ON author.id = book.authorId +/// <- the join condition --> /// /// When we eventually add support for new ways to join tables, JoinCondition /// is the type we'll need to update. /// -/// The Equatable conformance is used when we merge associations. Two -/// associations can be merged if and only if their join conditions -/// are equal: -/// -/// let request = Book -/// .include(required: Book.author) -/// .include(required: Book.author) -/// TODO: Hide if possible /// :nodoc: -public struct JoinCondition: Equatable { +public /* TODO: make internal when possible */ struct JoinCondition { + /// Definition of a foreign key var foreignKeyRequest: ForeignKeyRequest + + /// True if the table at the origin of the foreign key is on the left of + /// the sql JOIN operator. + /// + /// Let's consider the `book.authorId -> author.id` foreign key. + /// Its origin table is `book`. + /// + /// The origin table `book` is on the left of the JOIN operator for + /// the BelongsTo association: + /// + /// -- Book.including(required: Book.author) + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// + /// The origin table `book`is on the right of the JOIN operator for + /// the HasMany and HasOne associations: + /// + /// -- Author.including(required: Author.books) + /// SELECT ... FROM author JOIN book ON author.id = book.authorId var originIsLeft: Bool + /// Returns an SQL expression for the join condition. + /// + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// <- the SQL expression --> + /// + /// - parameter db: A database connection. + /// - parameter leftAlias: A TableAlias for the table on the left of the + /// JOIN operator. + /// - parameter rightAlias: A TableAlias for the table on the right of the + /// JOIN operator. + /// - Returns: An SQL expression. func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression? { let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping let columnMapping: [(left: Column, right: Column)] @@ -276,6 +323,25 @@ public struct JoinCondition: Equatable { } } +/// JoinCondition equality allows merging of associations: +/// +/// // request1 and request2 are equivalent +/// let request1 = Book +/// .including(required: Book.author) +/// let request2 = Book +/// .including(required: Book.author) +/// .including(required: Book.author) +/// +/// // request3 and request4 are equivalent +/// let request3 = Book +/// .including(required: Book.author.filter(condition1 && condition2)) +/// let request4 = Book +/// .joining(required: Book.author.filter(condition1)) +/// .including(optional: Book.author.filter(condition2)) +/// +/// :nodoc: +extension JoinCondition: Equatable { } + extension Association { /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association does not diff --git a/GRDB/QueryInterface/Association/JoinQuery.swift b/GRDB/QueryInterface/Association/JoinQuery.swift index 1c6b0c45a..fd75deedb 100644 --- a/GRDB/QueryInterface/Association/JoinQuery.swift +++ b/GRDB/QueryInterface/Association/JoinQuery.swift @@ -1,7 +1,7 @@ /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// TODO: Hide if possible +/// /// :nodoc: -public struct JoinQuery { +public /* TODO: make internal when possible */ struct JoinQuery { var source: SQLSource var selection: [SQLSelectable] var filterPromise: DatabasePromise diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 32dd101b5..e70167aa8 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -465,9 +465,9 @@ extension QueryInterfaceQuery { /// /// // what is my meaning? /// A.including(optional: A.b.including(required: B.c)) -/// TODO: Hide if possible +/// /// :nodoc: -public enum JoinOperator { +public /* TODO: make internal when possible */ enum JoinOperator { case required, optional } From d9530433f2d04c5357b93843a38a1818d5bc9ade Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 13:15:17 +0100 Subject: [PATCH 05/26] Move JoinCondition definition --- .../Association/Association.swift | 79 ------------------- GRDB/QueryInterface/QueryInterfaceQuery.swift | 79 +++++++++++++++++++ 2 files changed, 79 insertions(+), 79 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 1c0a5d6a6..b77842e0a 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -263,85 +263,6 @@ extension Association { } } -/// The condition that links two joined tables. -/// -/// Currently, we only support one kind of join condition: foreign keys. -/// -/// SELECT ... FROM book JOIN author ON author.id = book.authorId -/// <- the join condition --> -/// -/// When we eventually add support for new ways to join tables, JoinCondition -/// is the type we'll need to update. -/// -/// :nodoc: -public /* TODO: make internal when possible */ struct JoinCondition { - /// Definition of a foreign key - var foreignKeyRequest: ForeignKeyRequest - - /// True if the table at the origin of the foreign key is on the left of - /// the sql JOIN operator. - /// - /// Let's consider the `book.authorId -> author.id` foreign key. - /// Its origin table is `book`. - /// - /// The origin table `book` is on the left of the JOIN operator for - /// the BelongsTo association: - /// - /// -- Book.including(required: Book.author) - /// SELECT ... FROM book JOIN author ON author.id = book.authorId - /// - /// The origin table `book`is on the right of the JOIN operator for - /// the HasMany and HasOne associations: - /// - /// -- Author.including(required: Author.books) - /// SELECT ... FROM author JOIN book ON author.id = book.authorId - var originIsLeft: Bool - - /// Returns an SQL expression for the join condition. - /// - /// SELECT ... FROM book JOIN author ON author.id = book.authorId - /// <- the SQL expression --> - /// - /// - parameter db: A database connection. - /// - parameter leftAlias: A TableAlias for the table on the left of the - /// JOIN operator. - /// - parameter rightAlias: A TableAlias for the table on the right of the - /// JOIN operator. - /// - Returns: An SQL expression. - func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression? { - let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping - let columnMapping: [(left: Column, right: Column)] - if originIsLeft { - columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } - } else { - columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } - } - - return columnMapping - .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } - .joined(operator: .and) - } -} - -/// JoinCondition equality allows merging of associations: -/// -/// // request1 and request2 are equivalent -/// let request1 = Book -/// .including(required: Book.author) -/// let request2 = Book -/// .including(required: Book.author) -/// .including(required: Book.author) -/// -/// // request3 and request4 are equivalent -/// let request3 = Book -/// .including(required: Book.author.filter(condition1 && condition2)) -/// let request4 = Book -/// .joining(required: Book.author.filter(condition1)) -/// .including(optional: Book.author.filter(condition2)) -/// -/// :nodoc: -extension JoinCondition: Equatable { } - extension Association { /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association does not diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index e70167aa8..175289d4b 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -471,6 +471,85 @@ public /* TODO: make internal when possible */ enum JoinOperator { case required, optional } +/// The condition that links two joined tables. +/// +/// Currently, we only support one kind of join condition: foreign keys. +/// +/// SELECT ... FROM book JOIN author ON author.id = book.authorId +/// <- the join condition --> +/// +/// When we eventually add support for new ways to join tables, JoinCondition +/// is the type we'll need to update. +/// +/// :nodoc: +public /* TODO: make internal when possible */ struct JoinCondition { + /// Definition of a foreign key + var foreignKeyRequest: ForeignKeyRequest + + /// True if the table at the origin of the foreign key is on the left of + /// the sql JOIN operator. + /// + /// Let's consider the `book.authorId -> author.id` foreign key. + /// Its origin table is `book`. + /// + /// The origin table `book` is on the left of the JOIN operator for + /// the BelongsTo association: + /// + /// -- Book.including(required: Book.author) + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// + /// The origin table `book`is on the right of the JOIN operator for + /// the HasMany and HasOne associations: + /// + /// -- Author.including(required: Author.books) + /// SELECT ... FROM author JOIN book ON author.id = book.authorId + var originIsLeft: Bool + + /// Returns an SQL expression for the join condition. + /// + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// <- the SQL expression --> + /// + /// - parameter db: A database connection. + /// - parameter leftAlias: A TableAlias for the table on the left of the + /// JOIN operator. + /// - parameter rightAlias: A TableAlias for the table on the right of the + /// JOIN operator. + /// - Returns: An SQL expression. + func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression? { + let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping + let columnMapping: [(left: Column, right: Column)] + if originIsLeft { + columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } + } else { + columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } + } + + return columnMapping + .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } + .joined(operator: .and) + } +} + +/// JoinCondition equality allows merging of associations: +/// +/// // request1 and request2 are equivalent +/// let request1 = Book +/// .including(required: Book.author) +/// let request2 = Book +/// .including(required: Book.author) +/// .including(required: Book.author) +/// +/// // request3 and request4 are equivalent +/// let request3 = Book +/// .including(required: Book.author.filter(condition1 && condition2)) +/// let request4 = Book +/// .joining(required: Book.author.filter(condition1)) +/// .including(optional: Book.author.filter(condition2)) +/// +/// :nodoc: +extension JoinCondition: Equatable { } + struct Join { var joinOperator: JoinOperator var joinCondition: JoinCondition From f309a0c5f3e1f2f1eb66310f7e47bc42c618a7eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 13:30:57 +0100 Subject: [PATCH 06/26] Documentation --- GRDB/Utils/OrderedDictionary.swift | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index 6fc1cfc4b..c4fb38609 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -1,16 +1,31 @@ +/// A dictionary with guaranteed keys ordering. +/// +/// var dict = OrderedDictionary() +/// dict.append(1, forKey: "foo") +/// dict.append(2, forKey: "bar") +/// +/// dict["foo"] // 1 +/// dict["bar"] // 2 +/// dict["qux"] // nil +/// dict.map { $0.key } // ["foo", "bar"], in this order. struct OrderedDictionary { private var keys: [Key] private var values: [Key: Value] + /// Creates an empty ordered dictionary. init() { self.keys = [] self.values = [:] } + /// Returns the value associated with key, or nil. subscript(_ key: Key) -> Value? { return values[key] } + /// Appends the given value for the given key. + /// + /// - precondition: There is no value associated with key yet. mutating func append(value: Value, forKey key: Key) { guard values.updateValue(value, forKey: key) == nil else { fatalError("key is already defined") @@ -18,6 +33,7 @@ struct OrderedDictionary { keys.append(key) } + /// Removes the value associated with key. @discardableResult mutating func removeValue(forKey key: Key) -> Value? { guard let value = values.removeValue(forKey: key) else { @@ -28,13 +44,12 @@ struct OrderedDictionary { return value } + /// Returns a new ordered dictionary containing the keys of this dictionary + /// with the values transformed by the given closure. func mapValues(_ transform: (Value) throws -> T) rethrows -> OrderedDictionary { - var result = OrderedDictionary() - for key in keys { - let value = values[key]! - try result.append(value: transform(value), forKey: key) + return try reduce(into: OrderedDictionary()) { dict, pair in + dict.append(value: try transform(pair.value), forKey: pair.key) } - return result } } From 9d391badc04f3565f6de6c586b78a21073617ded Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 14:31:12 +0100 Subject: [PATCH 07/26] Documentation --- .../Association/AssociationAggregate.swift | 314 +++++++++++++++--- 1 file changed, 270 insertions(+), 44 deletions(-) diff --git a/GRDB/QueryInterface/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Association/AssociationAggregate.swift index faeb31476..7206b0ce2 100644 --- a/GRDB/QueryInterface/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Association/AssociationAggregate.swift @@ -16,8 +16,49 @@ import Foundation /// /// let request = Author.annotated(with: bookCount) /// let request = Author.having(bookCount >= 10) +/// +/// The RowDecoder generic type helps the compiler prevent incorrect use +/// of aggregates: +/// +/// // Won't compile because Fruit is not Author. +/// let request = Fruit.annotated(with: bookCount) public struct AssociationAggregate { + /// Given a request, returns a tuple made of a request extended with the + /// associated records used to compute the aggregate, and an expression + /// whose value is the aggregated value. + /// + /// For example: + /// + /// struct Author: TableRecord { + /// static let books = hasMany(Book.self) + /// } + /// + /// // SELECT * FROM author + /// let request = Author.all() + /// + /// let aggregate = Author.books.count + /// let tuple = aggregate.prepare(request) + /// + /// // The request extended with associated records: + /// // + /// // SELECT author.* FROM author + /// // LEFT JOIN book ON book.authorId = author.id + /// // GROUP BY author.id + /// tuple.request + /// + /// // The aggregated value: + /// // + /// // COUNT(DISTINCT book.rowid) + /// tuple.expression + /// + /// The aggregated value is not right away embedded in the extended request: + /// + /// - 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: (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression) + + /// The SQL alias for the value of this aggregate. See aliased(_:). var alias: String? init(_ prepare: @escaping (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression)) { @@ -63,7 +104,11 @@ extension AssociationAggregate { // MARK: - Logical Operators (AND, OR, NOT) -/// :nodoc: +/// Returns a logically negated aggregate. +/// +/// For example: +/// +/// let request = Author.having(!Author.books.isEmpty) public prefix func ! (aggregate: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = aggregate.prepare(request) @@ -71,7 +116,11 @@ public prefix func ! (aggregate: AssociationAggregate) - } } -/// :nodoc: +/// Groups two aggregates with the `AND` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.isEmpty && Author.paintings.isEmpty) public func && (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -80,6 +129,7 @@ public func && (lhs: AssociationAggregate, rhs: Associat } } +// TODO: test & document /// :nodoc: public func && (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in @@ -88,6 +138,7 @@ public func && (lhs: AssociationAggregate, rhs: SQLExpre } } +// TODO: test & document /// :nodoc: public func && (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in @@ -96,7 +147,12 @@ public func && (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -105,6 +161,7 @@ public func || (lhs: AssociationAggregate, rhs: Associat } } +// TODO: test & document /// :nodoc: public func || (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in @@ -113,6 +170,7 @@ public func || (lhs: AssociationAggregate, rhs: SQLExpre } } +// TODO: test & document /// :nodoc: public func || (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in @@ -123,7 +181,11 @@ public func || (lhs: SQLExpressible, rhs: AssociationAggregate, IS, IS NOT) -/// :nodoc: +/// Returns an aggregate that compares two aggregates with the `=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count == Author.paintings.count) public func == (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -132,7 +194,11 @@ public func == (lhs: AssociationAggregate, rhs: Associat } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count == 3) public func == (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -140,7 +206,11 @@ public func == (lhs: AssociationAggregate, rhs: SQLExpre } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 == Author.books.count) public func == (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -148,7 +218,11 @@ public func == (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -156,7 +230,11 @@ public func == (lhs: AssociationAggregate, rhs: Bool) -> } } -/// :nodoc: +/// Returns an aggregate that checks the boolean value of an aggregate. +/// +/// For example: +/// +/// let request = Author.having(false == Author.books.isEmpty) public func == (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -164,7 +242,11 @@ public func == (lhs: Bool, rhs: AssociationAggregate) -> } } -/// :nodoc: +/// Returns an aggregate that compares two aggregates with the `<>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count != Author.paintings.count) public func != (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -173,7 +255,11 @@ public func != (lhs: AssociationAggregate, rhs: Associat } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count != 3) public func != (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -181,7 +267,11 @@ public func != (lhs: AssociationAggregate, rhs: SQLExpre } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 != Author.books.count) public func != (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -189,7 +279,11 @@ public func != (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -197,7 +291,11 @@ public func != (lhs: AssociationAggregate, rhs: Bool) -> } } -/// :nodoc: +/// Returns an aggregate that checks the boolean value of an aggregate. +/// +/// For example: +/// +/// let request = Author.having(true != Author.books.isEmpty) public func != (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -205,7 +303,11 @@ public func != (lhs: Bool, rhs: AssociationAggregate) -> } } -/// :nodoc: +/// Returns an aggregate that compares two aggregates with the `IS` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count === Author.paintings.count) public func === (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -214,7 +316,11 @@ public func === (lhs: AssociationAggregate, rhs: Associa } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `IS` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count === 3) public func === (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -222,7 +328,11 @@ public func === (lhs: AssociationAggregate, rhs: SQLExpr } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `IS` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 === Author.books.count) public func === (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -230,7 +340,11 @@ public func === (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -239,7 +353,11 @@ public func !== (lhs: AssociationAggregate, rhs: Associa } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count !== 3) public func !== (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -247,7 +365,11 @@ public func !== (lhs: AssociationAggregate, rhs: SQLExpr } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 !== Author.books.count) public func !== (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -257,7 +379,11 @@ public func !== (lhs: SQLExpressible, rhs: AssociationAggregate, <=, >=) -/// :nodoc: +/// Returns an aggregate that compares two aggregates with the `<=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count <= Author.paintings.count) public func <= (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -266,7 +392,11 @@ public func <= (lhs: AssociationAggregate, rhs: Associat } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count <= 3) public func <= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -274,7 +404,11 @@ public func <= (lhs: AssociationAggregate, rhs: SQLExpre } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 <= Author.books.count) public func <= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -282,7 +416,11 @@ public func <= (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -291,7 +429,11 @@ public func < (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count < 3) public func < (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -299,7 +441,11 @@ public func < (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 < Author.books.count) public func < (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -307,7 +453,11 @@ public func < (lhs: SQLExpressible, rhs: AssociationAggregate` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count > Author.paintings.count) public func > (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -316,7 +466,11 @@ public func > (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count > 3) public func > (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -324,7 +478,11 @@ public func > (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 > Author.books.count) public func > (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -332,7 +490,11 @@ public func > (lhs: SQLExpressible, rhs: AssociationAggregate=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count >= Author.paintings.count) public func >= (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -341,7 +503,11 @@ public func >= (lhs: AssociationAggregate, rhs: Associat } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `>=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count >= 3) public func >= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -349,7 +515,11 @@ public func >= (lhs: AssociationAggregate, rhs: SQLExpre } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `>=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 >= Author.books.count) public func >= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -359,7 +529,11 @@ public func >= (lhs: SQLExpressible, rhs: AssociationAggregate(aggregate: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = aggregate.prepare(request) @@ -367,7 +541,11 @@ public prefix func - (aggregate: AssociationAggregate) - } } -/// :nodoc: +/// Returns an aggregate that sums two aggregates with the `+` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count + Author.paintings.count) public func + (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -376,7 +554,11 @@ public func + (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that sums an aggregate with the `+` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count + 1) public func + (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -384,7 +566,11 @@ public func + (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that sums an aggregate with the `+` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: 1 + Author.books.count) public func + (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -392,7 +578,11 @@ public func + (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -401,7 +591,11 @@ public func - (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `-` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count - 1) public func - (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -409,7 +603,11 @@ public func - (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `-` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: 1 - Author.books.count) public func - (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -417,7 +615,11 @@ public func - (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -426,7 +628,11 @@ public func * (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `*` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count * 2) public func * (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -434,7 +640,11 @@ public func * (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `*` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: 2 * Author.books.count) public func * (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -442,7 +652,11 @@ public func * (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -451,7 +665,11 @@ public func / (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `/` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count / 2) public func / (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -459,7 +677,11 @@ public func / (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `/` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: 2 / Author.books.count) public func / (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -467,3 +689,7 @@ public func / (lhs: SQLExpressible, rhs: AssociationAggregate Date: Sat, 2 Feb 2019 14:54:31 +0100 Subject: [PATCH 08/26] Replace JoinQuery initializer with QueryInterfaceRequest.asJoinQuery() --- .../Association/BelongsToAssociation.swift | 2 +- .../Association/HasManyAssociation.swift | 2 +- .../Association/HasOneAssociation.swift | 2 +- .../Association/JoinQuery.swift | 16 ------------ .../QueryInterfaceRequest.swift | 26 +++++++++++++++++++ 5 files changed, 29 insertions(+), 19 deletions(-) diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index f3fe443b3..c34afbd4b 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -187,6 +187,6 @@ extension TableRecord { return BelongsToAssociation( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - query: JoinQuery(Destination.all().query)) + query: Destination.all().asJoinQuery()) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index f86524f72..35d4a6e48 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -276,6 +276,6 @@ extension TableRecord { return HasManyAssociation( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - query: JoinQuery(Destination.all().query)) + query: Destination.all().asJoinQuery()) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 7f96b8254..c9895091a 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -189,6 +189,6 @@ extension TableRecord { return HasOneAssociation( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - query: JoinQuery(Destination.all().query)) + query: Destination.all().asJoinQuery()) } } diff --git a/GRDB/QueryInterface/Association/JoinQuery.swift b/GRDB/QueryInterface/Association/JoinQuery.swift index fd75deedb..3200cd5fa 100644 --- a/GRDB/QueryInterface/Association/JoinQuery.swift +++ b/GRDB/QueryInterface/Association/JoinQuery.swift @@ -13,22 +13,6 @@ public /* TODO: make internal when possible */ struct JoinQuery { } } -extension JoinQuery { - init(_ query: QueryInterfaceQuery) { - GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") - GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries") - GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries") - GRDBPrecondition(query.limit == nil, "Can't join limited queries") - - self.init( - source: query.source, - selection: query.selection, - filterPromise: query.filterPromise, - ordering: query.ordering, - joins: query.joins) - } -} - extension JoinQuery { func select(_ selection: [SQLSelectable]) -> JoinQuery { var query = self diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index beea64f0d..6d0535673 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -226,6 +226,32 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { } } +extension QueryInterfaceRequest { + /// Turns a request into a JoinQuery. + /// + /// This method helps initializing associations: + /// + /// struct Book: TableRecord { + /// // invokes Author.all().asJoinQuery() + /// static let author = belongsTo(Author.self) + /// } + func asJoinQuery() -> JoinQuery { + let query = self.query + + GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") + GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries") + GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries") + GRDBPrecondition(query.limit == nil, "Can't join limited queries") + + return JoinQuery( + source: query.source, + selection: query.selection, + filterPromise: query.filterPromise, + ordering: query.ordering, + joins: query.joins) + } +} + /// Conditional conformance to TableRequest when RowDecoder conforms /// to TableRecord: /// From bb972a351ab6fe3d5662d73595dad467cb37ec57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 15:39:18 +0100 Subject: [PATCH 09/26] Refactor JoinQuery into SQLRelation --- GRDB.xcodeproj/project.pbxproj | 16 ++-- .../Association/Association.swift | 30 +++---- .../Association/BelongsToAssociation.swift | 20 ++--- .../Association/HasManyAssociation.swift | 20 ++--- .../Association/HasOneAssociation.swift | 22 ++--- GRDB/QueryInterface/QueryInterfaceQuery.swift | 40 ++++----- .../QueryInterfaceRequest.swift | 10 +-- .../JoinQuery.swift => SQLRelation.swift} | 90 ++++++++++--------- GRDBCipher.xcodeproj/project.pbxproj | 12 +-- GRDBCustom.xcodeproj/project.pbxproj | 12 +-- 10 files changed, 138 insertions(+), 134 deletions(-) rename GRDB/QueryInterface/{Association/JoinQuery.swift => SQLRelation.swift} (66%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 22a639917..f94ade828 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -271,9 +271,6 @@ 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; - 5653EB1520944C7C00F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* JoinQuery.swift */; }; - 5653EB1620944C7C00F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* JoinQuery.swift */; }; - 5653EB1720944C7C00F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* JoinQuery.swift */; }; 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; 5653EB1920944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; @@ -728,6 +725,9 @@ 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; + 56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; + 56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.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 */; }; @@ -1008,7 +1008,6 @@ 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; 5653EAFA20944C7B00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; - 5653EAFE20944C7C00F46237 /* JoinQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinQuery.swift; sourceTree = ""; }; 5653EAFF20944C7C00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; @@ -1212,6 +1211,7 @@ 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InsertRecordStructTests.swift; sourceTree = ""; }; 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 = ""; }; 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 = ""; }; @@ -1534,6 +1534,7 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, + 56D91AA12205E03700770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, @@ -1608,7 +1609,6 @@ 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */, 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */, 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */, - 5653EAFE20944C7C00F46237 /* JoinQuery.swift */, ); path = Association; sourceTree = ""; @@ -2485,6 +2485,7 @@ 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */, 565490E21D5AE252005622CB /* Record.swift in Sources */, 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */, 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, @@ -2586,7 +2587,6 @@ 565490CB1D5AE252005622CB /* (null) in Sources */, 563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, - 5653EB1720944C7C00F46237 /* JoinQuery.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, @@ -2671,7 +2671,6 @@ 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, - 5653EB1620944C7C00F46237 /* JoinQuery.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, @@ -2737,6 +2736,7 @@ 566B912E1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, + 56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */, 564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */, 564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */, @@ -3126,6 +3126,7 @@ 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, + 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, @@ -3199,7 +3200,6 @@ 56BF6D361DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 5653EB1520944C7C00F46237 /* JoinQuery.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index b77842e0a..a1a1cfa81 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -10,7 +10,7 @@ public protocol _Association { /// /// // Invokes Book.author.mapQuery { $0.filter(...) } /// Book.author.filter(...) - func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> Self + func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self /// Returns a request joined with self. /// @@ -24,11 +24,11 @@ public protocol _Association { /// /// This method provides fundamental support for joining methods: /// - /// // Invokes Book.author.mapQuery { Author.country.joinedQuery($0, .optional) } + /// // Invokes Book.author.mapQuery { Author.country.joinedRelation($0, .optional) } /// Book.including(required: Book.author.including(optional: Author.country) - func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery + func joinedRelation(_ query: SQLRelation, joinOperator: JoinOperator) -> SQLRelation - // TODO: remove query & joinCondition properties. + // TODO: remove relation & joinCondition properties. // // They assume that an association is implemented as a direct join to an // associated table. This is limiting: has-one-through and has-many-through @@ -38,7 +38,7 @@ public protocol _Association { // Association.request(from:). When this method gets a new implementation // that does not need a direct join to an associated table, we'll be able to // remove those properties. - var query: JoinQuery { get } + var relation: SQLRelation { get } var joinCondition: JoinCondition { get } } @@ -133,7 +133,7 @@ extension Association { /// .select([Column("color")]) /// var request = Player.including(required: association) public func select(_ selection: [SQLSelectable]) -> Self { - return mapQuery { $0.select(selection) } + return mapRelation { $0.select(selection) } } /// Creates an association with the provided *predicate promise* added to @@ -149,7 +149,7 @@ extension Association { /// let association = Player.team.filter { db in true } /// var request = Player.including(required: association) public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - return mapQuery { $0.filter(predicate) } + return mapRelation { $0.filter(predicate) } } /// Creates an association with the provided *orderings promise*. @@ -177,7 +177,7 @@ extension Association { /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { - return mapQuery { $0.order(orderings) } + return mapRelation { $0.order(orderings) } } /// Creates an association that reverses applied orderings. @@ -201,7 +201,7 @@ extension Association { /// let association = Player.team.reversed() /// var request = Player.including(required: association) public func reversed() -> Self { - return mapQuery { $0.reversed() } + return mapRelation { $0.reversed() } } /// Creates an association with the given key. @@ -259,7 +259,7 @@ extension Association { /// .including(required: Player.team.aliased(teamAlias)) /// .filter(sql: "custom.color = ?", arguments: ["red"]) public func aliased(_ alias: TableAlias) -> Self { - return mapQuery { $0.qualified(with: alias) } + return mapRelation { $0.qualified(with: alias) } } } @@ -268,28 +268,28 @@ extension Association { /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapQuery { association.joinedQuery($0, joinOperator: .optional) } + return mapRelation { association.joinedRelation($0, joinOperator: .optional) } } /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapQuery { association.joinedQuery($0, joinOperator: .required) } + return mapRelation { association.joinedRelation($0, joinOperator: .required) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapQuery { association.select([]).joinedQuery($0, joinOperator: .optional) } + return mapRelation { association.select([]).joinedRelation($0, joinOperator: .optional) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapQuery { association.select([]).joinedQuery($0, joinOperator: .required) } + return mapRelation { association.select([]).joinedRelation($0, joinOperator: .required) } } } @@ -317,7 +317,7 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { // Turn the association query into a query interface request: // JOIN association -> SELECT FROM association - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(relation: relation) // Turn the JOIN condition into a regular WHERE condition .filter { db in diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index c34afbd4b..69a345c1b 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -71,7 +71,7 @@ public struct BelongsToAssociation: Association { public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition /// :nodoc: - public /* TODO: make internal when no longer required by Association */ var query: JoinQuery + public /* TODO: make internal when no longer required by Association */ var relation: SQLRelation public func forKey(_ key: String) -> BelongsToAssociation { var assoc = self @@ -80,10 +80,10 @@ public struct BelongsToAssociation: Association { } /// :nodoc: - public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> BelongsToAssociation { - var impl = self - impl.query = transform(query) - return impl + public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> BelongsToAssociation { + var assoc = self + assoc.relation = transform(relation) + return assoc } /// :nodoc: @@ -91,17 +91,17 @@ public struct BelongsToAssociation: Association { let join = Join( joinOperator: joinOperator, joinCondition: joinCondition, - query: query) + relation: relation) return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) } /// :nodoc: - public func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery { + public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { let join = Join( joinOperator: joinOperator, joinCondition: joinCondition, - query: self.query) - return query.appendingJoin(join, forKey: key) + relation: self.relation) + return relation.appendingJoin(join, forKey: key) } } @@ -187,6 +187,6 @@ extension TableRecord { return BelongsToAssociation( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - query: Destination.all().asJoinQuery()) + relation: Destination.all().relation) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 35d4a6e48..24481719b 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -71,7 +71,7 @@ public struct HasManyAssociation: Association { public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition /// :nodoc: - public /* TODO: make internal when no longer required by Association */ var query: JoinQuery + public /* TODO: make internal when no longer required by Association */ var relation: SQLRelation public func forKey(_ key: String) -> HasManyAssociation { var assoc = self @@ -80,10 +80,10 @@ public struct HasManyAssociation: Association { } /// :nodoc: - public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> HasManyAssociation { - var impl = self - impl.query = transform(query) - return impl + public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> HasManyAssociation { + var assoc = self + assoc.relation = transform(relation) + return assoc } /// :nodoc: @@ -91,17 +91,17 @@ public struct HasManyAssociation: Association { let join = Join( joinOperator: joinOperator, joinCondition: joinCondition, - query: query) + relation: relation) return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) } /// :nodoc: - public func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery { + public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { let join = Join( joinOperator: joinOperator, joinCondition: joinCondition, - query: self.query) - return query.appendingJoin(join, forKey: key) + relation: self.relation) + return relation.appendingJoin(join, forKey: key) } } @@ -276,6 +276,6 @@ extension TableRecord { return HasManyAssociation( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - query: Destination.all().asJoinQuery()) + relation: Destination.all().relation) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index c9895091a..20a417644 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -73,7 +73,7 @@ public struct HasOneAssociation : Association { public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition /// :nodoc: - public /* TODO: make internal when no longer required by Association */ var query: JoinQuery + public /* TODO: make internal when no longer required by Association */ var relation: SQLRelation public func forKey(_ key: String) -> HasOneAssociation { var assoc = self @@ -82,10 +82,10 @@ public struct HasOneAssociation : Association { } /// :nodoc: - public func mapQuery(_ transform: (JoinQuery) -> JoinQuery) -> HasOneAssociation { - var impl = self - impl.query = transform(query) - return impl + public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> HasOneAssociation { + var assoc = self + assoc.relation = transform(relation) + return assoc } /// :nodoc: @@ -93,17 +93,17 @@ public struct HasOneAssociation : Association { let join = Join( joinOperator: joinOperator, joinCondition: joinCondition, - query: query) - return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) + relation: relation) + return QueryInterfaceRequest(relation: request.relation.appendingJoin(join, forKey: key)) } /// :nodoc: - public func joinedQuery(_ query: JoinQuery, joinOperator: JoinOperator) -> JoinQuery { + public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { let join = Join( joinOperator: joinOperator, joinCondition: joinCondition, - query: self.query) - return query.appendingJoin(join, forKey: key) + relation: self.relation) + return relation.appendingJoin(join, forKey: key) } } @@ -189,6 +189,6 @@ extension TableRecord { return HasOneAssociation( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - query: Destination.all().asJoinQuery()) + relation: Destination.all().relation) } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 175289d4b..d68b59a45 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -49,13 +49,13 @@ struct QueryInterfaceQuery { self.joins = joins } - init(_ query: JoinQuery) { + init(_ relation: SQLRelation) { self.init( - source: query.source, - selection: query.selection, - filterPromise: query.filterPromise, - ordering: query.ordering, - joins: query.joins) + source: relation.source, + selection: relation.selection, + filterPromise: relation.filterPromise, + ordering: relation.ordering, + joins: relation.joins) } var alias: TableAlias? { @@ -553,31 +553,31 @@ extension JoinCondition: Equatable { } struct Join { var joinOperator: JoinOperator var joinCondition: JoinCondition - var query: JoinQuery + var relation: SQLRelation var finalizedJoin: Join { var join = self - join.query = query.finalizedQuery + join.relation = relation.finalizedRelation return join } var finalizedAliases: [TableAlias] { - return query.finalizedAliases + return relation.finalizedAliases } var finalizedSelection: [SQLSelectable] { - return query.finalizedSelection + return relation.finalizedSelection } var finalizedOrdering: QueryOrdering { - return query.finalizedOrdering + return relation.finalizedOrdering } func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { - return try query.finalizedRowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) + return try relation.finalizedRowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) } - /// precondition: query is the result of finalizedQuery + /// precondition: relation is the result of finalizedRelation func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { var isRequiredAllowed = isRequiredAllowed var sql = "" @@ -593,32 +593,32 @@ struct Join { sql += "JOIN" } - sql += try " " + query.source.sourceSQL(db, &context) + sql += try " " + relation.source.sourceSQL(db, &context) - let rightAlias = query.alias! + let rightAlias = relation.alias! let filters = try [ joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), - query.filterPromise.resolve(db) + relation.filterPromise.resolve(db) ].compactMap { $0 } if !filters.isEmpty { sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) } - for (_, join) in query.joins { + for (_, join) in relation.joins { sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) } return sql } - /// Returns nil if joins can't be merged (conflict in condition, query...) + /// Returns nil if joins can't be merged (conflict in condition, relation...) func merged(with other: Join) -> Join? { guard joinCondition == other.joinCondition else { // can't merge return nil } - guard let mergedQuery = query.merged(with: other.query) else { + guard let mergedRelation = relation.merged(with: other.relation) else { // can't merge return nil } @@ -634,7 +634,7 @@ struct Join { return Join( joinOperator: mergedJoinOperator, joinCondition: joinCondition, - query: mergedQuery) + relation: mergedRelation) } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 6d0535673..447a9990a 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -8,8 +8,8 @@ public struct QueryInterfaceRequest { self.query = query } - init(query: JoinQuery) { - self.query = QueryInterfaceQuery(query) + init(relation: SQLRelation) { + self.query = QueryInterfaceQuery(relation) } } @@ -232,10 +232,10 @@ extension QueryInterfaceRequest { /// This method helps initializing associations: /// /// struct Book: TableRecord { - /// // invokes Author.all().asJoinQuery() + /// // invokes Author.all().relation /// static let author = belongsTo(Author.self) /// } - func asJoinQuery() -> JoinQuery { + var relation: SQLRelation { let query = self.query GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") @@ -243,7 +243,7 @@ extension QueryInterfaceRequest { GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries") GRDBPrecondition(query.limit == nil, "Can't join limited queries") - return JoinQuery( + return SQLRelation( source: query.source, selection: query.selection, filterPromise: query.filterPromise, diff --git a/GRDB/QueryInterface/Association/JoinQuery.swift b/GRDB/QueryInterface/SQLRelation.swift similarity index 66% rename from GRDB/QueryInterface/Association/JoinQuery.swift rename to GRDB/QueryInterface/SQLRelation.swift index 3200cd5fa..908330050 100644 --- a/GRDB/QueryInterface/Association/JoinQuery.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -1,7 +1,11 @@ /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// +/// A "relation" as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology): +/// +/// > A set of tuples sharing the same attributes; a set of columns and rows. +/// /// :nodoc: -public /* TODO: make internal when possible */ struct JoinQuery { +public /* TODO: make internal when possible */ struct SQLRelation { var source: SQLSource var selection: [SQLSelectable] var filterPromise: DatabasePromise @@ -13,76 +17,76 @@ public /* TODO: make internal when possible */ struct JoinQuery { } } -extension JoinQuery { - func select(_ selection: [SQLSelectable]) -> JoinQuery { - var query = self - query.selection = selection - return query +extension SQLRelation { + func select(_ selection: [SQLSelectable]) -> SQLRelation { + var relation = self + relation.selection = selection + return relation } - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> JoinQuery { - var query = self - query.filterPromise = query.filterPromise.map { (db, filter) in + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLRelation { + var relation = self + relation.filterPromise = relation.filterPromise.map { (db, filter) in if let filter = filter { return try filter && predicate(db) } else { return try predicate(db).sqlExpression } } - return query + return relation } - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> JoinQuery { + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> SQLRelation { return order(QueryOrdering(orderings: orderings)) } - func reversed() -> JoinQuery { + func reversed() -> SQLRelation { return order(ordering.reversed) } - private func order(_ ordering: QueryOrdering) -> JoinQuery { - var query = self - query.ordering = ordering - return query + private func order(_ ordering: QueryOrdering) -> SQLRelation { + var relation = self + relation.ordering = ordering + return relation } - func appendingJoin(_ join: Join, forKey key: String) -> JoinQuery { - var query = self - if let existingJoin = query.joins.removeValue(forKey: key) { + func appendingJoin(_ join: Join, forKey key: String) -> SQLRelation { + var relation = self + if let existingJoin = relation.joins.removeValue(forKey: key) { guard let mergedJoin = existingJoin.merged(with: join) else { // can't merge fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") } - query.joins.append(value: mergedJoin, forKey: key) + relation.joins.append(value: mergedJoin, forKey: key) } else { - query.joins.append(value: join, forKey: key) + relation.joins.append(value: join, forKey: key) } - return query + return relation } - func qualified(with alias: TableAlias) -> JoinQuery { - var query = self - query.source = source.qualified(with: alias) - return query + func qualified(with alias: TableAlias) -> SQLRelation { + var relation = self + relation.source = source.qualified(with: alias) + return relation } } -extension JoinQuery { - /// A finalized query is ready for SQL generation - var finalizedQuery: JoinQuery { - var query = self +extension SQLRelation { + /// A finalized relation is ready for SQL generation + var finalizedRelation: SQLRelation { + var relation = self let alias = TableAlias() - query.source = source.qualified(with: alias) - query.selection = selection.map { $0.qualifiedSelectable(with: alias) } - query.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } - query.ordering = ordering.qualified(with: alias) - query.joins = joins.mapValues { $0.finalizedJoin } + relation.source = source.qualified(with: alias) + relation.selection = selection.map { $0.qualifiedSelectable(with: alias) } + relation.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + relation.ordering = ordering.qualified(with: alias) + relation.joins = joins.mapValues { $0.finalizedJoin } - return query + return relation } - /// precondition: self is the result of finalizedQuery + /// precondition: self is the result of finalizedRelation var finalizedAliases: [TableAlias] { var aliases: [TableAlias] = [] if let alias = alias { @@ -93,21 +97,21 @@ extension JoinQuery { } } - /// precondition: self is the result of finalizedQuery + /// precondition: self is the result of finalizedRelation var finalizedSelection: [SQLSelectable] { return joins.reduce(into: selection) { $0.append(contentsOf: $1.value.finalizedSelection) } } - /// precondition: self is the result of finalizedQuery + /// precondition: self is the result of finalizedRelation var finalizedOrdering: QueryOrdering { return joins.reduce(ordering) { $0.appending($1.value.finalizedOrdering) } } - /// precondition: self is the result of finalizedQuery + /// precondition: self is the result of finalizedRelation func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { let selectionWidth = try selection .map { try $0.columnCount(db) } @@ -131,9 +135,9 @@ extension JoinQuery { } } -extension JoinQuery { +extension SQLRelation { /// Returns nil if queries can't be merged (conflict in source, joins...) - func merged(with other: JoinQuery) -> JoinQuery? { + func merged(with other: SQLRelation) -> SQLRelation? { guard let mergedSource = source.merged(with: other.source) else { // can't merge return nil @@ -170,7 +174,7 @@ extension JoinQuery { // replace ordering unless empty let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering - return JoinQuery( + return SQLRelation( source: mergedSource, selection: mergedSelection, filterPromise: mergedFilterPromise, diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 5c8445238..36e4fe69b 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -296,8 +296,6 @@ 5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */; }; 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; - 5653EB9320961FC000F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* JoinQuery.swift */; }; - 5653EB9420961FC000F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* JoinQuery.swift */; }; 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8920961FBF00F46237 /* ForeignKey.swift */; }; @@ -922,6 +920,8 @@ 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D91A9C2205DD5200770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9B2205DD5200770D8D /* SQLRelation.swift */; }; + 56D91A9D2205DD5200770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9B2205DD5200770D8D /* SQLRelation.swift */; }; 56DAA2D31DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; @@ -1104,7 +1104,6 @@ 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; - 5653EB8720961FBF00F46237 /* JoinQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinQuery.swift; sourceTree = ""; }; 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; 5653EB8920961FBF00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; @@ -1304,6 +1303,7 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; + 56D91A9B2205DD5200770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.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 = ""; }; @@ -1617,6 +1617,7 @@ 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */, 5653EC19209873E600F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, + 56D91A9B2205DD5200770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, @@ -1669,7 +1670,6 @@ 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */, 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */, 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */, - 5653EB8720961FBF00F46237 /* JoinQuery.swift */, ); path = Association; sourceTree = ""; @@ -2333,6 +2333,7 @@ 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 5613ED8121A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, + 56D91A9C2205DD5200770D8D /* SQLRelation.swift in Sources */, 56D1215B1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 5613ED8921A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */, @@ -2395,7 +2396,6 @@ 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, - 5653EB9320961FC000F46237 /* JoinQuery.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, 5659F4891EA8D94E004A4992 /* Utils.swift in Sources */, 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */, @@ -2820,6 +2820,7 @@ 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 5613ED8221A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, + 56D91A9D2205DD5200770D8D /* SQLRelation.swift in Sources */, 56D1215E1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 5613ED8A21A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */, @@ -2882,7 +2883,6 @@ 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, - 5653EB9420961FC000F46237 /* JoinQuery.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, 5659F48C1EA8D94E004A4992 /* Utils.swift in Sources */, 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 644402f28..6f64f7e7a 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -121,8 +121,6 @@ 5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */; }; 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; - 5653EB4520961F6100F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* JoinQuery.swift */; }; - 5653EB4620961F6100F46237 /* JoinQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* JoinQuery.swift */; }; 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3B20961F6000F46237 /* ForeignKey.swift */; }; @@ -384,6 +382,8 @@ 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D91A9F2205E02300770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9E2205E02300770D8D /* SQLRelation.swift */; }; + 56D91AA02205E02300770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9E2205E02300770D8D /* SQLRelation.swift */; }; 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -739,7 +739,6 @@ 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; 5653EB3820961F6000F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; - 5653EB3920961F6000F46237 /* JoinQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinQuery.swift; sourceTree = ""; }; 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; 5653EB3B20961F6000F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; @@ -929,6 +928,7 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; + 56D91A9E2205E02300770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.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 = ""; }; @@ -1225,6 +1225,7 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, 5653EC072098737400F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, + 56D91A9E2205E02300770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, @@ -1277,7 +1278,6 @@ 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */, 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */, 5653EB3820961F6000F46237 /* HasOneAssociation.swift */, - 5653EB3920961F6000F46237 /* JoinQuery.swift */, ); path = Association; sourceTree = ""; @@ -2026,12 +2026,12 @@ 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB141D10899D006283EF /* URL.swift in Sources */, 5613ED6A21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, + 56D91AA02205E02300770D8D /* SQLRelation.swift in Sources */, 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, - 5653EB4620961F6100F46237 /* JoinQuery.swift in Sources */, F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, @@ -2333,12 +2333,12 @@ 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, 5613ED6921A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, + 56D91A9F2205E02300770D8D /* SQLRelation.swift in Sources */, 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, - 5653EB4520961F6100F46237 /* JoinQuery.swift in Sources */, F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, From 5a942d72135b6744058b0b3ec58a2c6dfc7c1a60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 16:20:43 +0100 Subject: [PATCH 10/26] More trimming: QueryInterfaceQuery now embeds a SQLRelation --- GRDB/QueryInterface/QueryInterfaceQuery.swift | 202 +++++------------- .../QueryInterfaceRequest.swift | 13 +- GRDB/QueryInterface/SQLRelation.swift | 26 ++- 3 files changed, 84 insertions(+), 157 deletions(-) diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index d68b59a45..5555db9d9 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -17,63 +17,42 @@ struct DatabasePromise { } struct QueryInterfaceQuery { - var source: SQLSource - var selection: [SQLSelectable] + var relation: SQLRelation var isDistinct: Bool - var filterPromise: DatabasePromise var groupPromise: DatabasePromise<[SQLExpression]>? - var ordering: QueryOrdering var havingExpression: SQLExpression? var limit: SQLLimit? - var joins: OrderedDictionary init( - source: SQLSource, - selection: [SQLSelectable] = [], + relation: SQLRelation, isDistinct: Bool = false, - filterPromise: DatabasePromise = DatabasePromise(value: nil), groupPromise: DatabasePromise<[SQLExpression]>? = nil, - ordering: QueryOrdering = QueryOrdering(), havingExpression: SQLExpression? = nil, - limit: SQLLimit? = nil, - joins: OrderedDictionary = [:]) + limit: SQLLimit? = nil) { - self.source = source - self.selection = selection + self.relation = relation self.isDistinct = isDistinct - self.filterPromise = filterPromise self.groupPromise = groupPromise - self.ordering = ordering self.havingExpression = havingExpression self.limit = limit - self.joins = joins - } - - init(_ relation: SQLRelation) { - self.init( - source: relation.source, - selection: relation.selection, - filterPromise: relation.filterPromise, - ordering: relation.ordering, - joins: relation.joins) } var alias: TableAlias? { - return source.alias + return relation.alias } } -extension QueryInterfaceQuery { +extension QueryInterfaceQuery: SelectionRequest, FilteredRequest, OrderedRequest { func select(_ selection: [SQLSelectable]) -> QueryInterfaceQuery { - var query = self - query.selection = selection - return query + return mapRelation { $0.select(selection) } } func annotated(with selection: [SQLSelectable]) -> QueryInterfaceQuery { - var query = self - query.selection.append(contentsOf: selection) - return query + return mapRelation { + var relation = $0 + relation.selection.append(contentsOf: selection) + return relation + } } func distinct() -> QueryInterfaceQuery { @@ -83,15 +62,7 @@ extension QueryInterfaceQuery { } func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceQuery { - var query = self - query.filterPromise = query.filterPromise.map { (db, filter) in - if let filter = filter { - return try filter && predicate(db) - } else { - return try predicate(db).sqlExpression - } - } - return query + return mapRelation { $0.filter(predicate) } } func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceQuery { @@ -111,23 +82,15 @@ extension QueryInterfaceQuery { } func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceQuery { - return order(QueryOrdering(orderings: orderings)) + return mapRelation { $0.order(orderings) } } func reversed() -> QueryInterfaceQuery { - return order(ordering.reversed) - } - - private func order(_ ordering: QueryOrdering) -> QueryInterfaceQuery { - var query = self - query.ordering = ordering - return query + return mapRelation { $0.reversed() } } func unordered() -> QueryInterfaceQuery { - var query = self - query.ordering = QueryOrdering() - return query + return mapRelation { $0.unordered() } } func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceQuery { @@ -137,22 +100,16 @@ extension QueryInterfaceQuery { } func appendingJoin(_ join: Join, forKey key: String) -> QueryInterfaceQuery { - var query = self - if let existingJoin = query.joins.removeValue(forKey: key) { - guard let mergedJoin = existingJoin.merged(with: join) else { - // can't merge - fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") - } - query.joins.append(value: mergedJoin, forKey: key) - } else { - query.joins.append(value: join, forKey: key) - } - return query + return mapRelation { $0.appendingJoin(join, forKey: key) } } func qualified(with alias: TableAlias) -> QueryInterfaceQuery { + return mapRelation { $0.qualified(with: alias) } + } + + private func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> QueryInterfaceQuery { var query = self - query.source = source.qualified(with: alias) + query.relation = transform(relation) return query } } @@ -162,74 +119,31 @@ extension QueryInterfaceQuery { var finalizedQuery: QueryInterfaceQuery { var query = self - let alias = TableAlias() - query.source = source.qualified(with: alias) - query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) } - query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + query.relation = query.relation.finalizedRelation + let alias = query.relation.alias! query.groupPromise = query.groupPromise?.map { [alias] (_, exprs) in exprs.map { $0.qualifiedExpression(with: alias) } } - query.ordering = query.ordering.qualified(with: alias) query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias) - query.joins = query.joins.mapValues { $0.finalizedJoin } - return query } - /// precondition: self is the result of finalizedQuery - var finalizedAliases: [TableAlias] { - var aliases: [TableAlias] = [] - if let alias = alias { - aliases.append(alias) - } - return joins.reduce(into: aliases) { - $0.append(contentsOf: $1.value.finalizedAliases) - } - } - - /// precondition: self is the result of finalizedQuery - var finalizedSelection: [SQLSelectable] { - return joins.reduce(into: selection) { - $0.append(contentsOf: $1.value.finalizedSelection) - } - } - - /// precondition: self is the result of finalizedQuery - var finalizedOrdering: QueryOrdering { - return joins.reduce(ordering) { - $0.appending($1.value.finalizedOrdering) - } - } - - /// precondition: self is the result of finalizedQuery + /// - precondition: self is the result of finalizedQuery private func finalizedRowAdapter(_ db: Database) throws -> RowAdapter? { - if joins.isEmpty { + // No join => no adapter + if relation.joins.isEmpty { return nil } - let selectionWidth = try selection - .map { try $0.columnCount(db) } - .reduce(0, +) - - var endIndex = selectionWidth - var scopes: [String: RowAdapter] = [:] - for (key, join) in joins { - if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: [key]) { - scopes[key] = joinAdapter - endIndex = joinEndIndex - } - } - - if selectionWidth == 0 && scopes.isEmpty { + guard let (adapter, _) = try relation.finalizedRowAdapter(db, fromIndex: 0, forKeyPath: []) else { return nil } - let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth)) - return adapter.addingScopes(scopes) + return adapter } } extension QueryInterfaceQuery { - /// precondition: self is the result of finalizedQuery + /// - precondition: self is the result of finalizedQuery func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { var sql = "SELECT" @@ -237,17 +151,17 @@ extension QueryInterfaceQuery { sql += " DISTINCT" } - let selection = finalizedSelection + let selection = relation.finalizedSelection GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - sql += try " FROM " + source.sourceSQL(db, &context) + sql += try " FROM " + relation.source.sourceSQL(db, &context) - for (_, join) in joins { + for (_, join) in relation.joins { sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true) } - if let filter = try filterPromise.resolve(db) { + if let filter = try relation.filterPromise.resolve(db) { sql += " WHERE " + filter.expressionSQL(&context) } @@ -261,7 +175,7 @@ extension QueryInterfaceQuery { sql += " HAVING " + havingExpression.expressionSQL(&context) } - let orderings = try finalizedOrdering.resolve(db) + let orderings = try relation.finalizedOrdering.resolve(db) if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") } @@ -273,16 +187,16 @@ extension QueryInterfaceQuery { return sql } - /// precondition: self is the result of finalizedQuery + /// - precondition: self is the result of finalizedQuery private func makeSelectStatement(_ db: Database) throws -> SelectStatement { - var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases) + var context = SQLGenerationContext.queryGenerationContext(aliases: relation.finalizedAliases) let sql = try self.sql(db, &context) let statement = try db.makeSelectStatement(sql) statement.arguments = context.arguments! return statement } - /// precondition: self is the result of finalizedQuery + /// - precondition: self is the result of finalizedQuery func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { // Programmer error @@ -294,26 +208,26 @@ extension QueryInterfaceQuery { fatalError("Can't delete query with HAVING clause") } - guard joins.isEmpty else { + guard relation.joins.isEmpty else { // Programmer error fatalError("Can't delete query with JOIN clause") } - guard case .table = source else { + guard case .table = relation.source else { // Programmer error fatalError("Can't delete without any database table") } - var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases) + var context = SQLGenerationContext.queryGenerationContext(aliases: relation.finalizedAliases) - var sql = try "DELETE FROM " + source.sourceSQL(db, &context) + var sql = try "DELETE FROM " + relation.source.sourceSQL(db, &context) - if let filter = try filterPromise.resolve(db) { + if let filter = try relation.filterPromise.resolve(db) { sql += " WHERE " + filter.expressionSQL(&context) } if let limit = limit { - let orderings = try finalizedOrdering.resolve(db) + let orderings = try relation.finalizedOrdering.resolve(db) if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") } @@ -330,7 +244,7 @@ extension QueryInterfaceQuery { return statement } - /// precondition: self is the result of finalizedQuery + /// - precondition: self is the result of finalizedQuery func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { return try (makeSelectStatement(db), finalizedRowAdapter(db)) } @@ -341,7 +255,7 @@ extension QueryInterfaceQuery { } /// The database region that the request looks into. - /// precondition: self is the result of finalizedQuery + /// - precondition: self is the result of finalizedQuery func databaseRegion(_ db: Database) throws -> DatabaseRegion { let statement = try makeSelectStatement(db) let databaseRegion = statement.databaseRegion @@ -349,7 +263,7 @@ extension QueryInterfaceQuery { // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table - guard case .table(tableName: let tableName, alias: _) = source else { + guard case .table(tableName: let tableName, alias: _) = relation.source else { // TODO: try harder return databaseRegion } @@ -361,7 +275,7 @@ extension QueryInterfaceQuery { } // Give up unless there is a where clause - guard let filter = try filterPromise.resolve(db) else { + guard let filter = try relation.filterPromise.resolve(db) else { return databaseRegion } @@ -382,19 +296,18 @@ extension QueryInterfaceQuery { return trivialCountQuery } - guard joins.isEmpty, case .table = source else { + guard relation.joins.isEmpty, case .table = relation.source else { // SELECT ... FROM (something which is not a plain table) return trivialCountQuery } - GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") - if selection.count == 1 { - guard let count = self.selection[0].count(distinct: isDistinct) else { + GRDBPrecondition(!relation.selection.isEmpty, "Can't generate SQL with empty selection") + if relation.selection.count == 1 { + guard let count = relation.selection[0].count(distinct: isDistinct) else { return trivialCountQuery } - var countQuery = self.unordered() + var countQuery = self.unordered().select(count.sqlSelectable) countQuery.isDistinct = false - countQuery.selection = [count.sqlSelectable] return countQuery } else { // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... @@ -406,17 +319,16 @@ extension QueryInterfaceQuery { // SELECT expr1, expr2, ... FROM tableName ... // -> // SELECT COUNT(*) FROM tableName ... - var countQuery = self.unordered() - countQuery.selection = [SQLExpressionCount(AllColumns())] - return countQuery + return self.unordered().select(SQLExpressionCount(AllColumns())) } } // SELECT COUNT(*) FROM (self) private var trivialCountQuery: QueryInterfaceQuery { - return QueryInterfaceQuery( + let relation = SQLRelation( source: .query(unordered()), selection: [SQLExpressionCount(AllColumns())]) + return QueryInterfaceQuery(relation: relation) } } @@ -577,7 +489,7 @@ struct Join { return try relation.finalizedRowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) } - /// precondition: relation is the result of finalizedRelation + /// - precondition: relation is the result of finalizedRelation func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { var isRequiredAllowed = isRequiredAllowed var sql = "" diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 447a9990a..08a9c44fd 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -9,7 +9,7 @@ public struct QueryInterfaceRequest { } init(relation: SQLRelation) { - self.query = QueryInterfaceQuery(relation) + self.query = QueryInterfaceQuery(relation: relation) } } @@ -238,17 +238,13 @@ extension QueryInterfaceRequest { var relation: SQLRelation { let query = self.query + // Prevent information loss GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries") GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries") GRDBPrecondition(query.limit == nil, "Can't join limited queries") - return SQLRelation( - source: query.source, - selection: query.selection, - filterPromise: query.filterPromise, - ordering: query.ordering, - joins: query.joins) + return query.relation } } @@ -294,9 +290,10 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func all() -> QueryInterfaceRequest { - let query = QueryInterfaceQuery( + let relation = SQLRelation( source: .table(tableName: databaseTableName, alias: nil), selection: databaseSelection) + let query = QueryInterfaceQuery(relation: relation) return QueryInterfaceRequest(query: query) } diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 908330050..1174b111c 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -15,6 +15,20 @@ public /* TODO: make internal when possible */ struct SQLRelation { var alias: TableAlias? { return source.alias } + + init( + source: SQLSource, + selection: [SQLSelectable] = [], + filterPromise: DatabasePromise = DatabasePromise(value: nil), + ordering: QueryOrdering = QueryOrdering(), + joins: OrderedDictionary = [:]) + { + self.source = source + self.selection = selection + self.filterPromise = filterPromise + self.ordering = ordering + self.joins = joins + } } extension SQLRelation { @@ -50,6 +64,10 @@ extension SQLRelation { return relation } + func unordered() -> SQLRelation { + return order(QueryOrdering()) + } + func appendingJoin(_ join: Join, forKey key: String) -> SQLRelation { var relation = self if let existingJoin = relation.joins.removeValue(forKey: key) { @@ -86,7 +104,7 @@ extension SQLRelation { return relation } - /// precondition: self is the result of finalizedRelation + /// - precondition: self is the result of finalizedRelation var finalizedAliases: [TableAlias] { var aliases: [TableAlias] = [] if let alias = alias { @@ -97,21 +115,21 @@ extension SQLRelation { } } - /// precondition: self is the result of finalizedRelation + /// - precondition: self is the result of finalizedRelation var finalizedSelection: [SQLSelectable] { return joins.reduce(into: selection) { $0.append(contentsOf: $1.value.finalizedSelection) } } - /// precondition: self is the result of finalizedRelation + /// - precondition: self is the result of finalizedRelation var finalizedOrdering: QueryOrdering { return joins.reduce(ordering) { $0.appending($1.value.finalizedOrdering) } } - /// precondition: self is the result of finalizedRelation + /// - precondition: self is the result of finalizedRelation func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { let selectionWidth = try selection .map { try $0.columnCount(db) } From 9addac6f541b2c10f7dd41a1b111eba285b8a39b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 16:43:10 +0100 Subject: [PATCH 11/26] Rename QueryOrdering to SQLRelation.Ordering --- GRDB.xcodeproj/project.pbxproj | 8 -- .../Association/Association.swift | 2 +- .../Association/HasOneAssociation.swift | 2 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 16 --- .../QueryInterfaceRequest.swift | 10 +- GRDB/QueryInterface/QueryOrdering.swift | 85 -------------- GRDB/QueryInterface/SQLRelation.swift | 107 ++++++++++++++++-- GRDBCipher.xcodeproj/project.pbxproj | 6 - GRDBCustom.xcodeproj/project.pbxproj | 6 - 9 files changed, 100 insertions(+), 142 deletions(-) delete mode 100644 GRDB/QueryInterface/QueryOrdering.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f94ade828..c708ce238 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -326,9 +326,6 @@ 565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56553C131C3E906C00522B5C /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC3773F319C8CBB3004FCF85 /* GRDB.framework */; }; - 5656BF4F20C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; - 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; - 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; 5657AAB91D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABC1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB0F1D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -1014,7 +1011,6 @@ 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; 565490A01D5A4798005622CB /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 5656BF4E20C723E300F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueryOrdering.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 = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1525,7 +1521,6 @@ 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */, - 5656BF4E20C723E300F98521 /* QueryOrdering.swift */, 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -2487,7 +2482,6 @@ 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */, 565490E21D5AE252005622CB /* Record.swift in Sources */, - 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */, 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, @@ -2718,7 +2712,6 @@ 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, - 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, @@ -3175,7 +3168,6 @@ 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5653EB0920944C7C00F46237 /* Association.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, - 5656BF4F20C723E300F98521 /* QueryOrdering.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index a1a1cfa81..4e7d1a0f0 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -317,7 +317,7 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { // Turn the association query into a query interface request: // JOIN association -> SELECT FROM association - return QueryInterfaceRequest(relation: relation) + return QueryInterfaceRequest(query: QueryInterfaceQuery(relation: relation)) // Turn the JOIN condition into a regular WHERE condition .filter { db in diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 20a417644..6ae4e9e99 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -94,7 +94,7 @@ public struct HasOneAssociation : Association { joinOperator: joinOperator, joinCondition: joinCondition, relation: relation) - return QueryInterfaceRequest(relation: request.relation.appendingJoin(join, forKey: key)) + return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) } /// :nodoc: diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 5555db9d9..89e0785ab 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -473,22 +473,6 @@ struct Join { return join } - var finalizedAliases: [TableAlias] { - return relation.finalizedAliases - } - - var finalizedSelection: [SQLSelectable] { - return relation.finalizedSelection - } - - var finalizedOrdering: QueryOrdering { - return relation.finalizedOrdering - } - - func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { - return try relation.finalizedRowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) - } - /// - precondition: relation is the result of finalizedRelation func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { var isRequiredAllowed = isRequiredAllowed diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 08a9c44fd..1434d7aee 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -3,14 +3,6 @@ /// See https://github.com/groue/GRDB.swift#the-query-interface public struct QueryInterfaceRequest { let query: QueryInterfaceQuery - - init(query: QueryInterfaceQuery) { - self.query = query - } - - init(relation: SQLRelation) { - self.query = QueryInterfaceQuery(relation: relation) - } } extension QueryInterfaceRequest : FetchRequest { @@ -227,7 +219,7 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { } extension QueryInterfaceRequest { - /// Turns a request into a JoinQuery. + /// Turns a request into a SQLRelation. /// /// This method helps initializing associations: /// diff --git a/GRDB/QueryInterface/QueryOrdering.swift b/GRDB/QueryInterface/QueryOrdering.swift deleted file mode 100644 index 73c4e421a..000000000 --- a/GRDB/QueryInterface/QueryOrdering.swift +++ /dev/null @@ -1,85 +0,0 @@ -/// QueryOrdering provides the order clause to QueryInterfaceQuery -/// and JoinQuery. -struct QueryOrdering { - private enum Element { - case orderingTerms((Database) throws -> [SQLOrderingTerm]) - case queryOrdering(QueryOrdering) - - var reversed: Element { - switch self { - case .orderingTerms(let orderings): - return .orderingTerms { db in try orderings(db).map { $0.reversed } } - case .queryOrdering(let queryOrdering): - return .queryOrdering(queryOrdering.reversed) - } - } - - func qualified(with alias: TableAlias) -> Element { - switch self { - case .orderingTerms(let orderings): - return .orderingTerms { db in try orderings(db).map { $0.qualifiedOrdering(with: alias) } } - case .queryOrdering(let queryOrdering): - return .queryOrdering(queryOrdering.qualified(with: alias)) - } - } - - func resolve(_ db: Database) throws -> [SQLOrderingTerm] { - switch self { - case .orderingTerms(let orderings): - return try orderings(db) - case .queryOrdering(let queryOrdering): - return try queryOrdering.resolve(db) - } - } - } - - private var elements: [Element] = [] - var isReversed: Bool - - var isEmpty: Bool { - return elements.isEmpty - } - - private init(elements: [Element], isReversed: Bool) { - self.elements = elements - self.isReversed = isReversed - } - - init() { - self.init( - elements: [], - isReversed: false) - } - - init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) { - self.init( - elements: [.orderingTerms(orderings)], - isReversed: false) - } - - var reversed: QueryOrdering { - return QueryOrdering( - elements: elements, - isReversed: !isReversed) - } - - func qualified(with alias: TableAlias) -> QueryOrdering { - return QueryOrdering( - elements: elements.map { $0.qualified(with: alias) }, - isReversed: isReversed) - } - - func appending(_ ordering: QueryOrdering) -> QueryOrdering { - return QueryOrdering( - elements: elements + [.queryOrdering(ordering)], - isReversed: isReversed) - } - - func resolve(_ db: Database) throws -> [SQLOrderingTerm] { - if isReversed { - return try elements.flatMap { try $0.reversed.resolve(db) } - } else { - return try elements.flatMap { try $0.resolve(db) } - } - } -} diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 1174b111c..e5f776ecd 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -9,7 +9,7 @@ public /* TODO: make internal when possible */ struct SQLRelation { var source: SQLSource var selection: [SQLSelectable] var filterPromise: DatabasePromise - var ordering: QueryOrdering + var ordering: SQLRelation.Ordering var joins: OrderedDictionary var alias: TableAlias? { @@ -20,7 +20,7 @@ public /* TODO: make internal when possible */ struct SQLRelation { source: SQLSource, selection: [SQLSelectable] = [], filterPromise: DatabasePromise = DatabasePromise(value: nil), - ordering: QueryOrdering = QueryOrdering(), + ordering: SQLRelation.Ordering = SQLRelation.Ordering(), joins: OrderedDictionary = [:]) { self.source = source @@ -31,6 +31,93 @@ public /* TODO: make internal when possible */ struct SQLRelation { } } +extension SQLRelation { + /// SQLRelation.Ordering provides the order clause to SQLRelation. + struct Ordering { + private enum Element { + case terms(DatabasePromise<[SQLOrderingTerm]>) + case ordering(SQLRelation.Ordering) + + var reversed: Element { + switch self { + case .terms(let terms): + return .terms(terms.map { (db, terms) in terms.map { $0.reversed } }) + case .ordering(let ordering): + return .ordering(ordering.reversed) + } + } + + func qualified(with alias: TableAlias) -> Element { + switch self { + case .terms(let terms): + return .terms(terms.map { (db, terms) in terms.map { $0.qualifiedOrdering(with: alias) } }) + case .ordering(let ordering): + return .ordering(ordering.qualified(with: alias)) + } + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + switch self { + case .terms(let terms): + return try terms.resolve(db) + case .ordering(let ordering): + return try ordering.resolve(db) + } + } + } + + private var elements: [Element] = [] + var isReversed: Bool + + var isEmpty: Bool { + return elements.isEmpty + } + + private init(elements: [Element], isReversed: Bool) { + self.elements = elements + self.isReversed = isReversed + } + + init() { + self.init( + elements: [], + isReversed: false) + } + + init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) { + self.init( + elements: [.terms(DatabasePromise(orderings))], + isReversed: false) + } + + var reversed: Ordering { + return Ordering( + elements: elements, + isReversed: !isReversed) + } + + func qualified(with alias: TableAlias) -> Ordering { + return Ordering( + elements: elements.map { $0.qualified(with: alias) }, + isReversed: isReversed) + } + + func appending(_ ordering: Ordering) -> Ordering { + return Ordering( + elements: elements + [.ordering(ordering)], + isReversed: isReversed) + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + if isReversed { + return try elements.flatMap { try $0.reversed.resolve(db) } + } else { + return try elements.flatMap { try $0.resolve(db) } + } + } + } +} + extension SQLRelation { func select(_ selection: [SQLSelectable]) -> SQLRelation { var relation = self @@ -51,21 +138,21 @@ extension SQLRelation { } func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> SQLRelation { - return order(QueryOrdering(orderings: orderings)) + return order(SQLRelation.Ordering(orderings: orderings)) } func reversed() -> SQLRelation { return order(ordering.reversed) } - private func order(_ ordering: QueryOrdering) -> SQLRelation { + private func order(_ ordering: SQLRelation.Ordering) -> SQLRelation { var relation = self relation.ordering = ordering return relation } func unordered() -> SQLRelation { - return order(QueryOrdering()) + return order(SQLRelation.Ordering()) } func appendingJoin(_ join: Join, forKey key: String) -> SQLRelation { @@ -111,21 +198,21 @@ extension SQLRelation { aliases.append(alias) } return joins.reduce(into: aliases) { - $0.append(contentsOf: $1.value.finalizedAliases) + $0.append(contentsOf: $1.value.relation.finalizedAliases) } } /// - precondition: self is the result of finalizedRelation var finalizedSelection: [SQLSelectable] { return joins.reduce(into: selection) { - $0.append(contentsOf: $1.value.finalizedSelection) + $0.append(contentsOf: $1.value.relation.finalizedSelection) } } /// - precondition: self is the result of finalizedRelation - var finalizedOrdering: QueryOrdering { + var finalizedOrdering: SQLRelation.Ordering { return joins.reduce(ordering) { - $0.appending($1.value.finalizedOrdering) + $0.appending($1.value.relation.finalizedOrdering) } } @@ -138,7 +225,7 @@ extension SQLRelation { var endIndex = startIndex + selectionWidth var scopes: [String: RowAdapter] = [:] for (key, join) in joins { - if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { + if let (joinAdapter, joinEndIndex) = try join.relation.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { scopes[key] = joinAdapter endIndex = joinEndIndex } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 36e4fe69b..caf178266 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -366,8 +366,6 @@ 5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */; }; 5653EC1A209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; 5653EC1B209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; - 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5C20C7248700F98521 /* QueryOrdering.swift */; }; - 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5C20C7248700F98521 /* QueryOrdering.swift */; }; 5657AABA1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABD1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB101D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -1125,7 +1123,6 @@ 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 5653EC19209873E600F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; - 5656BF5C20C7248700F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryOrdering.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 = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1608,7 +1605,6 @@ 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */, - 5656BF5C20C7248700F98521 /* QueryOrdering.swift */, 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -2377,7 +2373,6 @@ 56CEB55B1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D301DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */, - 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5613ED8721A95E8400DC7A68 /* ValueReducer.swift in Sources */, @@ -2864,7 +2859,6 @@ 56CEB55E1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D331DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */, - 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5613ED8821A95E8400DC7A68 /* ValueReducer.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 6f64f7e7a..86e01a98d 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -161,8 +161,6 @@ 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; 5653EC082098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; 5653EC092098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; - 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5820C7247100F98521 /* QueryOrdering.swift */; }; - 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5820C7247100F98521 /* QueryOrdering.swift */; }; 5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABE1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB111D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -759,7 +757,6 @@ 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5653EC072098737400F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; - 5656BF5820C7247100F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryOrdering.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 = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1216,7 +1213,6 @@ 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */, - 5656BF5820C7247100F98521 /* QueryOrdering.swift */, 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -2013,7 +2009,6 @@ F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, 56A8C2351D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D341DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, 5613ED6E21A95E6100DC7A68 /* ValueReducer.swift in Sources */, @@ -2320,7 +2315,6 @@ F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D311DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, 5613ED6D21A95E6100DC7A68 /* ValueReducer.swift in Sources */, From 89dda44364c29fca70511b5510d256142423c82e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 17:04:16 +0100 Subject: [PATCH 12/26] Extract and document DatabasePromise --- GRDB.xcodeproj/project.pbxproj | 8 ++++ GRDB/QueryInterface/DatabasePromise.swift | 44 +++++++++++++++++++ GRDB/QueryInterface/QueryInterfaceQuery.swift | 18 -------- GRDB/QueryInterface/SQLRelation.swift | 2 +- GRDBCipher.xcodeproj/project.pbxproj | 6 +++ GRDBCustom.xcodeproj/project.pbxproj | 6 +++ 6 files changed, 65 insertions(+), 19 deletions(-) create mode 100644 GRDB/QueryInterface/DatabasePromise.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index c708ce238..36996b8ea 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -725,6 +725,9 @@ 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; 56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; 56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; + 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 */; }; 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 */; }; @@ -1208,6 +1211,7 @@ 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InsertRecordStructTests.swift; sourceTree = ""; }; 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 = ""; }; 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 = ""; }; @@ -1516,6 +1520,7 @@ children = ( 5653EAF720944BC900F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, + 56D91AA82205F2F000770D8D /* DatabasePromise.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, @@ -2530,6 +2535,7 @@ 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 56E06F181E85906E008AE2A4 /* Fixits-0.102.0.swift in Sources */, 56B964A31DA51B4C0002DA19 /* FTS5.swift in Sources */, + 56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */, 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 565490BB1D5AE236005622CB /* DatabaseReader.swift in Sources */, 5659F4A61EA8D997004A4992 /* Result.swift in Sources */, @@ -2700,6 +2706,7 @@ 569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */, + 56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */, 5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 56D1215D1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, @@ -3177,6 +3184,7 @@ 5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, + 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */, 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */, 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, diff --git a/GRDB/QueryInterface/DatabasePromise.swift b/GRDB/QueryInterface/DatabasePromise.swift new file mode 100644 index 000000000..3d25acecf --- /dev/null +++ b/GRDB/QueryInterface/DatabasePromise.swift @@ -0,0 +1,44 @@ +/// DatabasePromise represents a value that can only be resolved when a +/// database connection is available. +/// +/// This type is important for the query interface, which lets the user define +/// requests without any database context. +/// +/// For example, consider those two requests: +/// +/// let playerRequest = Player.filter(key: 1) +/// let countryRequest = Country.filter(key: "FR") +/// +/// Both need a database connection in order to introspect the database schema, +/// find the primary key of both table, and generate the correct SQL: +/// +/// try dbQueue.read { db in +/// // SELECT * FROM player WHERE id = 1 +/// let player = try playerRequest.fetchOne(db) +/// // SELECT * FROM country WHERE code = 'FR' +/// let country = try countryRequest.fetchOne(db) +/// } +/// +/// Such late computations are backed by DatabasePromise. In our example, +/// see SQLRelation.filterPromise. +struct DatabasePromise { + /// Returns the resolved value. + let resolve: (Database) throws -> T + + /// Creates a promise that resolves to a value. + init(value: T) { + self.resolve = { _ in value } + } + + /// Creates a promise from a closure. + init(_ resolve: @escaping (Database) throws -> T) { + self.resolve = resolve + } + + /// Returns a promise whose value is transformed by the given closure. + func map(_ transform: @escaping (Database, T) throws -> U) -> DatabasePromise { + return DatabasePromise { db in + try transform(db, self.resolve(db)) + } + } +} diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 89e0785ab..73844f42a 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -1,21 +1,3 @@ -struct DatabasePromise { - let resolve: (Database) throws -> T - - init(value: T) { - self.resolve = { _ in value } - } - - init(_ resolve: @escaping (Database) throws -> T) { - self.resolve = resolve - } - - func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise { - return DatabasePromise { db in - try transform(db, self.resolve(db)) - } - } -} - struct QueryInterfaceQuery { var relation: SQLRelation var isDistinct: Bool diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index e5f776ecd..366b0c775 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -248,7 +248,7 @@ extension SQLRelation { return nil } - let mergedFilterPromise = filterPromise.map { (db, expression) in + let mergedFilterPromise = filterPromise.map { (db, expression) -> SQLExpression? in let otherExpression = try other.filterPromise.resolve(db) let expressions = [expression, otherExpression].compactMap { $0 } if expressions.isEmpty { diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index caf178266..07050de40 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -920,6 +920,8 @@ 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D91A9C2205DD5200770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9B2205DD5200770D8D /* SQLRelation.swift */; }; 56D91A9D2205DD5200770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9B2205DD5200770D8D /* SQLRelation.swift */; }; + 56D91AAD2205F30200770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAC2205F30200770D8D /* DatabasePromise.swift */; }; + 56D91AAE2205F30200770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAC2205F30200770D8D /* DatabasePromise.swift */; }; 56DAA2D31DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; @@ -1301,6 +1303,7 @@ 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56D91A9B2205DD5200770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; + 56D91AAC2205F30200770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.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 = ""; }; @@ -1600,6 +1603,7 @@ children = ( 5653EB8420961FBF00F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, + 56D91AAC2205F30200770D8D /* DatabasePromise.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, @@ -2387,6 +2391,7 @@ 5613ED8321A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7C20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, + 56D91AAD2205F30200770D8D /* DatabasePromise.swift in Sources */, 560FC5331CB003810014AA8E /* Migration.swift in Sources */, 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, @@ -2873,6 +2878,7 @@ 5613ED8421A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7D20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */, + 56D91AAE2205F30200770D8D /* DatabasePromise.swift in Sources */, 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */, 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 86e01a98d..8ea39349e 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -382,6 +382,8 @@ 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D91A9F2205E02300770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9E2205E02300770D8D /* SQLRelation.swift */; }; 56D91AA02205E02300770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9E2205E02300770D8D /* SQLRelation.swift */; }; + 56D91AA62205F2CF00770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA52205F2CF00770D8D /* DatabasePromise.swift */; }; + 56D91AA72205F2CF00770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA52205F2CF00770D8D /* DatabasePromise.swift */; }; 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -926,6 +928,7 @@ 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56D91A9E2205E02300770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; + 56D91AA52205F2CF00770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabasePromise.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 = ""; }; @@ -1208,6 +1211,7 @@ children = ( 5653EB3620961F6000F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, + 56D91AA52205F2CF00770D8D /* DatabasePromise.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, @@ -2024,6 +2028,7 @@ 56D91AA02205E02300770D8D /* SQLRelation.swift in Sources */, 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */, + 56D91AA72205F2CF00770D8D /* DatabasePromise.swift in Sources */, F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, @@ -2330,6 +2335,7 @@ 56D91A9F2205E02300770D8D /* SQLRelation.swift in Sources */, 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */, + 56D91AA62205F2CF00770D8D /* DatabasePromise.swift in Sources */, F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, From 40f6b351ead0e6324d2266fd6f2337e29cb89bee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 17:15:29 +0100 Subject: [PATCH 13/26] Rename QueryInterfaceQuery to SQLSelectQuery --- GRDB.xcodeproj/project.pbxproj | 16 +++--- .../Association/Association.swift | 2 +- .../QueryInterfaceRequest.swift | 4 +- .../QueryInterface/SQLGenerationContext.swift | 2 +- GRDB/QueryInterface/SQLRelation.swift | 6 +++ ...erfaceQuery.swift => SQLSelectQuery.swift} | 51 +++++++++---------- GRDBCipher.xcodeproj/project.pbxproj | 12 ++--- GRDBCustom.xcodeproj/project.pbxproj | 12 ++--- 8 files changed, 54 insertions(+), 51 deletions(-) rename GRDB/QueryInterface/{QueryInterfaceQuery.swift => SQLSelectQuery.swift} (93%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 36996b8ea..b5fe20bb8 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -27,8 +27,6 @@ 5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; }; 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; - 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; @@ -318,7 +316,6 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; @@ -728,6 +725,9 @@ 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 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.swift */; }; + 56D91AB12205F8AC00770D8D /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.swift */; }; + 56D91AB22205F8AC00770D8D /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.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 */; }; @@ -909,7 +909,6 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -1212,6 +1211,7 @@ 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 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.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 = ""; }; @@ -1523,7 +1523,6 @@ 56D91AA82205F2F000770D8D /* DatabasePromise.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */, @@ -1537,6 +1536,7 @@ 56D91AA12205E03700770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, + 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -2491,6 +2491,7 @@ 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, + 56D91AB22205F8AC00770D8D /* SQLSelectQuery.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, @@ -2582,7 +2583,6 @@ 565490D31D5AE252005622CB /* (null) in Sources */, 566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 566B910F1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, - 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */, 56F5ABDD1D814330001F60CB /* UUID.swift in Sources */, 565490CB1D5AE252005622CB /* (null) in Sources */, 563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */, @@ -2683,7 +2683,7 @@ 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */, - 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, + 56D91AB12205F8AC00770D8D /* SQLSelectQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, 5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, @@ -3110,6 +3110,7 @@ files = ( 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, + 56D91AB02205F8AC00770D8D /* SQLSelectQuery.swift in Sources */, 5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 56BF6D3D1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -3187,7 +3188,6 @@ 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */, 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */, - 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 5613ED3521A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */, 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 4e7d1a0f0..50430e4e4 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -317,7 +317,7 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { // Turn the association query into a query interface request: // JOIN association -> SELECT FROM association - return QueryInterfaceRequest(query: QueryInterfaceQuery(relation: relation)) + return QueryInterfaceRequest(query: SQLSelectQuery(relation: relation)) // Turn the JOIN condition into a regular WHERE condition .filter { db in diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 1434d7aee..3595e9785 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -2,7 +2,7 @@ /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct QueryInterfaceRequest { - let query: QueryInterfaceQuery + let query: SQLSelectQuery } extension QueryInterfaceRequest : FetchRequest { @@ -285,7 +285,7 @@ extension TableRecord { let relation = SQLRelation( source: .table(tableName: databaseTableName, alias: nil), selection: databaseSelection) - let query = QueryInterfaceQuery(relation: relation) + let query = SQLSelectQuery(relation: relation) return QueryInterfaceRequest(query: query) } diff --git a/GRDB/QueryInterface/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGenerationContext.swift index ffa06b1a5..95dfd274a 100644 --- a/GRDB/QueryInterface/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGenerationContext.swift @@ -17,7 +17,7 @@ public struct SQLGenerationContext { qualifierNeeded: false) } - /// Used for QueryInterfaceQuery.makeSelectStatement() and QueryInterfaceQuery.makeDeleteStatement() + /// Used for SQLSelectQuery.makeSelectStatement() and SQLSelectQuery.makeDeleteStatement() static func queryGenerationContext(aliases: [TableAlias]) -> SQLGenerationContext { return SQLGenerationContext( arguments: [], diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 366b0c775..da7ce435b 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -125,6 +125,12 @@ extension SQLRelation { return relation } + func annotated(with selection: [SQLSelectable]) -> SQLRelation { + var relation = self + relation.selection.append(contentsOf: selection) + return relation + } + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLRelation { var relation = self relation.filterPromise = relation.filterPromise.map { (db, filter) in diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift similarity index 93% rename from GRDB/QueryInterface/QueryInterfaceQuery.swift rename to GRDB/QueryInterface/SQLSelectQuery.swift index 73844f42a..ef45a1ea5 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -1,4 +1,5 @@ -struct QueryInterfaceQuery { +/// The SQLSelectQuery generates SQL for query interface requests. +struct SQLSelectQuery { var relation: SQLRelation var isDistinct: Bool var groupPromise: DatabasePromise<[SQLExpression]>? @@ -24,36 +25,32 @@ struct QueryInterfaceQuery { } } -extension QueryInterfaceQuery: SelectionRequest, FilteredRequest, OrderedRequest { - func select(_ selection: [SQLSelectable]) -> QueryInterfaceQuery { +extension SQLSelectQuery: SelectionRequest, FilteredRequest, OrderedRequest { + func select(_ selection: [SQLSelectable]) -> SQLSelectQuery { return mapRelation { $0.select(selection) } } - func annotated(with selection: [SQLSelectable]) -> QueryInterfaceQuery { - return mapRelation { - var relation = $0 - relation.selection.append(contentsOf: selection) - return relation - } + func annotated(with selection: [SQLSelectable]) -> SQLSelectQuery { + return mapRelation { $0.annotated(with: selection) } } - func distinct() -> QueryInterfaceQuery { + func distinct() -> SQLSelectQuery { var query = self query.isDistinct = true return query } - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceQuery { + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLSelectQuery { return mapRelation { $0.filter(predicate) } } - func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceQuery { + func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> SQLSelectQuery { var query = self query.groupPromise = DatabasePromise { db in try expressions(db).map { $0.sqlExpression } } return query } - func having(_ predicate: SQLExpressible) -> QueryInterfaceQuery { + func having(_ predicate: SQLExpressible) -> SQLSelectQuery { var query = self if let havingExpression = query.havingExpression { query.havingExpression = (havingExpression && predicate).sqlExpression @@ -63,42 +60,42 @@ extension QueryInterfaceQuery: SelectionRequest, FilteredRequest, OrderedRequest return query } - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceQuery { + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> SQLSelectQuery { return mapRelation { $0.order(orderings) } } - func reversed() -> QueryInterfaceQuery { + func reversed() -> SQLSelectQuery { return mapRelation { $0.reversed() } } - func unordered() -> QueryInterfaceQuery { + func unordered() -> SQLSelectQuery { return mapRelation { $0.unordered() } } - func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceQuery { + func limit(_ limit: Int, offset: Int? = nil) -> SQLSelectQuery { var query = self query.limit = SQLLimit(limit: limit, offset: offset) return query } - func appendingJoin(_ join: Join, forKey key: String) -> QueryInterfaceQuery { + func appendingJoin(_ join: Join, forKey key: String) -> SQLSelectQuery { return mapRelation { $0.appendingJoin(join, forKey: key) } } - func qualified(with alias: TableAlias) -> QueryInterfaceQuery { + func qualified(with alias: TableAlias) -> SQLSelectQuery { return mapRelation { $0.qualified(with: alias) } } - private func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> QueryInterfaceQuery { + private func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> SQLSelectQuery { var query = self query.relation = transform(relation) return query } } -extension QueryInterfaceQuery { +extension SQLSelectQuery { /// A finalized query is ready for SQL generation - var finalizedQuery: QueryInterfaceQuery { + var finalizedQuery: SQLSelectQuery { var query = self query.relation = query.relation.finalizedRelation @@ -124,7 +121,7 @@ extension QueryInterfaceQuery { } } -extension QueryInterfaceQuery { +extension SQLSelectQuery { /// - precondition: self is the result of finalizedQuery func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { var sql = "SELECT" @@ -271,7 +268,7 @@ extension QueryInterfaceQuery { return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds) } - private var countQuery: QueryInterfaceQuery { + private var countQuery: SQLSelectQuery { guard groupPromise == nil && limit == nil else { // SELECT ... GROUP BY ... // SELECT ... LIMIT ... @@ -306,11 +303,11 @@ extension QueryInterfaceQuery { } // SELECT COUNT(*) FROM (self) - private var trivialCountQuery: QueryInterfaceQuery { + private var trivialCountQuery: SQLSelectQuery { let relation = SQLRelation( source: .query(unordered()), selection: [SQLExpressionCount(AllColumns())]) - return QueryInterfaceQuery(relation: relation) + return SQLSelectQuery(relation: relation) } } @@ -520,7 +517,7 @@ struct Join { enum SQLSource { case table(tableName: String, alias: TableAlias?) - indirect case query(QueryInterfaceQuery) + indirect case query(SQLSelectQuery) var alias: TableAlias? { switch self { diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 07050de40..14f84c3ef 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -25,7 +25,6 @@ 560FC5311CB003810014AA8E /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 560FC5331CB003810014AA8E /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; - 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 560FC5351CB003810014AA8E /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; 560FC5371CB003810014AA8E /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -705,7 +704,6 @@ 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; - 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 56AFCA0C1CB1A8BB00F48B96 /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -922,6 +920,8 @@ 56D91A9D2205DD5200770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9B2205DD5200770D8D /* SQLRelation.swift */; }; 56D91AAD2205F30200770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAC2205F30200770D8D /* DatabasePromise.swift */; }; 56D91AAE2205F30200770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAC2205F30200770D8D /* DatabasePromise.swift */; }; + 56D91AB42205F8C000770D8D /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */; }; + 56D91AB52205F8C000770D8D /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */; }; 56DAA2D31DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; @@ -1023,7 +1023,6 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -1304,6 +1303,7 @@ 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56D91A9B2205DD5200770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; 56D91AAC2205F30200770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = ""; }; + 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.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 = ""; }; @@ -1606,7 +1606,6 @@ 56D91AAC2205F30200770D8D /* DatabasePromise.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */, @@ -1620,6 +1619,7 @@ 56D91A9B2205DD5200770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, + 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -2317,6 +2317,7 @@ files = ( 56873BED1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 563EF43C2161183E007DAACD /* AssociationAggregate.swift in Sources */, + 56D91AB42205F8C000770D8D /* SQLSelectQuery.swift in Sources */, 56BF6D3E1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, 5616AAF9207CD5A900AC3664 /* RequestProtocols.swift in Sources */, 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */, @@ -2393,7 +2394,6 @@ 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, 56D91AAD2205F30200770D8D /* DatabasePromise.swift in Sources */, 560FC5331CB003810014AA8E /* Migration.swift in Sources */, - 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, @@ -2804,6 +2804,7 @@ files = ( 56873BF01F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 563EF43D2161183E007DAACD /* AssociationAggregate.swift in Sources */, + 56D91AB52205F8C000770D8D /* SQLSelectQuery.swift in Sources */, 56BF6D411DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, 5616AAFA207CD5A900AC3664 /* RequestProtocols.swift in Sources */, 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */, @@ -2880,7 +2881,6 @@ 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */, 56D91AAE2205F30200770D8D /* DatabasePromise.swift in Sources */, 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */, - 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 8ea39349e..77514725e 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -435,7 +435,7 @@ F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; + F3BA802F1CFB289B003DC1BA /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; @@ -479,7 +479,7 @@ F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; + F3BA808B1CFB2E70003DC1BA /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; @@ -661,7 +661,7 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; + 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -1214,7 +1214,6 @@ 56D91AA52205F2CF00770D8D /* DatabasePromise.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */, @@ -1228,6 +1227,7 @@ 56D91A9E2205E02300770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, + 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -2007,7 +2007,7 @@ 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, 564CE4DB21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */, - F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */, + F3BA802F1CFB289B003DC1BA /* SQLSelectQuery.swift in Sources */, 56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55F1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, @@ -2314,7 +2314,7 @@ 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, 564CE4DA21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */, - F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */, + F3BA808B1CFB2E70003DC1BA /* SQLSelectQuery.swift in Sources */, 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55C1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, From e62cfe086c6a8f3044f28f90c9eff45149aff4ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 17:23:50 +0100 Subject: [PATCH 14/26] Documentation --- .../QueryInterfaceRequest.swift | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 3595e9785..3bd1d4f96 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -1,3 +1,22 @@ +/// QueryInterfaceRequest is the type of requests generated by TableRecord: +/// +/// struct Player: TableRecord { ... } +/// let playerRequest = Player.all() // QueryInterfaceRequest +/// +/// It wraps an SQLSelectQuery, and has an attached type. +/// +/// The attached type helps decoding raw database values: +/// +/// try dbQueue.read { db in +/// try playerRequest.fetchAll(db) // [Player] +/// try playerRequest.asRequest(of: Row.self).fetchAll(db) // [Row] +/// } +/// +/// The attached type also helps the compiler validate associated requests: +/// +/// playerRequest.including(required: Player.team) // OK +/// fruitRequest.including(required: Player.team) // Does not compile + /// A QueryInterfaceRequest describes an SQL query. /// /// See https://github.com/groue/GRDB.swift#the-query-interface From 27c6390635eef3ac47d3db341e703674eb19f025 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 17:53:01 +0100 Subject: [PATCH 15/26] More Association trimming --- .../Association/Association.swift | 29 +++++----- .../Association/BelongsToAssociation.swift | 9 ---- .../Association/HasManyAssociation.swift | 9 ---- .../Association/HasOneAssociation.swift | 9 ---- .../FTS3+QueryInterfaceRequest.swift | 3 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 3 +- .../QueryInterfaceRequest.swift | 53 +++++++++++-------- GRDB/QueryInterface/SQLSelectQuery.swift | 3 +- 8 files changed, 47 insertions(+), 71 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 50430e4e4..f8ada0ab2 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -4,29 +4,19 @@ /// /// :nodoc: public protocol _Association { - /// Returns a transformed association. + /// Returns an association whose relation is transformed by the + /// given closure. /// /// This method provides fundamental support for association derivation: /// - /// // Invokes Book.author.mapQuery { $0.filter(...) } + /// // Invokes Book.author.mapRelation { $0.filter(...) } /// Book.author.filter(...) func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self - /// Returns a request joined with self. + /// Returns a relation joined with self. /// - /// This method provides fundamental support for joining methods: - /// - /// // Invokes Book.author.joinedRequest(Book.all(), .required) - /// Book.including(required: Book.author) - func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest - - /// Returns a query joined with self. - /// - /// This method provides fundamental support for joining methods: - /// - /// // Invokes Book.author.mapQuery { Author.country.joinedRelation($0, .optional) } - /// Book.including(required: Book.author.including(optional: Author.country) - func joinedRelation(_ query: SQLRelation, joinOperator: JoinOperator) -> SQLRelation + /// This method provides fundamental support for joining methods. + func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation // TODO: remove relation & joinCondition properties. // @@ -42,6 +32,13 @@ public protocol _Association { var joinCondition: JoinCondition { get } } +extension _Association { + /// Returns a request joined with self. + func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { + return request.mapQuery { $0.mapRelation { joinedRelation($0, joinOperator: joinOperator) } } + } +} + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The base protocol for all associations that define a connection between two diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 69a345c1b..c20048166 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -86,15 +86,6 @@ public struct BelongsToAssociation: Association { return assoc } - /// :nodoc: - public func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { - let join = Join( - joinOperator: joinOperator, - joinCondition: joinCondition, - relation: relation) - return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) - } - /// :nodoc: public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { let join = Join( diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 24481719b..0e74acf33 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -86,15 +86,6 @@ public struct HasManyAssociation: Association { return assoc } - /// :nodoc: - public func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { - let join = Join( - joinOperator: joinOperator, - joinCondition: joinCondition, - relation: relation) - return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) - } - /// :nodoc: public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { let join = Join( diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 6ae4e9e99..b5cf88c94 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -88,15 +88,6 @@ public struct HasOneAssociation : Association { return assoc } - /// :nodoc: - public func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { - let join = Join( - joinOperator: joinOperator, - joinCondition: joinCondition, - relation: relation) - return QueryInterfaceRequest(query: request.query.appendingJoin(join, forKey: key)) - } - /// :nodoc: public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { let join = Join( diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 0c1d56aaa..7bdfaade4 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -16,9 +16,8 @@ extension QueryInterfaceRequest { return none() } let alias = TableAlias() - let qualifiedQuery = query.qualified(with: alias) let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) - return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression) + return self.aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index 2affcfe44..ab3bb55e0 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -21,9 +21,8 @@ return none() } let alias = TableAlias() - let qualifiedQuery = query.qualified(with: alias) let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) - return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression) + return self.aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 3bd1d4f96..d41bdf733 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -21,7 +21,7 @@ /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct QueryInterfaceRequest { - let query: SQLSelectQuery + var query: SQLSelectQuery } extension QueryInterfaceRequest : FetchRequest { @@ -70,8 +70,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// request /// .select([Column("id")]) /// .select([Column("email")]) - public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.select(selection)) + public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { + return mapQuery { $0.select(selection) } } /// Creates a request which selects *selection*, and fetches values of @@ -83,7 +83,7 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// let maxScore: Int? = try request.fetchOne(db) /// } public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.select(selection)) + return mapQuery { $0.select(selection) }.asRequest(of: RowDecoder.self) } /// Creates a request which selects *selection*, and fetches values of @@ -117,8 +117,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) - public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.annotated(with: selection)) + public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { + return mapQuery { $0.annotated(with: selection) } } /// Creates a request which returns distinct rows. @@ -130,8 +130,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// // SELECT DISTINCT name FROM player /// var request = Player.select(Column("name")) /// request = request.distinct() - public func distinct() -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.distinct()) + public func distinct() -> QueryInterfaceRequest { + return mapQuery { $0.distinct() } } /// Creates a request with the provided *predicate promise* added to the @@ -140,19 +140,19 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// // SELECT * FROM player WHERE 1 /// var request = Player.all() /// request = request.filter { db in true } - public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.filter(predicate)) + public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { + return mapQuery { $0.filter(predicate) } } /// Creates a request grouped according to *expressions promise*. - public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.group(expressions)) + public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { + return mapQuery { $0.group(expressions) } } /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. - public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.having(predicate)) + public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { + return mapQuery { $0.having(predicate) } } /// Creates a request with the provided *orderings promise*. @@ -168,8 +168,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// .order{ _ in [Column("email")] } /// .reversed() /// .order{ _ in [Column("name")] } - public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.order(orderings)) + public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { + return mapQuery { $0.order(orderings) } } /// Creates a request that reverses applied orderings. @@ -183,8 +183,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// // SELECT * FROM player /// var request = Player.all() /// request = request.reversed() - public func reversed() -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.reversed()) + public func reversed() -> QueryInterfaceRequest { + return mapQuery { $0.reversed() } } /// Creates a request which fetches *limit* rows, starting at *offset*. @@ -194,8 +194,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// request = request.limit(1) /// /// Any previous limit is replaced. - public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.limit(limit, offset: offset)) + public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { + return mapQuery { $0.limit(limit, offset: offset) } } /// Creates a request that allows you to define expressions that target @@ -216,7 +216,7 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// .aliased(playerAlias) /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.qualified(with: alias)) + return mapQuery { $0.qualified(with: alias) } } /// Creates a request bound to type Target. @@ -232,8 +232,15 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// /// - parameter type: The fetched type Target /// - returns: A typed request bound to type Target. - public func asRequest(of type: Target.Type) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query) + public func asRequest(of type: RowDecoder.Type) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query) + } + + /// Returns a request whose query is transformed by the given closure. + func mapQuery(_ transform: (SQLSelectQuery) -> SQLSelectQuery) -> QueryInterfaceRequest { + var request = self + request.query = transform(query) + return request } } diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index ef45a1ea5..325488312 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -86,7 +86,8 @@ extension SQLSelectQuery: SelectionRequest, FilteredRequest, OrderedRequest { return mapRelation { $0.qualified(with: alias) } } - private func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> SQLSelectQuery { + /// Returns a query whose relation is transformed by the given closure. + func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> SQLSelectQuery { var query = self query.relation = transform(relation) return query From f42d5f202dcc3ebfbde5d221bbaf567c8ef3efd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 2 Feb 2019 17:57:01 +0100 Subject: [PATCH 16/26] White space --- GRDB/QueryInterface/Association/Association.swift | 12 ++++++------ .../Association/BelongsToAssociation.swift | 4 ++-- .../Association/HasManyAssociation.swift | 6 +++--- .../Association/HasOneAssociation.swift | 4 ++-- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index f8ada0ab2..2ea26c9d0 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -307,15 +307,15 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { func request(from record: OriginRowDecoder) -> QueryInterfaceRequest { // Goal: turn `JOIN association ON association.recordId = record.id` // into a regular request `SELECT * FROM association WHERE association.recordId = 123` - + // We need table aliases to build the joining condition let associationAlias = TableAlias() let recordAlias = TableAlias() - + // Turn the association query into a query interface request: // JOIN association -> SELECT FROM association return QueryInterfaceRequest(query: SQLSelectQuery(relation: relation)) - + // Turn the JOIN condition into a regular WHERE condition .filter { db in // Build a join condition: `association.recordId = record.id` @@ -323,16 +323,16 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { guard let joinExpression = try self.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { fatalError("Can't request from record without join condition") } - + // Serialize record: ["id": 123, ...] // We do it as late as possible, when request is about to be // executed, in order to support long-lived reference types. let container = PersistenceContainer(record) - + // Replace `record.id` with 123 return joinExpression.resolvedExpression(inContext: [recordAlias: container]) } - + // We just added a condition qualified with associationAlias. Don't // risk introducing conflicting aliases that would prevent the user // from setting a custom alias name: force the same alias for the diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index c20048166..08336152a 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -64,9 +64,9 @@ public struct BelongsToAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination - + public var key: String - + /// :nodoc: public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 0e74acf33..d83832087 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -64,9 +64,9 @@ public struct HasManyAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination - + public var key: String - + /// :nodoc: public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition @@ -175,7 +175,7 @@ extension HasManyAssociation where Origin: TableRecord, Destination: TableRecord return aggregate } } - + /// The sum of the given expression in associated records. /// /// For example: diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index b5cf88c94..b003262bf 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -66,9 +66,9 @@ public struct HasOneAssociation : Association { /// :nodoc: public typealias RowDecoder = Destination - + public var key: String - + /// :nodoc: public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition From c9ff5a53a174877bec369d2d6f5742ebdd43f8b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 00:03:04 +0100 Subject: [PATCH 17/26] JoinCondition: Equatable --- GRDB/QueryInterface/SQLSelectQuery.swift | 37 +++++++++++------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index 325488312..0e71c0f94 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -373,8 +373,24 @@ public /* TODO: make internal when possible */ enum JoinOperator { /// When we eventually add support for new ways to join tables, JoinCondition /// is the type we'll need to update. /// +/// JoinCondition equality allows merging of associations: +/// +/// // request1 and request2 are equivalent +/// let request1 = Book +/// .including(required: Book.author) +/// let request2 = Book +/// .including(required: Book.author) +/// .including(required: Book.author) +/// +/// // request3 and request4 are equivalent +/// let request3 = Book +/// .including(required: Book.author.filter(condition1 && condition2)) +/// let request4 = Book +/// .joining(required: Book.author.filter(condition1)) +/// .including(optional: Book.author.filter(condition2)) +/// /// :nodoc: -public /* TODO: make internal when possible */ struct JoinCondition { +public /* TODO: make internal when possible */ struct JoinCondition: Equatable { /// Definition of a foreign key var foreignKeyRequest: ForeignKeyRequest @@ -423,25 +439,6 @@ public /* TODO: make internal when possible */ struct JoinCondition { } } -/// JoinCondition equality allows merging of associations: -/// -/// // request1 and request2 are equivalent -/// let request1 = Book -/// .including(required: Book.author) -/// let request2 = Book -/// .including(required: Book.author) -/// .including(required: Book.author) -/// -/// // request3 and request4 are equivalent -/// let request3 = Book -/// .including(required: Book.author.filter(condition1 && condition2)) -/// let request4 = Book -/// .joining(required: Book.author.filter(condition1)) -/// .including(optional: Book.author.filter(condition2)) -/// -/// :nodoc: -extension JoinCondition: Equatable { } - struct Join { var joinOperator: JoinOperator var joinCondition: JoinCondition From 950fa607a15545a24c9382b50f5568cf3d5ae7e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 08:26:58 +0100 Subject: [PATCH 18/26] Hide implementation details of associations --- .../Association/Association.swift | 144 +++++++++++------- .../Association/BelongsToAssociation.swift | 29 ++-- .../Association/HasManyAssociation.swift | 29 ++-- .../Association/HasOneAssociation.swift | 31 ++-- .../QueryInterfaceRequest+Association.swift | 8 +- GRDB/QueryInterface/SQLRelation.swift | 2 +- GRDB/QueryInterface/SQLSelectQuery.swift | 4 +- 7 files changed, 151 insertions(+), 96 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 2ea26c9d0..0d3781238 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -1,9 +1,60 @@ /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// -/// The protocol for associations implementation details. +/// The base protocol for all associations that define a connection between two +/// record types. +public protocol Association: DerivableRequest { + // OriginRowDecoder and RowDecoder provide type safety: + // + // Book.including(required: Book.author) // compiles + // Fruit.including(required: Book.author) // does not compile + + /// The record type at the origin of the association. + /// + /// In the `belongsTo` association below, it is Book: + /// + /// struct Book: TableRecord { + /// // BelongsToAssociation + /// static let author = belongsTo(Author.self) + /// } + associatedtype OriginRowDecoder + + /// The associated record type. + /// + /// In the `belongsTo` association below, it is Author: + /// + /// struct Book: TableRecord { + /// // BelongsToAssociation + /// static let author = belongsTo(Author.self) + /// } + associatedtype RowDecoder + + // Association is a protocol, not a struct. + // This is because we want associations to be richly typed. + // Yet, we don't want to pollute user code with implementation details of + // associations. So let's hide all this stuff behind the _impl property: + + /// :nodoc: + associatedtype Impl: AssociationImpl + + /// :nodoc: + var _impl: Impl { get } + + /// :nodoc: + init(_impl: Impl) +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The protocol for implementation details of associations. /// /// :nodoc: -public protocol _Association { +public /* TODO: internal */ protocol AssociationImpl { + /// The association key + var key: String { get } + + /// Creates an association with the given key. + func forKey(_ key: String) -> Self + /// Returns an association whose relation is transformed by the /// given closure. /// @@ -32,38 +83,25 @@ public protocol _Association { var joinCondition: JoinCondition { get } } -extension _Association { +extension AssociationImpl { /// Returns a request joined with self. func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { return request.mapQuery { $0.mapRelation { joinedRelation($0, joinOperator: joinOperator) } } } } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// The base protocol for all associations that define a connection between two -/// record types. -public protocol Association: _Association, DerivableRequest { - /// The record type at the origin of the association. - /// - /// In the `belongsTo` association below, it is Book: - /// - /// struct Book: TableRecord { - /// // BelongsToAssociation - /// static let author = belongsTo(Author.self) - /// } - associatedtype OriginRowDecoder - - /// The associated record type. - /// - /// In the `belongsTo` association below, it is Author: - /// - /// struct Book: TableRecord { - /// // BelongsToAssociation - /// static let author = belongsTo(Author.self) - /// } - associatedtype RowDecoder +extension Association { + private func mapImpl(_ transform: (Impl) throws -> Impl) rethrows -> Self { + return try Self.init(_impl: transform(_impl)) + } + private func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { + return mapImpl { $0.mapRelation(transform) } + } +} + +extension Association { + /// The association key defines how rows fetched from this association /// should be consumed. /// @@ -88,26 +126,10 @@ public protocol Association: _Association, DerivableRequest { /// for row in Row.fetchAll(db, request) { /// let team: Team = row["custom"] /// } - var key: String { get } + var key: String { + return _impl.key + } - /// Creates an association with the given key. - /// - /// This new key impacts how rows fetched from the resulting association - /// should be consumed: - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // Consume rows: - /// let request = Player.including(required: Player.team.forKey("custom")) - /// for row in Row.fetchAll(db, request) { - /// let team: Team = row["custom"] - /// } - func forKey(_ key: String) -> Self -} - -extension Association { /// Creates an association which selects *selection*. /// /// struct Player: TableRecord { @@ -201,6 +223,24 @@ extension Association { return mapRelation { $0.reversed() } } + /// Creates an association with the given key. + /// + /// This new key impacts how rows fetched from the resulting association + /// should be consumed: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // Consume rows: + /// let request = Player.including(required: Player.team.forKey("custom")) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["custom"] + /// } + public func forKey(_ key: String) -> Self { + return mapImpl { $0.forKey(key) } + } + /// Creates an association with the given key. /// /// This new key helps Decodable records decode rows fetched from the @@ -265,28 +305,28 @@ extension Association { /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRelation { association.joinedRelation($0, joinOperator: .optional) } + return mapRelation { association._impl.joinedRelation($0, joinOperator: .optional) } } /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRelation { association.joinedRelation($0, joinOperator: .required) } + return mapRelation { association._impl.joinedRelation($0, joinOperator: .required) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRelation { association.select([]).joinedRelation($0, joinOperator: .optional) } + return mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .optional) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRelation { association.select([]).joinedRelation($0, joinOperator: .required) } + return mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .required) } } } @@ -314,13 +354,13 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { // Turn the association query into a query interface request: // JOIN association -> SELECT FROM association - return QueryInterfaceRequest(query: SQLSelectQuery(relation: relation)) + return QueryInterfaceRequest(query: SQLSelectQuery(relation: _impl.relation)) // Turn the JOIN condition into a regular WHERE condition .filter { db in // Build a join condition: `association.recordId = record.id` // We still need to replace `record.id` with the actual record id. - guard let joinExpression = try self.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { + guard let joinExpression = try self._impl.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { fatalError("Can't request from record without join condition") } diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 08336152a..3c7269368 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -65,28 +65,33 @@ public struct BelongsToAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination + /// :nodoc: + public var _impl: BelongsToAssociationImpl + + /// :nodoc: + public init(_impl: BelongsToAssociationImpl) { + self._impl = _impl + } +} + +/// :nodoc: +public /* TODO: internal */ struct BelongsToAssociationImpl: AssociationImpl { public var key: String + public let joinCondition: JoinCondition + public var relation: SQLRelation - /// :nodoc: - public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition - - /// :nodoc: - public /* TODO: make internal when no longer required by Association */ var relation: SQLRelation - - public func forKey(_ key: String) -> BelongsToAssociation { + public func forKey(_ key: String) -> BelongsToAssociationImpl { var assoc = self assoc.key = key return assoc } - /// :nodoc: - public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> BelongsToAssociation { + public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> BelongsToAssociationImpl { var assoc = self assoc.relation = transform(relation) return assoc } - /// :nodoc: public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { let join = Join( joinOperator: joinOperator, @@ -175,9 +180,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: true) - return BelongsToAssociation( + return BelongsToAssociation(_impl: BelongsToAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - relation: Destination.all().relation) + relation: Destination.all().relation)) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index d83832087..f2a1d47b8 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -65,28 +65,33 @@ public struct HasManyAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination + /// :nodoc: + public var _impl: HasManyAssociationImpl + + /// :nodoc: + public init(_impl: HasManyAssociationImpl) { + self._impl = _impl + } +} + +/// :nodoc: +public /* TODO: internal */ struct HasManyAssociationImpl: AssociationImpl { public var key: String + public let joinCondition: JoinCondition + public var relation: SQLRelation - /// :nodoc: - public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition - - /// :nodoc: - public /* TODO: make internal when no longer required by Association */ var relation: SQLRelation - - public func forKey(_ key: String) -> HasManyAssociation { + public func forKey(_ key: String) -> HasManyAssociationImpl { var assoc = self assoc.key = key return assoc } - /// :nodoc: - public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> HasManyAssociation { + public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> HasManyAssociationImpl { var assoc = self assoc.relation = transform(relation) return assoc } - /// :nodoc: public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { let join = Join( joinOperator: joinOperator, @@ -264,9 +269,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasManyAssociation( + return HasManyAssociation(_impl: HasManyAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - relation: Destination.all().relation) + relation: Destination.all().relation)) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index b003262bf..358b86de5 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -60,35 +60,40 @@ /// } /// /// See ForeignKey for more information. -public struct HasOneAssociation : Association { +public struct HasOneAssociation: Association { /// :nodoc: public typealias OriginRowDecoder = Origin /// :nodoc: public typealias RowDecoder = Destination + /// :nodoc: + public var _impl: HasOneAssociationImpl + + /// :nodoc: + public init(_impl: HasOneAssociationImpl) { + self._impl = _impl + } +} + +/// :nodoc: +public /* TODO: internal */ struct HasOneAssociationImpl: AssociationImpl { public var key: String + public let joinCondition: JoinCondition + public var relation: SQLRelation - /// :nodoc: - public /* TODO: make internal when no longer required by Association */ let joinCondition: JoinCondition - - /// :nodoc: - public /* TODO: make internal when no longer required by Association */ var relation: SQLRelation - - public func forKey(_ key: String) -> HasOneAssociation { + public func forKey(_ key: String) -> HasOneAssociationImpl { var assoc = self assoc.key = key return assoc } - /// :nodoc: - public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> HasOneAssociation { + public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> HasOneAssociationImpl { var assoc = self assoc.relation = transform(relation) return assoc } - /// :nodoc: public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { let join = Join( joinOperator: joinOperator, @@ -177,9 +182,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasOneAssociation( + return HasOneAssociation(_impl: HasOneAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - relation: Destination.all().relation) + relation: Destination.all().relation)) } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index df7c4dcbc..46072f51e 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -5,28 +5,28 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association.joinedRequest(self, joinOperator: .optional) + return association._impl.joinedRequest(self, joinOperator: .optional) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association.joinedRequest(self, joinOperator: .required) + return association._impl.joinedRequest(self, joinOperator: .required) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association.select([]).joinedRequest(self, joinOperator: .optional) + return association.select([])._impl.joinedRequest(self, joinOperator: .optional) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association.select([]).joinedRequest(self, joinOperator: .required) + return association.select([])._impl.joinedRequest(self, joinOperator: .required) } // MARK: - Association Aggregates diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index da7ce435b..83b2aa15f 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -5,7 +5,7 @@ /// > A set of tuples sharing the same attributes; a set of columns and rows. /// /// :nodoc: -public /* TODO: make internal when possible */ struct SQLRelation { +public /* TODO: internal */ struct SQLRelation { var source: SQLSource var selection: [SQLSelectable] var filterPromise: DatabasePromise diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index 0e71c0f94..21e15f808 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -359,7 +359,7 @@ extension SQLSelectQuery { /// A.including(optional: A.b.including(required: B.c)) /// /// :nodoc: -public /* TODO: make internal when possible */ enum JoinOperator { +public /* TODO: internal */ enum JoinOperator { case required, optional } @@ -390,7 +390,7 @@ public /* TODO: make internal when possible */ enum JoinOperator { /// .including(optional: Book.author.filter(condition2)) /// /// :nodoc: -public /* TODO: make internal when possible */ struct JoinCondition: Equatable { +public /* TODO: internal */ struct JoinCondition: Equatable { /// Definition of a foreign key var foreignKeyRequest: ForeignKeyRequest From 5ea914ce0abceeaf5e2a7459afd66f10a33dd897 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 08:42:37 +0100 Subject: [PATCH 19/26] YAGNI: JoinCondition.sqlExpression is not optional --- GRDB/QueryInterface/Association/Association.swift | 4 +--- GRDB/QueryInterface/SQLSelectQuery.swift | 4 ++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 0d3781238..f9666c953 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -360,9 +360,7 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { .filter { db in // Build a join condition: `association.recordId = record.id` // We still need to replace `record.id` with the actual record id. - guard let joinExpression = try self._impl.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { - fatalError("Can't request from record without join condition") - } + let joinExpression = try self._impl.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) // Serialize record: ["id": 123, ...] // We do it as late as possible, when request is about to be diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index 21e15f808..94304673b 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -1,4 +1,4 @@ -/// The SQLSelectQuery generates SQL for query interface requests. +/// SQLSelectQuery generates SQL for query interface requests. struct SQLSelectQuery { var relation: SQLRelation var isDistinct: Bool @@ -424,7 +424,7 @@ public /* TODO: internal */ struct JoinCondition: Equatable { /// - parameter rightAlias: A TableAlias for the table on the right of the /// JOIN operator. /// - Returns: An SQL expression. - func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression? { + func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression { let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping let columnMapping: [(left: Column, right: Column)] if originIsLeft { From 91b68ffa4f4ff5bdb3c9c3525cee3ee44d5819cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 09:29:52 +0100 Subject: [PATCH 20/26] Trim --- .../Association/Association.swift | 7 ------ .../QueryInterfaceRequest+Association.swift | 24 +++++++++---------- 2 files changed, 12 insertions(+), 19 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index f9666c953..69815ffa3 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -83,13 +83,6 @@ public /* TODO: internal */ protocol AssociationImpl { var joinCondition: JoinCondition { get } } -extension AssociationImpl { - /// Returns a request joined with self. - func joinedRequest(_ request: QueryInterfaceRequest, joinOperator: JoinOperator) -> QueryInterfaceRequest { - return request.mapQuery { $0.mapRelation { joinedRelation($0, joinOperator: joinOperator) } } - } -} - extension Association { private func mapImpl(_ transform: (Impl) throws -> Impl) rethrows -> Self { return try Self.init(_impl: transform(_impl)) diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 46072f51e..d381f4af1 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -4,34 +4,34 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association._impl.joinedRequest(self, joinOperator: .optional) + public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { + return mapQuery { $0.mapRelation { association._impl.joinedRelation($0, joinOperator: .optional) } } } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association._impl.joinedRequest(self, joinOperator: .required) + public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { + return mapQuery { $0.mapRelation { association._impl.joinedRelation($0, joinOperator: .required) } } } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association.select([])._impl.joinedRequest(self, joinOperator: .optional) + public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { + return mapQuery { $0.mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .optional) } } } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return association.select([])._impl.joinedRequest(self, joinOperator: .required) + public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { + return mapQuery { $0.mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .required) } } } // MARK: - Association Aggregates - private func annotated(with aggregate: AssociationAggregate) -> QueryInterfaceRequest { + private func annotated(with aggregate: AssociationAggregate) -> QueryInterfaceRequest { let (request, expression) = aggregate.prepare(self) if let alias = aggregate.alias { return request.annotated(with: [expression.aliased(alias)]) @@ -46,7 +46,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// // FROM player LEFT JOIN book ... /// var request = Player.all() /// request = request.annotated(with: Player.books.count) - public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { + public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { return annotated(with: aggregates) } @@ -56,7 +56,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// // FROM player LEFT JOIN book ... /// var request = Player.all() /// request = request.annotated(with: [Player.books.count]) - public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { + public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { return aggregates.reduce(self) { request, aggregate in request.annotated(with: aggregate) } @@ -70,7 +70,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// // HAVING COUNT(DISTINCT book.rowid) = 0 /// var request = Player.all() /// request = request.having(Player.books.isEmpty) - public func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { + public func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { let (request, expression) = predicate.prepare(self) return request.having(expression) } From 4a209fcbc4b1ce39943707772daee357dcb3c43c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 10:06:23 +0100 Subject: [PATCH 21/26] Rename SQLSource to SQLRelation.Source --- GRDB/QueryInterface/SQLRelation.swift | 252 +++++++++++++++-------- GRDB/QueryInterface/SQLSelectQuery.swift | 70 ------- 2 files changed, 163 insertions(+), 159 deletions(-) diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 83b2aa15f..b45d178a1 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -6,7 +6,7 @@ /// /// :nodoc: public /* TODO: internal */ struct SQLRelation { - var source: SQLSource + var source: SQLRelation.Source var selection: [SQLSelectable] var filterPromise: DatabasePromise var ordering: SQLRelation.Ordering @@ -17,7 +17,7 @@ public /* TODO: internal */ struct SQLRelation { } init( - source: SQLSource, + source: SQLRelation.Source, selection: [SQLSelectable] = [], filterPromise: DatabasePromise = DatabasePromise(value: nil), ordering: SQLRelation.Ordering = SQLRelation.Ordering(), @@ -31,93 +31,6 @@ public /* TODO: internal */ struct SQLRelation { } } -extension SQLRelation { - /// SQLRelation.Ordering provides the order clause to SQLRelation. - struct Ordering { - private enum Element { - case terms(DatabasePromise<[SQLOrderingTerm]>) - case ordering(SQLRelation.Ordering) - - var reversed: Element { - switch self { - case .terms(let terms): - return .terms(terms.map { (db, terms) in terms.map { $0.reversed } }) - case .ordering(let ordering): - return .ordering(ordering.reversed) - } - } - - func qualified(with alias: TableAlias) -> Element { - switch self { - case .terms(let terms): - return .terms(terms.map { (db, terms) in terms.map { $0.qualifiedOrdering(with: alias) } }) - case .ordering(let ordering): - return .ordering(ordering.qualified(with: alias)) - } - } - - func resolve(_ db: Database) throws -> [SQLOrderingTerm] { - switch self { - case .terms(let terms): - return try terms.resolve(db) - case .ordering(let ordering): - return try ordering.resolve(db) - } - } - } - - private var elements: [Element] = [] - var isReversed: Bool - - var isEmpty: Bool { - return elements.isEmpty - } - - private init(elements: [Element], isReversed: Bool) { - self.elements = elements - self.isReversed = isReversed - } - - init() { - self.init( - elements: [], - isReversed: false) - } - - init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) { - self.init( - elements: [.terms(DatabasePromise(orderings))], - isReversed: false) - } - - var reversed: Ordering { - return Ordering( - elements: elements, - isReversed: !isReversed) - } - - func qualified(with alias: TableAlias) -> Ordering { - return Ordering( - elements: elements.map { $0.qualified(with: alias) }, - isReversed: isReversed) - } - - func appending(_ ordering: Ordering) -> Ordering { - return Ordering( - elements: elements + [.ordering(ordering)], - isReversed: isReversed) - } - - func resolve(_ db: Database) throws -> [SQLOrderingTerm] { - if isReversed { - return try elements.flatMap { try $0.reversed.resolve(db) } - } else { - return try elements.flatMap { try $0.resolve(db) } - } - } - } -} - extension SQLRelation { func select(_ selection: [SQLSelectable]) -> SQLRelation { var relation = self @@ -293,3 +206,164 @@ extension SQLRelation { joins: mergedJoins) } } + +// MARK: - SQLRelation.Source + +extension SQLRelation { + enum Source { + case table(tableName: String, alias: TableAlias?) + indirect case query(SQLSelectQuery) + + var alias: TableAlias? { + switch self { + case .table(_, let alias): + return alias + case .query(let query): + return query.alias + } + } + + func sourceSQL(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { + switch self { + case .table(let tableName, let alias): + if let alias = alias, let aliasName = context.aliasName(for: alias) { + return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" + } else { + return "\(tableName.quotedDatabaseIdentifier)" + } + case .query(let query): + return try "(\(query.sql(db, &context)))" + } + } + + func qualified(with alias: TableAlias) -> Source { + switch self { + case .table(let tableName, let sourceAlias): + if let sourceAlias = sourceAlias { + alias.becomeProxy(of: sourceAlias) + return self + } else { + alias.setTableName(tableName) + return .table(tableName: tableName, alias: alias) + } + case .query(let query): + return .query(query.qualified(with: alias)) + } + } + + /// Returns nil if sources can't be merged (conflict in tables, aliases...) + func merged(with other: Source) -> Source? { + switch (self, other) { + case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)): + guard tableName == otherTableName else { + // can't merge + return nil + } + switch (alias, otherAlias) { + case (nil, nil): + return .table(tableName: tableName, alias: nil) + case let (alias?, nil), let (nil, alias?): + return .table(tableName: tableName, alias: alias) + case let (alias?, otherAlias?): + guard let mergedAlias = alias.merge(with: otherAlias) else { + // can't merge + return nil + } + return .table(tableName: tableName, alias: mergedAlias) + } + default: + // can't merge + return nil + } + } + } +} + +// MARK: - SQLRelation.Ordering + +extension SQLRelation { + /// SQLRelation.Ordering provides the order clause to SQLRelation. + struct Ordering { + private enum Element { + case terms(DatabasePromise<[SQLOrderingTerm]>) + case ordering(SQLRelation.Ordering) + + var reversed: Element { + switch self { + case .terms(let terms): + return .terms(terms.map { (db, terms) in terms.map { $0.reversed } }) + case .ordering(let ordering): + return .ordering(ordering.reversed) + } + } + + func qualified(with alias: TableAlias) -> Element { + switch self { + case .terms(let terms): + return .terms(terms.map { (db, terms) in terms.map { $0.qualifiedOrdering(with: alias) } }) + case .ordering(let ordering): + return .ordering(ordering.qualified(with: alias)) + } + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + switch self { + case .terms(let terms): + return try terms.resolve(db) + case .ordering(let ordering): + return try ordering.resolve(db) + } + } + } + + private var elements: [Element] = [] + var isReversed: Bool + + var isEmpty: Bool { + return elements.isEmpty + } + + private init(elements: [Element], isReversed: Bool) { + self.elements = elements + self.isReversed = isReversed + } + + init() { + self.init( + elements: [], + isReversed: false) + } + + init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) { + self.init( + elements: [.terms(DatabasePromise(orderings))], + isReversed: false) + } + + var reversed: Ordering { + return Ordering( + elements: elements, + isReversed: !isReversed) + } + + func qualified(with alias: TableAlias) -> Ordering { + return Ordering( + elements: elements.map { $0.qualified(with: alias) }, + isReversed: isReversed) + } + + func appending(_ ordering: Ordering) -> Ordering { + return Ordering( + elements: elements + [.ordering(ordering)], + isReversed: isReversed) + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + if isReversed { + return try elements.flatMap { try $0.reversed.resolve(db) } + } else { + return try elements.flatMap { try $0.resolve(db) } + } + } + } +} diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index 94304673b..e00dd886a 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -511,76 +511,6 @@ struct Join { } } -// MARK: - SQLSource - -enum SQLSource { - case table(tableName: String, alias: TableAlias?) - indirect case query(SQLSelectQuery) - - var alias: TableAlias? { - switch self { - case .table(_, let alias): - return alias - case .query(let query): - return query.alias - } - } - - func sourceSQL(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { - switch self { - case .table(let tableName, let alias): - if let alias = alias, let aliasName = context.aliasName(for: alias) { - return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" - } else { - return "\(tableName.quotedDatabaseIdentifier)" - } - case .query(let query): - return try "(\(query.sql(db, &context)))" - } - } - - func qualified(with alias: TableAlias) -> SQLSource { - switch self { - case .table(let tableName, let sourceAlias): - if let sourceAlias = sourceAlias { - alias.becomeProxy(of: sourceAlias) - return self - } else { - alias.setTableName(tableName) - return .table(tableName: tableName, alias: alias) - } - case .query(let query): - return .query(query.qualified(with: alias)) - } - } - - /// Returns nil if sources can't be merged (conflict in tables, aliases...) - func merged(with other: SQLSource) -> SQLSource? { - switch (self, other) { - case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)): - guard tableName == otherTableName else { - // can't merge - return nil - } - switch (alias, otherAlias) { - case (nil, nil): - return .table(tableName: tableName, alias: nil) - case let (alias?, nil), let (nil, alias?): - return .table(tableName: tableName, alias: alias) - case let (alias?, otherAlias?): - guard let mergedAlias = alias.merge(with: otherAlias) else { - // can't merge - return nil - } - return .table(tableName: tableName, alias: mergedAlias) - } - default: - // can't merge - return nil - } - } -} - struct SQLLimit { let limit: Int let offset: Int? From 659171902e1d3ec04af628642183fc6eaef441f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 10:09:34 +0100 Subject: [PATCH 22/26] Move join-related types to SQLRelation.swift --- GRDB/QueryInterface/SQLRelation.swift | 199 ++++++++++++++++++++++ GRDB/QueryInterface/SQLSelectQuery.swift | 201 +---------------------- 2 files changed, 200 insertions(+), 200 deletions(-) diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index b45d178a1..f8172f3c5 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -367,3 +367,202 @@ extension SQLRelation { } } } + +// MARK: - Join + +/// Not to be mismatched with SQL join operators (inner join, left join). +/// +/// JoinOperator is designed to be hierarchically nested, unlike +/// SQL join operators. +/// +/// Consider the following request for (A, B, C) tuples: +/// +/// let r = A.including(optional: A.b.including(required: B.c)) +/// +/// It chains three associations, the first optional, the second required. +/// +/// It looks like it means: "Give me all As, along with their Bs, granted those +/// Bs have their Cs. For As whose B has no C, give me a nil B". +/// +/// It can not be expressed as one left join, and a regular join, as below, +/// Because this would not honor the first optional: +/// +/// -- dubious +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// JOIN c ON ... +/// +/// Instead, it should: +/// - allow (A + missing (B + C)) +/// - prevent (A + (B + missing C)). +/// +/// This can be expressed in SQL with two left joins, and an extra condition: +/// +/// -- likely correct +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// LEFT JOIN c ON ... +/// WHERE NOT((b.id IS NOT NULL) AND (c.id IS NULL)) -- no B without C +/// +/// This is currently not implemented, and requires a little more thought. +/// I don't even know if inventing a whole new way to perform joins should even +/// be on the table. But we have a hierarchical way to express joined queries, +/// and they have a meaning: +/// +/// // what is my meaning? +/// A.including(optional: A.b.including(required: B.c)) +/// +/// :nodoc: +public /* TODO: internal */ enum JoinOperator { + case required, optional +} + +/// The condition that links two joined tables. +/// +/// Currently, we only support one kind of join condition: foreign keys. +/// +/// SELECT ... FROM book JOIN author ON author.id = book.authorId +/// <- the join condition --> +/// +/// When we eventually add support for new ways to join tables, JoinCondition +/// is the type we'll need to update. +/// +/// JoinCondition equality allows merging of associations: +/// +/// // request1 and request2 are equivalent +/// let request1 = Book +/// .including(required: Book.author) +/// let request2 = Book +/// .including(required: Book.author) +/// .including(required: Book.author) +/// +/// // request3 and request4 are equivalent +/// let request3 = Book +/// .including(required: Book.author.filter(condition1 && condition2)) +/// let request4 = Book +/// .joining(required: Book.author.filter(condition1)) +/// .including(optional: Book.author.filter(condition2)) +/// +/// :nodoc: +public /* TODO: internal */ struct JoinCondition: Equatable { + /// Definition of a foreign key + var foreignKeyRequest: ForeignKeyRequest + + /// True if the table at the origin of the foreign key is on the left of + /// the sql JOIN operator. + /// + /// Let's consider the `book.authorId -> author.id` foreign key. + /// Its origin table is `book`. + /// + /// The origin table `book` is on the left of the JOIN operator for + /// the BelongsTo association: + /// + /// -- Book.including(required: Book.author) + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// + /// The origin table `book`is on the right of the JOIN operator for + /// the HasMany and HasOne associations: + /// + /// -- Author.including(required: Author.books) + /// SELECT ... FROM author JOIN book ON author.id = book.authorId + var originIsLeft: Bool + + /// Returns an SQL expression for the join condition. + /// + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// <- the SQL expression --> + /// + /// - parameter db: A database connection. + /// - parameter leftAlias: A TableAlias for the table on the left of the + /// JOIN operator. + /// - parameter rightAlias: A TableAlias for the table on the right of the + /// JOIN operator. + /// - Returns: An SQL expression. + func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression { + let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping + let columnMapping: [(left: Column, right: Column)] + if originIsLeft { + columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } + } else { + columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } + } + + return columnMapping + .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } + .joined(operator: .and) + } +} + +struct Join { + var joinOperator: JoinOperator + var joinCondition: JoinCondition + var relation: SQLRelation + + var finalizedJoin: Join { + var join = self + join.relation = relation.finalizedRelation + return join + } + + /// - precondition: relation is the result of finalizedRelation + func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { + var isRequiredAllowed = isRequiredAllowed + var sql = "" + switch joinOperator { + case .optional: + isRequiredAllowed = false + sql += "LEFT JOIN" + case .required: + guard isRequiredAllowed else { + // TODO: chainOptionalRequired + fatalError("Not implemented: chaining a required association behind an optional association") + } + sql += "JOIN" + } + + sql += try " " + relation.source.sourceSQL(db, &context) + + let rightAlias = relation.alias! + let filters = try [ + joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), + relation.filterPromise.resolve(db) + ].compactMap { $0 } + if !filters.isEmpty { + sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) + } + + for (_, join) in relation.joins { + sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) + } + + return sql + } + + /// Returns nil if joins can't be merged (conflict in condition, relation...) + func merged(with other: Join) -> Join? { + guard joinCondition == other.joinCondition else { + // can't merge + return nil + } + + guard let mergedRelation = relation.merged(with: other.relation) else { + // can't merge + return nil + } + + let mergedJoinOperator: JoinOperator + switch (joinOperator, other.joinOperator) { + case (.required, _), (_, .required): + mergedJoinOperator = .required + default: + mergedJoinOperator = .optional + } + + return Join( + joinOperator: mergedJoinOperator, + joinCondition: joinCondition, + relation: mergedRelation) + } +} diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index e00dd886a..24d2d4875 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -312,205 +312,6 @@ extension SQLSelectQuery { } } -// MARK: - Join - -/// Not to be mismatched with SQL join operators (inner join, left join). -/// -/// JoinOperator is designed to be hierarchically nested, unlike -/// SQL join operators. -/// -/// Consider the following request for (A, B, C) tuples: -/// -/// let r = A.including(optional: A.b.including(required: B.c)) -/// -/// It chains three associations, the first optional, the second required. -/// -/// It looks like it means: "Give me all As, along with their Bs, granted those -/// Bs have their Cs. For As whose B has no C, give me a nil B". -/// -/// It can not be expressed as one left join, and a regular join, as below, -/// Because this would not honor the first optional: -/// -/// -- dubious -/// SELECT a.*, b.*, c.* -/// FROM a -/// LEFT JOIN b ON ... -/// JOIN c ON ... -/// -/// Instead, it should: -/// - allow (A + missing (B + C)) -/// - prevent (A + (B + missing C)). -/// -/// This can be expressed in SQL with two left joins, and an extra condition: -/// -/// -- likely correct -/// SELECT a.*, b.*, c.* -/// FROM a -/// LEFT JOIN b ON ... -/// LEFT JOIN c ON ... -/// WHERE NOT((b.id IS NOT NULL) AND (c.id IS NULL)) -- no B without C -/// -/// This is currently not implemented, and requires a little more thought. -/// I don't even know if inventing a whole new way to perform joins should even -/// be on the table. But we have a hierarchical way to express joined queries, -/// and they have a meaning: -/// -/// // what is my meaning? -/// A.including(optional: A.b.including(required: B.c)) -/// -/// :nodoc: -public /* TODO: internal */ enum JoinOperator { - case required, optional -} - -/// The condition that links two joined tables. -/// -/// Currently, we only support one kind of join condition: foreign keys. -/// -/// SELECT ... FROM book JOIN author ON author.id = book.authorId -/// <- the join condition --> -/// -/// When we eventually add support for new ways to join tables, JoinCondition -/// is the type we'll need to update. -/// -/// JoinCondition equality allows merging of associations: -/// -/// // request1 and request2 are equivalent -/// let request1 = Book -/// .including(required: Book.author) -/// let request2 = Book -/// .including(required: Book.author) -/// .including(required: Book.author) -/// -/// // request3 and request4 are equivalent -/// let request3 = Book -/// .including(required: Book.author.filter(condition1 && condition2)) -/// let request4 = Book -/// .joining(required: Book.author.filter(condition1)) -/// .including(optional: Book.author.filter(condition2)) -/// -/// :nodoc: -public /* TODO: internal */ struct JoinCondition: Equatable { - /// Definition of a foreign key - var foreignKeyRequest: ForeignKeyRequest - - /// True if the table at the origin of the foreign key is on the left of - /// the sql JOIN operator. - /// - /// Let's consider the `book.authorId -> author.id` foreign key. - /// Its origin table is `book`. - /// - /// The origin table `book` is on the left of the JOIN operator for - /// the BelongsTo association: - /// - /// -- Book.including(required: Book.author) - /// SELECT ... FROM book JOIN author ON author.id = book.authorId - /// - /// The origin table `book`is on the right of the JOIN operator for - /// the HasMany and HasOne associations: - /// - /// -- Author.including(required: Author.books) - /// SELECT ... FROM author JOIN book ON author.id = book.authorId - var originIsLeft: Bool - - /// Returns an SQL expression for the join condition. - /// - /// SELECT ... FROM book JOIN author ON author.id = book.authorId - /// <- the SQL expression --> - /// - /// - parameter db: A database connection. - /// - parameter leftAlias: A TableAlias for the table on the left of the - /// JOIN operator. - /// - parameter rightAlias: A TableAlias for the table on the right of the - /// JOIN operator. - /// - Returns: An SQL expression. - func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression { - let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping - let columnMapping: [(left: Column, right: Column)] - if originIsLeft { - columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } - } else { - columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } - } - - return columnMapping - .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } - .joined(operator: .and) - } -} - -struct Join { - var joinOperator: JoinOperator - var joinCondition: JoinCondition - var relation: SQLRelation - - var finalizedJoin: Join { - var join = self - join.relation = relation.finalizedRelation - return join - } - - /// - precondition: relation is the result of finalizedRelation - func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { - var isRequiredAllowed = isRequiredAllowed - var sql = "" - switch joinOperator { - case .optional: - isRequiredAllowed = false - sql += "LEFT JOIN" - case .required: - guard isRequiredAllowed else { - // TODO: chainOptionalRequired - fatalError("Not implemented: chaining a required association behind an optional association") - } - sql += "JOIN" - } - - sql += try " " + relation.source.sourceSQL(db, &context) - - let rightAlias = relation.alias! - let filters = try [ - joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), - relation.filterPromise.resolve(db) - ].compactMap { $0 } - if !filters.isEmpty { - sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) - } - - for (_, join) in relation.joins { - sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) - } - - return sql - } - - /// Returns nil if joins can't be merged (conflict in condition, relation...) - func merged(with other: Join) -> Join? { - guard joinCondition == other.joinCondition else { - // can't merge - return nil - } - - guard let mergedRelation = relation.merged(with: other.relation) else { - // can't merge - return nil - } - - let mergedJoinOperator: JoinOperator - switch (joinOperator, other.joinOperator) { - case (.required, _), (_, .required): - mergedJoinOperator = .required - default: - mergedJoinOperator = .optional - } - - return Join( - joinOperator: mergedJoinOperator, - joinCondition: joinCondition, - relation: mergedRelation) - } -} - struct SQLLimit { let limit: Int let offset: Int? @@ -525,7 +326,7 @@ struct SQLLimit { } extension SQLCount { - var sqlSelectable: SQLSelectable { + fileprivate var sqlSelectable: SQLSelectable { switch self { case .all: return SQLExpressionCount(AllColumns()) From 73782d5e9d00401fe7a21c33513578ee0c382212 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 10:23:34 +0100 Subject: [PATCH 23/26] BelongsTo, HasOne and HasMany share the same JoinAssociationImpl --- .../Association/Association.swift | 115 ++++++++++++------ .../Association/BelongsToAssociation.swift | 33 +---- .../Association/HasManyAssociation.swift | 33 +---- .../Association/HasOneAssociation.swift | 33 +---- 4 files changed, 84 insertions(+), 130 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 69815ffa3..3a95ad8e4 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -43,46 +43,6 @@ public protocol Association: DerivableRequest { init(_impl: Impl) } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// The protocol for implementation details of associations. -/// -/// :nodoc: -public /* TODO: internal */ protocol AssociationImpl { - /// The association key - var key: String { get } - - /// Creates an association with the given key. - func forKey(_ key: String) -> Self - - /// Returns an association whose relation is transformed by the - /// given closure. - /// - /// This method provides fundamental support for association derivation: - /// - /// // Invokes Book.author.mapRelation { $0.filter(...) } - /// Book.author.filter(...) - func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self - - /// Returns a relation joined with self. - /// - /// This method provides fundamental support for joining methods. - func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation - - // TODO: remove relation & joinCondition properties. - // - // They assume that an association is implemented as a direct join to an - // associated table. This is limiting: has-one-through and has-many-through - // associations can't be implemented in such context. - // - // Their impact is limited yet. Those propertise are currently only used by - // Association.request(from:). When this method gets a new implementation - // that does not need a direct join to an associated table, we'll be able to - // remove those properties. - var relation: SQLRelation { get } - var joinCondition: JoinCondition { get } -} - extension Association { private func mapImpl(_ transform: (Impl) throws -> Impl) rethrows -> Self { return try Self.init(_impl: transform(_impl)) @@ -371,3 +331,78 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { .aliased(associationAlias) } } + +// MARK: - AssociationImpl + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The protocol for implementation details of associations. +/// +/// :nodoc: +public /* TODO: internal */ protocol AssociationImpl { + /// The association key + var key: String { get } + + /// Creates an association with the given key. + func forKey(_ key: String) -> Self + + /// Returns an association whose relation is transformed by the + /// given closure. + /// + /// This method provides fundamental support for association derivation: + /// + /// // Invokes Book.author.mapRelation { $0.filter(...) } + /// Book.author.filter(...) + func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self + + /// Returns a relation joined with self. + /// + /// This method provides fundamental support for joining methods. + func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation + + // TODO: remove relation & joinCondition properties. + // + // They assume that an association is implemented as a direct join to an + // associated table. This is limiting: has-one-through and has-many-through + // associations can't be implemented in such context. + // + // Their impact is limited yet. Those propertise are currently only used by + // Association.request(from:). When this method gets a new implementation + // that does not need a direct join to an associated table, we'll be able to + // remove those properties. + var relation: SQLRelation { get } + var joinCondition: JoinCondition { get } +} + +// MARK: - + +/// The AssociationImpl shared by BelongsTo, HasOne, and HasMany, which is +/// implemented as a simple join. +/// +/// :nodoc: +public /* TODO: internal */ struct JoinAssociationImpl: AssociationImpl { + public var key: String + public /* TODO: internal */ let joinCondition: JoinCondition + public /* TODO: internal */ var relation: SQLRelation + + public func forKey(_ key: String) -> JoinAssociationImpl { + var assoc = self + assoc.key = key + return assoc + } + + public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> JoinAssociationImpl { + var assoc = self + assoc.relation = transform(relation) + return assoc + } + + public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { + let join = Join( + joinOperator: joinOperator, + joinCondition: joinCondition, + relation: self.relation) + return relation.appendingJoin(join, forKey: key) + } +} + diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 3c7269368..32c9f390a 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -66,41 +66,14 @@ public struct BelongsToAssociation: Association { public typealias RowDecoder = Destination /// :nodoc: - public var _impl: BelongsToAssociationImpl + public var _impl: JoinAssociationImpl /// :nodoc: - public init(_impl: BelongsToAssociationImpl) { + public init(_impl: JoinAssociationImpl) { self._impl = _impl } } -/// :nodoc: -public /* TODO: internal */ struct BelongsToAssociationImpl: AssociationImpl { - public var key: String - public let joinCondition: JoinCondition - public var relation: SQLRelation - - public func forKey(_ key: String) -> BelongsToAssociationImpl { - var assoc = self - assoc.key = key - return assoc - } - - public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> BelongsToAssociationImpl { - var assoc = self - assoc.relation = transform(relation) - return assoc - } - - public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { - let join = Join( - joinOperator: joinOperator, - joinCondition: joinCondition, - relation: self.relation) - return relation.appendingJoin(join, forKey: key) - } -} - // Allow BelongsToAssociation(...).filter(key: ...) extension BelongsToAssociation: TableRequest where Destination: TableRecord { /// :nodoc: @@ -180,7 +153,7 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: true) - return BelongsToAssociation(_impl: BelongsToAssociationImpl( + return BelongsToAssociation(_impl: JoinAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, relation: Destination.all().relation)) diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index f2a1d47b8..5f0994e07 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -66,41 +66,14 @@ public struct HasManyAssociation: Association { public typealias RowDecoder = Destination /// :nodoc: - public var _impl: HasManyAssociationImpl + public var _impl: JoinAssociationImpl /// :nodoc: - public init(_impl: HasManyAssociationImpl) { + public init(_impl: JoinAssociationImpl) { self._impl = _impl } } -/// :nodoc: -public /* TODO: internal */ struct HasManyAssociationImpl: AssociationImpl { - public var key: String - public let joinCondition: JoinCondition - public var relation: SQLRelation - - public func forKey(_ key: String) -> HasManyAssociationImpl { - var assoc = self - assoc.key = key - return assoc - } - - public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> HasManyAssociationImpl { - var assoc = self - assoc.relation = transform(relation) - return assoc - } - - public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { - let join = Join( - joinOperator: joinOperator, - joinCondition: joinCondition, - relation: self.relation) - return relation.appendingJoin(join, forKey: key) - } -} - // Allow HasManyAssociation(...).filter(key: ...) extension HasManyAssociation: TableRequest where Destination: TableRecord { /// :nodoc: @@ -269,7 +242,7 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasManyAssociation(_impl: HasManyAssociationImpl( + return HasManyAssociation(_impl: JoinAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, relation: Destination.all().relation)) diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 358b86de5..61779de5f 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -68,41 +68,14 @@ public struct HasOneAssociation: Association { public typealias RowDecoder = Destination /// :nodoc: - public var _impl: HasOneAssociationImpl + public var _impl: JoinAssociationImpl /// :nodoc: - public init(_impl: HasOneAssociationImpl) { + public init(_impl: JoinAssociationImpl) { self._impl = _impl } } -/// :nodoc: -public /* TODO: internal */ struct HasOneAssociationImpl: AssociationImpl { - public var key: String - public let joinCondition: JoinCondition - public var relation: SQLRelation - - public func forKey(_ key: String) -> HasOneAssociationImpl { - var assoc = self - assoc.key = key - return assoc - } - - public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> HasOneAssociationImpl { - var assoc = self - assoc.relation = transform(relation) - return assoc - } - - public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { - let join = Join( - joinOperator: joinOperator, - joinCondition: joinCondition, - relation: self.relation) - return relation.appendingJoin(join, forKey: key) - } -} - // Allow HasOneAssociation(...).filter(key: ...) extension HasOneAssociation: TableRequest where Destination: TableRecord { /// :nodoc: @@ -182,7 +155,7 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasOneAssociation(_impl: HasOneAssociationImpl( + return HasOneAssociation(_impl: JoinAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, relation: Destination.all().relation)) From c776801c4a538f4bc017bc764f78beefd8ef262c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 11:58:16 +0100 Subject: [PATCH 24/26] Document "merging" and "finalization" --- .../QueryInterface/SQLGenerationContext.swift | 2 +- GRDB/QueryInterface/SQLRelation.swift | 302 ++++++++++-------- GRDB/QueryInterface/SQLSelectQuery.swift | 4 - 3 files changed, 164 insertions(+), 144 deletions(-) diff --git a/GRDB/QueryInterface/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGenerationContext.swift index 95dfd274a..7a98561dd 100644 --- a/GRDB/QueryInterface/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGenerationContext.swift @@ -201,7 +201,7 @@ public class TableAlias: Hashable { } /// Returns nil if aliases can't be merged (conflict in tables, aliases...) - func merge(with other: TableAlias) -> TableAlias? { + func merged(with other: TableAlias) -> TableAlias? { let root = self.root let otherRoot = other.root switch (root.impl, otherRoot.impl) { diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index f8172f3c5..9b347cb2d 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -95,118 +95,6 @@ extension SQLRelation { } } -extension SQLRelation { - /// A finalized relation is ready for SQL generation - var finalizedRelation: SQLRelation { - var relation = self - - let alias = TableAlias() - relation.source = source.qualified(with: alias) - relation.selection = selection.map { $0.qualifiedSelectable(with: alias) } - relation.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } - relation.ordering = ordering.qualified(with: alias) - relation.joins = joins.mapValues { $0.finalizedJoin } - - return relation - } - - /// - precondition: self is the result of finalizedRelation - var finalizedAliases: [TableAlias] { - var aliases: [TableAlias] = [] - if let alias = alias { - aliases.append(alias) - } - return joins.reduce(into: aliases) { - $0.append(contentsOf: $1.value.relation.finalizedAliases) - } - } - - /// - precondition: self is the result of finalizedRelation - var finalizedSelection: [SQLSelectable] { - return joins.reduce(into: selection) { - $0.append(contentsOf: $1.value.relation.finalizedSelection) - } - } - - /// - precondition: self is the result of finalizedRelation - var finalizedOrdering: SQLRelation.Ordering { - return joins.reduce(ordering) { - $0.appending($1.value.relation.finalizedOrdering) - } - } - - /// - precondition: self is the result of finalizedRelation - func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { - let selectionWidth = try selection - .map { try $0.columnCount(db) } - .reduce(0, +) - - var endIndex = startIndex + selectionWidth - var scopes: [String: RowAdapter] = [:] - for (key, join) in joins { - if let (joinAdapter, joinEndIndex) = try join.relation.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { - scopes[key] = joinAdapter - endIndex = joinEndIndex - } - } - - if selectionWidth == 0 && scopes.isEmpty { - return nil - } - - let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) - return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) - } -} - -extension SQLRelation { - /// Returns nil if queries can't be merged (conflict in source, joins...) - func merged(with other: SQLRelation) -> SQLRelation? { - guard let mergedSource = source.merged(with: other.source) else { - // can't merge - return nil - } - - let mergedFilterPromise = filterPromise.map { (db, expression) -> SQLExpression? in - let otherExpression = try other.filterPromise.resolve(db) - let expressions = [expression, otherExpression].compactMap { $0 } - if expressions.isEmpty { - return nil - } - return expressions.joined(operator: .and) - } - - var mergedJoins: OrderedDictionary = [:] - for (key, join) in joins { - if let otherJoin = other.joins[key] { - guard let mergedJoin = join.merged(with: otherJoin) else { - // can't merge - return nil - } - mergedJoins.append(value: mergedJoin, forKey: key) - } else { - mergedJoins.append(value: join, forKey: key) - } - } - for (key, join) in other.joins where mergedJoins[key] == nil { - mergedJoins.append(value: join, forKey: key) - } - - // replace selection unless empty - let mergedSelection = other.selection.isEmpty ? selection : other.selection - - // replace ordering unless empty - let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering - - return SQLRelation( - source: mergedSource, - selection: mergedSelection, - filterPromise: mergedFilterPromise, - ordering: mergedOrdering, - joins: mergedJoins) - } -} - // MARK: - SQLRelation.Source extension SQLRelation { @@ -250,32 +138,6 @@ extension SQLRelation { return .query(query.qualified(with: alias)) } } - - /// Returns nil if sources can't be merged (conflict in tables, aliases...) - func merged(with other: Source) -> Source? { - switch (self, other) { - case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)): - guard tableName == otherTableName else { - // can't merge - return nil - } - switch (alias, otherAlias) { - case (nil, nil): - return .table(tableName: tableName, alias: nil) - case let (alias?, nil), let (nil, alias?): - return .table(tableName: tableName, alias: alias) - case let (alias?, otherAlias?): - guard let mergedAlias = alias.merge(with: otherAlias) else { - // can't merge - return nil - } - return .table(tableName: tableName, alias: mergedAlias) - } - default: - // can't merge - return nil - } - } } } @@ -539,7 +401,100 @@ struct Join { return sql } - +} + +// MARK: - Merging +// +// "Merging" is an operation that takes two relations and, if they are +// compatible, gathers them into a merged relation. +// +// It is an important feature that allows the user to define associated requests +// in several steps. For example, in the sample code below, both requests are +// equivalent and generate the same SQL query, thanks to merging: +// +// let request1 = Book.including(required: Book.author) +// +// let request2 = Book +// .including(required: Book.author) +// .including(required: Book.author) + +extension SQLRelation { + /// Returns nil if relations can't be merged (conflict in source, joins...) + func merged(with other: SQLRelation) -> SQLRelation? { + guard let mergedSource = source.merged(with: other.source) else { + // can't merge + return nil + } + + let mergedFilterPromise = filterPromise.map { (db, expression) -> SQLExpression? in + let otherExpression = try other.filterPromise.resolve(db) + let expressions = [expression, otherExpression].compactMap { $0 } + if expressions.isEmpty { + return nil + } + return expressions.joined(operator: .and) + } + + var mergedJoins: OrderedDictionary = [:] + for (key, join) in joins { + if let otherJoin = other.joins[key] { + guard let mergedJoin = join.merged(with: otherJoin) else { + // can't merge + return nil + } + mergedJoins.append(value: mergedJoin, forKey: key) + } else { + mergedJoins.append(value: join, forKey: key) + } + } + for (key, join) in other.joins where mergedJoins[key] == nil { + mergedJoins.append(value: join, forKey: key) + } + + // replace selection unless empty + let mergedSelection = other.selection.isEmpty ? selection : other.selection + + // replace ordering unless empty + let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering + + return SQLRelation( + source: mergedSource, + selection: mergedSelection, + filterPromise: mergedFilterPromise, + ordering: mergedOrdering, + joins: mergedJoins) + } +} + +extension SQLRelation.Source { + /// Returns nil if sources can't be merged (conflict in tables, aliases...) + func merged(with other: SQLRelation.Source) -> SQLRelation.Source? { + switch (self, other) { + case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)): + guard tableName == otherTableName else { + // can't merge + return nil + } + switch (alias, otherAlias) { + case (nil, nil): + return .table(tableName: tableName, alias: nil) + case let (alias?, nil), let (nil, alias?): + return .table(tableName: tableName, alias: alias) + case let (alias?, otherAlias?): + guard let mergedAlias = alias.merged(with: otherAlias) else { + // can't merge + return nil + } + return .table(tableName: tableName, alias: mergedAlias) + } + default: + // can't merge + return nil + } + } +} + +extension Join { /// Returns nil if joins can't be merged (conflict in condition, relation...) func merged(with other: Join) -> Join? { guard joinCondition == other.joinCondition else { @@ -566,3 +521,72 @@ struct Join { relation: mergedRelation) } } + +// MARK: - Finalization +// +// "Finalization" is the operation which gathers all information required +// for SQL generation. + +extension SQLRelation { + /// A finalized relation is ready for SQL generation + var finalizedRelation: SQLRelation { + var relation = self + + let alias = TableAlias() + relation.source = source.qualified(with: alias) + relation.selection = selection.map { $0.qualifiedSelectable(with: alias) } + relation.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + relation.ordering = ordering.qualified(with: alias) + relation.joins = joins.mapValues { $0.finalizedJoin } + + return relation + } + + /// - precondition: self is the result of finalizedRelation + var finalizedAliases: [TableAlias] { + var aliases: [TableAlias] = [] + if let alias = alias { + aliases.append(alias) + } + return joins.reduce(into: aliases) { + $0.append(contentsOf: $1.value.relation.finalizedAliases) + } + } + + /// - precondition: self is the result of finalizedRelation + var finalizedSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.value.relation.finalizedSelection) + } + } + + /// - precondition: self is the result of finalizedRelation + var finalizedOrdering: SQLRelation.Ordering { + return joins.reduce(ordering) { + $0.appending($1.value.relation.finalizedOrdering) + } + } + + /// - precondition: self is the result of finalizedRelation + func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + let selectionWidth = try selection + .map { try $0.columnCount(db) } + .reduce(0, +) + + var endIndex = startIndex + selectionWidth + var scopes: [String: RowAdapter] = [:] + for (key, join) in joins { + if let (joinAdapter, joinEndIndex) = try join.relation.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { + scopes[key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) + return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) + } +} diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index 24d2d4875..1247d8130 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -78,10 +78,6 @@ extension SQLSelectQuery: SelectionRequest, FilteredRequest, OrderedRequest { return query } - func appendingJoin(_ join: Join, forKey key: String) -> SQLSelectQuery { - return mapRelation { $0.appendingJoin(join, forKey: key) } - } - func qualified(with alias: TableAlias) -> SQLSelectQuery { return mapRelation { $0.qualified(with: alias) } } From e924587236f717326f0d83c37f1f60f325e2eb7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 14:31:59 +0100 Subject: [PATCH 25/26] Extract generation of SQL SELECT queries into SQLSelectQueryGenerator --- GRDB.xcodeproj/project.pbxproj | 8 + .../Association/Association.swift | 2 +- .../QueryInterfaceRequest.swift | 6 +- GRDB/QueryInterface/SQLRelation.swift | 198 ++-------- GRDB/QueryInterface/SQLSelectQuery.swift | 194 +--------- .../SQLSelectQueryGenerator.swift | 342 ++++++++++++++++++ GRDBCipher.xcodeproj/project.pbxproj | 6 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../QueryInterfaceRequestTests.swift | 9 + 9 files changed, 423 insertions(+), 348 deletions(-) create mode 100644 GRDB/QueryInterface/SQLSelectQueryGenerator.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b5fe20bb8..e06acb792 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -446,6 +446,9 @@ 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BF21F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; + 568D131F2207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13202207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13212207213F00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */; }; 5690AFD82120589A001530EA /* InsertRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */; }; 5690AFD92120589A001530EA /* InsertRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */; }; 5690AFDB212058CB001530EA /* FetchRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */; }; @@ -1074,6 +1077,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; + 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQueryGenerator.swift; sourceTree = ""; }; 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordCodableTests.swift; sourceTree = ""; }; 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordCodableTests.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1537,6 +1541,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.swift */, + 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -2564,6 +2569,7 @@ 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, + 568D13212207213F00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 565490C61D5AE236005622CB /* Statement.swift in Sources */, @@ -2651,6 +2657,7 @@ 56CEB51C1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 5698AC3A1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, + 568D13202207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, @@ -3196,6 +3203,7 @@ 56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, + 568D131F2207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D361DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 3a95ad8e4..d38f4cdcb 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -398,7 +398,7 @@ public /* TODO: internal */ struct JoinAssociationImpl: AssociationImpl { } public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { - let join = Join( + let join = SQLJoin( joinOperator: joinOperator, joinCondition: joinCondition, relation: self.relation) diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index d41bdf733..5d155f840 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -34,7 +34,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - returns: A prepared statement and an eventual row adapter. /// :nodoc: public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try query.finalizedQuery.prepare(db) + return try SQLSelectQueryGenerator(query).prepare(db) } /// Returns the number of rows fetched by the request. @@ -50,7 +50,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - parameter db: A database connection. /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - return try query.finalizedQuery.databaseRegion(db) + return try SQLSelectQueryGenerator(query).databaseRegion(db) } } @@ -290,7 +290,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @discardableResult public func deleteAll(_ db: Database) throws -> Int { - try query.makeDeleteStatement(db).execute() + try SQLSelectQueryGenerator(query).makeDeleteStatement(db).execute() return db.changesCount } } diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 9b347cb2d..269310d13 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -6,22 +6,22 @@ /// /// :nodoc: public /* TODO: internal */ struct SQLRelation { - var source: SQLRelation.Source + var source: SQLSource var selection: [SQLSelectable] var filterPromise: DatabasePromise var ordering: SQLRelation.Ordering - var joins: OrderedDictionary + var joins: OrderedDictionary var alias: TableAlias? { return source.alias } init( - source: SQLRelation.Source, + source: SQLSource, selection: [SQLSelectable] = [], filterPromise: DatabasePromise = DatabasePromise(value: nil), ordering: SQLRelation.Ordering = SQLRelation.Ordering(), - joins: OrderedDictionary = [:]) + joins: OrderedDictionary = [:]) { self.source = source self.selection = selection @@ -74,7 +74,7 @@ extension SQLRelation { return order(SQLRelation.Ordering()) } - func appendingJoin(_ join: Join, forKey key: String) -> SQLRelation { + func appendingJoin(_ join: SQLJoin, forKey key: String) -> SQLRelation { var relation = self if let existingJoin = relation.joins.removeValue(forKey: key) { guard let mergedJoin = existingJoin.merged(with: join) else { @@ -95,48 +95,33 @@ extension SQLRelation { } } -// MARK: - SQLRelation.Source +// MARK: - SQLSource -extension SQLRelation { - enum Source { - case table(tableName: String, alias: TableAlias?) - indirect case query(SQLSelectQuery) - - var alias: TableAlias? { - switch self { - case .table(_, let alias): - return alias - case .query(let query): - return query.alias - } +enum SQLSource { + case table(tableName: String, alias: TableAlias?) + indirect case query(SQLSelectQuery) + + var alias: TableAlias? { + switch self { + case .table(_, let alias): + return alias + case .query(let query): + return query.alias } - - func sourceSQL(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { - switch self { - case .table(let tableName, let alias): - if let alias = alias, let aliasName = context.aliasName(for: alias) { - return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" - } else { - return "\(tableName.quotedDatabaseIdentifier)" - } - case .query(let query): - return try "(\(query.sql(db, &context)))" - } - } - - func qualified(with alias: TableAlias) -> Source { - switch self { - case .table(let tableName, let sourceAlias): - if let sourceAlias = sourceAlias { - alias.becomeProxy(of: sourceAlias) - return self - } else { - alias.setTableName(tableName) - return .table(tableName: tableName, alias: alias) - } - case .query(let query): - return .query(query.qualified(with: alias)) + } + + func qualified(with alias: TableAlias) -> SQLSource { + switch self { + case .table(let tableName, let sourceAlias): + if let sourceAlias = sourceAlias { + alias.becomeProxy(of: sourceAlias) + return self + } else { + alias.setTableName(tableName) + return .table(tableName: tableName, alias: alias) } + case .query(let query): + return .query(query.qualified(with: alias)) } } } @@ -230,7 +215,7 @@ extension SQLRelation { } } -// MARK: - Join +// MARK: - SQLJoin /// Not to be mismatched with SQL join operators (inner join, left join). /// @@ -357,50 +342,10 @@ public /* TODO: internal */ struct JoinCondition: Equatable { } } -struct Join { +struct SQLJoin { var joinOperator: JoinOperator var joinCondition: JoinCondition var relation: SQLRelation - - var finalizedJoin: Join { - var join = self - join.relation = relation.finalizedRelation - return join - } - - /// - precondition: relation is the result of finalizedRelation - func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { - var isRequiredAllowed = isRequiredAllowed - var sql = "" - switch joinOperator { - case .optional: - isRequiredAllowed = false - sql += "LEFT JOIN" - case .required: - guard isRequiredAllowed else { - // TODO: chainOptionalRequired - fatalError("Not implemented: chaining a required association behind an optional association") - } - sql += "JOIN" - } - - sql += try " " + relation.source.sourceSQL(db, &context) - - let rightAlias = relation.alias! - let filters = try [ - joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), - relation.filterPromise.resolve(db) - ].compactMap { $0 } - if !filters.isEmpty { - sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) - } - - for (_, join) in relation.joins { - sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) - } - - return sql - } } // MARK: - Merging @@ -435,7 +380,7 @@ extension SQLRelation { return expressions.joined(operator: .and) } - var mergedJoins: OrderedDictionary = [:] + var mergedJoins: OrderedDictionary = [:] for (key, join) in joins { if let otherJoin = other.joins[key] { guard let mergedJoin = join.merged(with: otherJoin) else { @@ -466,9 +411,9 @@ extension SQLRelation { } } -extension SQLRelation.Source { +extension SQLSource { /// Returns nil if sources can't be merged (conflict in tables, aliases...) - func merged(with other: SQLRelation.Source) -> SQLRelation.Source? { + func merged(with other: SQLSource) -> SQLSource? { switch (self, other) { case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)): guard tableName == otherTableName else { @@ -494,9 +439,9 @@ extension SQLRelation.Source { } } -extension Join { +extension SQLJoin { /// Returns nil if joins can't be merged (conflict in condition, relation...) - func merged(with other: Join) -> Join? { + func merged(with other: SQLJoin) -> SQLJoin? { guard joinCondition == other.joinCondition else { // can't merge return nil @@ -515,78 +460,9 @@ extension Join { mergedJoinOperator = .optional } - return Join( + return SQLJoin( joinOperator: mergedJoinOperator, joinCondition: joinCondition, relation: mergedRelation) } } - -// MARK: - Finalization -// -// "Finalization" is the operation which gathers all information required -// for SQL generation. - -extension SQLRelation { - /// A finalized relation is ready for SQL generation - var finalizedRelation: SQLRelation { - var relation = self - - let alias = TableAlias() - relation.source = source.qualified(with: alias) - relation.selection = selection.map { $0.qualifiedSelectable(with: alias) } - relation.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } - relation.ordering = ordering.qualified(with: alias) - relation.joins = joins.mapValues { $0.finalizedJoin } - - return relation - } - - /// - precondition: self is the result of finalizedRelation - var finalizedAliases: [TableAlias] { - var aliases: [TableAlias] = [] - if let alias = alias { - aliases.append(alias) - } - return joins.reduce(into: aliases) { - $0.append(contentsOf: $1.value.relation.finalizedAliases) - } - } - - /// - precondition: self is the result of finalizedRelation - var finalizedSelection: [SQLSelectable] { - return joins.reduce(into: selection) { - $0.append(contentsOf: $1.value.relation.finalizedSelection) - } - } - - /// - precondition: self is the result of finalizedRelation - var finalizedOrdering: SQLRelation.Ordering { - return joins.reduce(ordering) { - $0.appending($1.value.relation.finalizedOrdering) - } - } - - /// - precondition: self is the result of finalizedRelation - func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { - let selectionWidth = try selection - .map { try $0.columnCount(db) } - .reduce(0, +) - - var endIndex = startIndex + selectionWidth - var scopes: [String: RowAdapter] = [:] - for (key, join) in joins { - if let (joinAdapter, joinEndIndex) = try join.relation.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { - scopes[key] = joinAdapter - endIndex = joinEndIndex - } - } - - if selectionWidth == 0 && scopes.isEmpty { - return nil - } - - let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) - return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) - } -} diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index 1247d8130..15e62f6b0 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -1,4 +1,6 @@ -/// SQLSelectQuery generates SQL for query interface requests. +/// SQLSelectQuery is a representation of an SQL SELECT query. +/// +/// See SQLSelectQueryGenerator for actual SQL generation. struct SQLSelectQuery { var relation: SQLRelation var isDistinct: Bool @@ -91,180 +93,11 @@ extension SQLSelectQuery: SelectionRequest, FilteredRequest, OrderedRequest { } extension SQLSelectQuery { - /// A finalized query is ready for SQL generation - var finalizedQuery: SQLSelectQuery { - var query = self - - query.relation = query.relation.finalizedRelation - let alias = query.relation.alias! - query.groupPromise = query.groupPromise?.map { [alias] (_, exprs) in exprs.map { $0.qualifiedExpression(with: alias) } } - query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias) - - return query - } - - /// - precondition: self is the result of finalizedQuery - private func finalizedRowAdapter(_ db: Database) throws -> RowAdapter? { - // No join => no adapter - if relation.joins.isEmpty { - return nil - } - - guard let (adapter, _) = try relation.finalizedRowAdapter(db, fromIndex: 0, forKeyPath: []) else { - return nil - } - - return adapter - } -} - -extension SQLSelectQuery { - /// - precondition: self is the result of finalizedQuery - func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { - var sql = "SELECT" - - if isDistinct { - sql += " DISTINCT" - } - - let selection = relation.finalizedSelection - GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") - sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - - sql += try " FROM " + relation.source.sourceSQL(db, &context) - - for (_, join) in relation.joins { - sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true) - } - - if let filter = try relation.filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&context) - } - - if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { - sql += " GROUP BY " - sql += groupExpressions.map { $0.expressionSQL(&context) } - .joined(separator: ", ") - } - - if let havingExpression = havingExpression { - sql += " HAVING " + havingExpression.expressionSQL(&context) - } - - let orderings = try relation.finalizedOrdering.resolve(db) - if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") - } - - if let limit = limit { - sql += " LIMIT " + limit.sql - } - - return sql - } - - /// - precondition: self is the result of finalizedQuery - private func makeSelectStatement(_ db: Database) throws -> SelectStatement { - var context = SQLGenerationContext.queryGenerationContext(aliases: relation.finalizedAliases) - let sql = try self.sql(db, &context) - let statement = try db.makeSelectStatement(sql) - statement.arguments = context.arguments! - return statement - } - - /// - precondition: self is the result of finalizedQuery - func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { - if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { - // Programmer error - fatalError("Can't delete query with GROUP BY clause") - } - - guard havingExpression == nil else { - // Programmer error - fatalError("Can't delete query with HAVING clause") - } - - guard relation.joins.isEmpty else { - // Programmer error - fatalError("Can't delete query with JOIN clause") - } - - guard case .table = relation.source else { - // Programmer error - fatalError("Can't delete without any database table") - } - - var context = SQLGenerationContext.queryGenerationContext(aliases: relation.finalizedAliases) - - var sql = try "DELETE FROM " + relation.source.sourceSQL(db, &context) - - if let filter = try relation.filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&context) - } - - if let limit = limit { - let orderings = try relation.finalizedOrdering.resolve(db) - if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") - } - - if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { - sql += " LIMIT " + limit.sql - } else { - fatalError("Can't delete query with limit") - } - } - - let statement = try db.makeUpdateStatement(sql) - statement.arguments = context.arguments! - return statement - } - - /// - precondition: self is the result of finalizedQuery - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (makeSelectStatement(db), finalizedRowAdapter(db)) - } - func fetchCount(_ db: Database) throws -> Int { - let (statement, adapter) = try countQuery.prepare(db) + let (statement, adapter) = try SQLSelectQueryGenerator(countQuery).prepare(db) return try Int.fetchOne(statement, adapter: adapter)! } - /// The database region that the request looks into. - /// - precondition: self is the result of finalizedQuery - func databaseRegion(_ db: Database) throws -> DatabaseRegion { - let statement = try makeSelectStatement(db) - let databaseRegion = statement.databaseRegion - - // Can we intersect the region with rowIds? - // - // Give up unless request feeds from a single database table - guard case .table(tableName: let tableName, alias: _) = relation.source else { - // TODO: try harder - return databaseRegion - } - - // Give up unless primary key is rowId - let primaryKeyInfo = try db.primaryKey(tableName) - guard primaryKeyInfo.isRowID else { - return databaseRegion - } - - // Give up unless there is a where clause - guard let filter = try relation.filterPromise.resolve(db) else { - return databaseRegion - } - - // The filter knows better - guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { - return databaseRegion - } - - // Database regions are case-insensitive: use the canonical table name - let canonicalTableName = try db.canonicalTableName(tableName) - return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds) - } - private var countQuery: SQLSelectQuery { guard groupPromise == nil && limit == nil else { // SELECT ... GROUP BY ... @@ -282,8 +115,14 @@ extension SQLSelectQuery { guard let count = relation.selection[0].count(distinct: isDistinct) else { return trivialCountQuery } - var countQuery = self.unordered().select(count.sqlSelectable) + var countQuery = self.unordered() countQuery.isDistinct = false + switch count { + case .all: + countQuery = countQuery.select(SQLExpressionCount(AllColumns())) + case .distinct(let expression): + countQuery = countQuery.select(SQLExpressionCountDistinct(expression)) + } return countQuery } else { // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... @@ -320,14 +159,3 @@ struct SQLLimit { } } } - -extension SQLCount { - fileprivate var sqlSelectable: SQLSelectable { - switch self { - case .all: - return SQLExpressionCount(AllColumns()) - case .distinct(let expression): - return SQLExpressionCountDistinct(expression) - } - } -} diff --git a/GRDB/QueryInterface/SQLSelectQueryGenerator.swift b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift new file mode 100644 index 000000000..2947fb98f --- /dev/null +++ b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift @@ -0,0 +1,342 @@ +/// SQLSelectQueryGenerator is able to generate an SQL SELECT query. +struct SQLSelectQueryGenerator { + private let relation: SQLQualifiedRelation + private let isDistinct: Bool + private let groupPromise: DatabasePromise<[SQLExpression]>? + private let havingExpression: SQLExpression? + private let limit: SQLLimit? + + init(_ query: SQLSelectQuery) { + // 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, as in the example below: + // + // // SELECT book.*, person1.*, person2.*, COUNT(DISTINCT awards.id) + // // FROM book + // // LEFT JOIN person person1 WHERE person1.id = book.authorId + // // LEFT JOIN person person2 WHERE person2.id = book.translatorId + // // LEFT JOIN award WHERE award.bookId = book.id + // let request = Book + // .including(optional: Book.author) + // .including(optional: Book.translator) + // .annotated(with: Book.awards.count) + 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 alias = relation.alias + groupPromise = query.groupPromise?.map { [alias] (_, exprs) in exprs.map { $0.qualifiedExpression(with: alias) } } + havingExpression = query.havingExpression?.qualifiedExpression(with: alias) + + // Preserve other flags + isDistinct = query.isDistinct + limit = query.limit + } + + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { + var sql = "SELECT" + + if isDistinct { + sql += " DISTINCT" + } + + let selection = relation.fullSelection + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") + sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") + + sql += try " FROM " + relation.source.sql(db, &context) + + for (_, join) in relation.joins { + sql += try " " + join.sql(db, &context, leftAlias: relation.alias, isRequiredAllowed: true) + } + + if let filter = try relation.filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) + } + + if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { + sql += " GROUP BY " + sql += groupExpressions.map { $0.expressionSQL(&context) } + .joined(separator: ", ") + } + + if let havingExpression = havingExpression { + sql += " HAVING " + havingExpression.expressionSQL(&context) + } + + let orderings = try relation.ordering.resolve(db) + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + } + + if let limit = limit { + sql += " LIMIT " + limit.sql + } + + return sql + } + + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (makeSelectStatement(db), rowAdapter(db)) + } + + func databaseRegion(_ db: Database) throws -> DatabaseRegion { + let statement = try makeSelectStatement(db) + let databaseRegion = statement.databaseRegion + + // Can we intersect the region with rowIds? + // + // Give up unless request feeds from a single database table + guard case .table(tableName: let tableName, alias: _) = relation.source else { + // TODO: try harder + return databaseRegion + } + + // Give up unless primary key is rowId + let primaryKeyInfo = try db.primaryKey(tableName) + guard primaryKeyInfo.isRowID else { + return databaseRegion + } + + // Give up unless there is a where clause + guard let filter = try relation.filterPromise.resolve(db) else { + return databaseRegion + } + + // The filter knows better + guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + return databaseRegion + } + + // Database regions are case-insensitive: use the canonical table name + let canonicalTableName = try db.canonicalTableName(tableName) + return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds) + } + + func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { + if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { + // Programmer error + fatalError("Can't delete query with GROUP BY clause") + } + + guard havingExpression == nil else { + // Programmer error + fatalError("Can't delete query with HAVING clause") + } + + guard relation.joins.isEmpty else { + // Programmer error + fatalError("Can't delete query with JOIN clause") + } + + guard case .table = relation.source else { + // Programmer error + fatalError("Can't delete without any database table") + } + + var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + + var sql = try "DELETE FROM " + relation.source.sql(db, &context) + + if let filter = try relation.filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) + } + + if let limit = limit { + let orderings = try relation.ordering.resolve(db) + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + } + + if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { + sql += " LIMIT " + limit.sql + } else { + fatalError("Can't delete query with limit") + } + } + + let statement = try db.makeUpdateStatement(sql) + statement.arguments = context.arguments! + return statement + } + + private func makeSelectStatement(_ db: Database) throws -> SelectStatement { + var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + let statement = try db.makeSelectStatement(sql(db, &context)) + statement.arguments = context.arguments! + return statement + } + + private func rowAdapter(_ db: Database) throws -> RowAdapter? { + return try relation.rowAdapter(db, fromIndex: 0, forKeyPath: [])?.adapter + } +} + +/// A "qualified" relation, where all tables are identified with a table alias. +private struct SQLQualifiedRelation { + /// The alias for the source + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ alias + let alias: TableAlias + + /// Own alias plus aliases of all joined relations + let allAliases: [TableAlias] + + /// The source + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ source + let source: SQLQualifiedSource + + /// The selection, not including selection of joined relations + private let ownSelection: [SQLSelectable] + + /// The full selection, including selection of joined relations + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ fullSelection + let fullSelection: [SQLSelectable] + + /// The filtering clause + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ filterPromise + let filterPromise: DatabasePromise + + /// The ordering + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ ordering + let ordering: SQLRelation.Ordering + + /// The joins + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ joins + let joins: OrderedDictionary + + init(_ relation: SQLRelation) { + let alias = TableAlias() + self.alias = alias + source = SQLQualifiedSource(relation.source.qualified(with: alias)) + joins = relation.joins.mapValues(SQLQualifiedJoin.init) + ownSelection = relation.selection.map { $0.qualifiedSelectable(with: alias) } + fullSelection = joins.reduce(into: ownSelection) { + $0.append(contentsOf: $1.value.relation.fullSelection) + } + filterPromise = relation.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + let ownOrdering = relation.ordering.qualified(with: alias) + ordering = joins.reduce(ownOrdering) { + $0.appending($1.value.relation.ordering) + } + allAliases = joins.reduce(into: [alias]) { + $0.append(contentsOf: $1.value.relation.allAliases) + } + } + + func rowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + if startIndex == 0 && joins.isEmpty { + // Root relation + no join => no adapter + return nil + } + + let selectionWidth = try ownSelection + .map { try $0.columnCount(db) } + .reduce(0, +) + + var endIndex = startIndex + selectionWidth + var scopes: [String: RowAdapter] = [:] + for (key, join) in joins { + if let (joinAdapter, joinEndIndex) = try join.relation.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { + scopes[key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) + return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) + } +} + +/// A "qualified" source, where all tables are identified with a table alias. +private enum SQLQualifiedSource { + case table(tableName: String, alias: TableAlias) + indirect case query(SQLSelectQueryGenerator) + + init(_ source: SQLSource) { + switch source { + case .table(let tableName, let sourceAlias): + self = .table(tableName: tableName, alias: sourceAlias ?? TableAlias()) + case .query(let query): + self = .query(SQLSelectQueryGenerator(query)) + } + } + + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { + switch self { + case .table(let tableName, let alias): + if let aliasName = context.aliasName(for: alias) { + return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" + } else { + return "\(tableName.quotedDatabaseIdentifier)" + } + case .query(let query): + return try "(\(query.sql(db, &context)))" + } + } +} + +/// A "qualified" join, where all tables are identified with a table alias. +private struct SQLQualifiedJoin { + private let joinOperator: JoinOperator + private let joinCondition: JoinCondition + let relation: SQLQualifiedRelation + + init(_ join: SQLJoin) { + self.joinOperator = join.joinOperator + self.joinCondition = join.joinCondition + self.relation = SQLQualifiedRelation(join.relation) + } + + func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { + var isRequiredAllowed = isRequiredAllowed + var sql = "" + switch joinOperator { + case .optional: + isRequiredAllowed = false + sql += "LEFT JOIN" + case .required: + guard isRequiredAllowed else { + // TODO: chainOptionalRequired + fatalError("Not implemented: chaining a required association behind an optional association") + } + sql += "JOIN" + } + + sql += try " " + relation.source.sql(db, &context) + + let rightAlias = relation.alias + let filters = try [ + joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), + relation.filterPromise.resolve(db) + ].compactMap { $0 } + if !filters.isEmpty { + sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) + } + + for (_, join) in relation.joins { + sql += try " " + join.sql(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) + } + + return sql + } +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 14f84c3ef..71a9ec433 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -590,6 +590,8 @@ 56873BED1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BF01F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 568BE5231CB0371D00270F93 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 560FC54D1CB003810014AA8E /* GRDBCipher.framework */; }; + 568D13242207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13252207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */; }; 568E1CB21CB037BA008D97A6 /* sqlite3.h in Headers */ = {isa = PBXBuildFile; fileRef = 568BE5191CB035A900270F93 /* sqlite3.h */; settings = {ATTRIBUTES = (Public, ); }; }; 568E1CB91CB03847008D97A6 /* GRDBCipher-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 568E1CB71CB03847008D97A6 /* GRDBCipher-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 568E1CBA1CB03847008D97A6 /* GRDBCipher.h in Headers */ = {isa = PBXBuildFile; fileRef = 568E1CB81CB03847008D97A6 /* GRDBCipher.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -1189,6 +1191,7 @@ 568BE5191CB035A900270F93 /* sqlite3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sqlite3.h; path = SQLCipher/src/sqlite3.h; sourceTree = ""; }; 568BE51F1CB0360500270F93 /* GRDBCipher.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBCipher.xcconfig; path = SQLCipher/GRDBCipher.xcconfig; sourceTree = ""; }; 568BE5201CB0360500270F93 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; name = module.modulemap; path = SQLCipher/module.modulemap; sourceTree = ""; }; + 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQueryGenerator.swift; sourceTree = ""; }; 568E1CB71CB03847008D97A6 /* GRDBCipher-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "GRDBCipher-Bridging.h"; path = "SQLCipher/GRDBCipher-Bridging.h"; sourceTree = ""; }; 568E1CB81CB03847008D97A6 /* GRDBCipher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GRDBCipher.h; path = SQLCipher/GRDBCipher.h; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1620,6 +1623,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */, + 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -2403,6 +2407,7 @@ 560FC5381CB003810014AA8E /* DatabaseDateComponents.swift in Sources */, 56BF6D371DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56193E961CD8A3E300F95862 /* FetchedRecordsController.swift in Sources */, + 568D13242207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56B964BA1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, @@ -2890,6 +2895,7 @@ 56AFCA0D1CB1A8BB00F48B96 /* DatabaseDateComponents.swift in Sources */, 56BF6D3A1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56AFCA0E1CB1A8BB00F48B96 /* DatabaseReader.swift in Sources */, + 568D13252207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56B964BD1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 77514725e..3fc2177d0 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -263,6 +263,8 @@ 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 56873BEE1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BF11F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; + 568D13152207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13162207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */; }; 5690C3291D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; 5690C32D1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; 5690C33A1D23E7D200E59934 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; }; @@ -820,6 +822,7 @@ 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; + 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelectQueryGenerator.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = ""; }; 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; @@ -1228,6 +1231,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */, + 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -2040,6 +2044,7 @@ F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, + 568D13162207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56BF6D3B1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, @@ -2347,6 +2352,7 @@ F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, + 568D13152207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56BF6D381DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 231b703ac..7eaa646d8 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -41,6 +41,15 @@ class QueryInterfaceRequestTests: GRDBTestCase { try migrator.migrate(dbWriter) } + // MARK: - Preparation + + func testSimpleRequestDoesNotUseAnyRowAdapter() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let (statement, adapter) = try Reader.all().prepare(db) + XCTAssertNil(adapter) + } + } // MARK: - Fetch rows From 699c63e913b7383798f740ca7255b68daad8e14f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Feb 2019 19:55:26 +0100 Subject: [PATCH 26/26] Explain how SQLSelectQueryGenerator uses RowAdapter --- .../SQLSelectQueryGenerator.swift | 157 ++++++++++++++---- .../AssociationBelongsToRowScopeTests.swift | 9 + .../QueryInterfaceRequestTests.swift | 2 +- 3 files changed, 133 insertions(+), 35 deletions(-) diff --git a/GRDB/QueryInterface/SQLSelectQueryGenerator.swift b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift index 2947fb98f..fe4f1c5c3 100644 --- a/GRDB/QueryInterface/SQLSelectQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift @@ -11,17 +11,23 @@ struct SQLSelectQueryGenerator { // expressions, etc, are identified with table aliases. // // All those aliases let us disambiguate tables at the SQL level, and - // prefix columns names, as in the example below: + // prefix columns names. For example, the following request... // - // // SELECT book.*, person1.*, person2.*, COUNT(DISTINCT awards.id) - // // FROM book - // // LEFT JOIN person person1 WHERE person1.id = book.authorId - // // LEFT JOIN person person2 WHERE person2.id = book.translatorId - // // LEFT JOIN award WHERE award.bookId = book.id - // let request = Book + // 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. @@ -44,7 +50,7 @@ struct SQLSelectQueryGenerator { sql += " DISTINCT" } - let selection = relation.fullSelection + let selection = relation.selection GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") @@ -164,28 +170,66 @@ struct SQLSelectQueryGenerator { return statement } + /// Returns a select statement private func makeSelectStatement(_ db: Database) throws -> SelectStatement { + // Build an SQK generation context with all aliases found in the query, + // so that we can disambiguate tables that are used several times with + // SQL aliases. var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) - let statement = try db.makeSelectStatement(sql(db, &context)) - statement.arguments = context.arguments! + + // Generate SQL + let sql = try self.sql(db, &context) + + // Compile & set arguments + let statement = try db.makeSelectStatement(sql) + statement.arguments = context.arguments! // not nil for this kind of context return statement } + /// Returns the row adapter which presents the fetched rows according to the + /// tree of joined relations. + /// + /// The adapter is nil for queries without any included relation, + /// because the fetched rows don't need any processing: + /// + /// // SELECT * FROM book + /// let request = Book.all() + /// for row in try Row.fetchAll(db, request) { + /// row // [id:1, title:"Moby-Dick"] + /// let book = Book(row: row) + /// } + /// + /// But as soon as the selection includes columns of a included relation, + /// we need an adapter: + /// + /// // SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorId + /// let request = Book.including(required: Book.author) + /// for row in try Row.fetchAll(db, request) { + /// row // [id:1, title:"Moby-Dick"] + /// let book = Book(row: row) + /// + /// row.scopes["author"] // [id:12, name:"Herman Melville"] + /// let author: Author = row["author"] + /// } private func rowAdapter(_ db: Database) throws -> RowAdapter? { - return try relation.rowAdapter(db, fromIndex: 0, forKeyPath: [])?.adapter + return try relation.rowAdapter(db, fromIndex: 0)?.adapter } } /// A "qualified" relation, where all tables are identified with a table alias. private struct SQLQualifiedRelation { - /// The alias for the source + /// The alias for the relation /// /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... /// ^ alias let alias: TableAlias - /// Own alias plus aliases of all joined relations - let allAliases: [TableAlias] + /// All aliases, including aliases of joined relations + var allAliases: [TableAlias] { + return joins.reduce(into: [alias]) { + $0.append(contentsOf: $1.value.relation.allAliases) + } + } /// The source /// @@ -200,7 +244,11 @@ private struct SQLQualifiedRelation { /// /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... /// ^ fullSelection - let fullSelection: [SQLSelectable] + var selection: [SQLSelectable] { + return joins.reduce(into: ownSelection) { + $0.append(contentsOf: $1.value.relation.selection) + } + } /// The filtering clause /// @@ -208,11 +256,18 @@ private struct SQLQualifiedRelation { /// ^ filterPromise let filterPromise: DatabasePromise - /// The ordering + /// The ordering, not including ordering of joined relations + private let ownOrdering: SQLRelation.Ordering + + /// The full ordering, including orderings of joined relations /// /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... - /// ^ ordering - let ordering: SQLRelation.Ordering + /// ^ ordering + var ordering: SQLRelation.Ordering { + return joins.reduce(ownOrdering) { + $0.appending($1.value.relation.ordering) + } + } /// The joins /// @@ -221,49 +276,83 @@ private struct SQLQualifiedRelation { let joins: OrderedDictionary init(_ relation: SQLRelation) { + // The alias that qualifies this relation let alias = TableAlias() self.alias = alias + + // Qualify the source, so that it be disambiguated with an SQL alias + // if needed (when a select query uses the same table several times). + // This disambiguation job will be actually performed by + // SQLGenerationContext, when the SQLSelectQueryGenerator which owns + // this SQLQualifiedRelation generates SQL. source = SQLQualifiedSource(relation.source.qualified(with: alias)) + + // Qualify all joins, selection, filter, and ordering, so that all + // identifiers can be correctly disambiguated and qualified. joins = relation.joins.mapValues(SQLQualifiedJoin.init) ownSelection = relation.selection.map { $0.qualifiedSelectable(with: alias) } - fullSelection = joins.reduce(into: ownSelection) { - $0.append(contentsOf: $1.value.relation.fullSelection) - } filterPromise = relation.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } - let ownOrdering = relation.ordering.qualified(with: alias) - ordering = joins.reduce(ownOrdering) { - $0.appending($1.value.relation.ordering) - } - allAliases = joins.reduce(into: [alias]) { - $0.append(contentsOf: $1.value.relation.allAliases) - } + ownOrdering = relation.ordering.qualified(with: alias) } - func rowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + /// See SQLSelectQueryGenerator.rowAdapter(_:) + /// + /// - parameter db: A database connection. + /// - parameter startIndex: The index of the leftmost selected column of + /// this relation in a full SQL query. `startIndex` is 0 for the relation + /// at the root of a SQLSelectQueryGenerator (as opposed to the + /// joined relations). + /// - returns: An optional tuple made of a RowAdapter and the index past the + /// rightmost selected column of this relation. Nil is returned if this + /// relations does not need any row adapter. + func rowAdapter(_ db: Database, fromIndex startIndex: Int) throws -> (adapter: RowAdapter, endIndex: Int)? { + // Root relation && no join => no need for any adapter if startIndex == 0 && joins.isEmpty { - // Root relation + no join => no adapter return nil } + // The number of columns in own selection. Columns selected by joined + // relations are appended after. let selectionWidth = try ownSelection .map { try $0.columnCount(db) } .reduce(0, +) + // Recursively build adapters for each joined relation with a selection. + // Name them according to the join keys. var endIndex = startIndex + selectionWidth var scopes: [String: RowAdapter] = [:] for (key, join) in joins { - if let (joinAdapter, joinEndIndex) = try join.relation.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { + if let (joinAdapter, joinEndIndex) = try join.relation.rowAdapter(db, fromIndex: endIndex) { scopes[key] = joinAdapter endIndex = joinEndIndex } } - if selectionWidth == 0 && scopes.isEmpty { + // (Root relation || empty selection) && no included relation => no need for any adapter + if (startIndex == 0 || selectionWidth == 0) && scopes.isEmpty { return nil } - let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) - return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) + // Build a RangeRowAdapter extended with the adapters of joined relations. + // + // // SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorId + // let request = Book.including(required: Book.author) + // for row in try Row.fetchAll(db, request) { + // + // The RangeRowAdapter hides the columns appended by joined relations: + // + // row // [id:1, title:"Moby-Dick"] + // let book = Book(row: row) + // + // Scopes give access to those joined relations: + // + // row.scopes["author"] // [id:12, name:"Herman Melville"] + // let author: Author = row["author"] + // } + let rangeAdapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) + let adapter = rangeAdapter.addingScopes(scopes) + + return (adapter: adapter, endIndex: endIndex) } } diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index 5f23e36a6..a0ffcf846 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -43,6 +43,15 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { } } + func testJoiningDoesNotUseAnyRowAdapter() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Player.joining(required: Player.defaultTeam) + let (_, adapter) = try request.prepare(db) + XCTAssertNil(adapter) + } + } + func testDefaultScopeIncludingRequired() throws { let dbQueue = try makeDatabaseQueue() let request = Player.including(required: Player.defaultTeam) diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 7eaa646d8..ee3b99bdc 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -46,7 +46,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testSimpleRequestDoesNotUseAnyRowAdapter() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let (statement, adapter) = try Reader.all().prepare(db) + let (_, adapter) = try Reader.all().prepare(db) XCTAssertNil(adapter) } }