From e7a590b82b204871f152a0e7ddcdcbdd8036c1e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 29 May 2019 08:36:55 +0200 Subject: [PATCH] Extract joining methods to the JoinableRequest protocol --- .../Request/Association/Association.swift | 82 ++++-------- .../QueryInterfaceRequest+Association.swift | 54 -------- .../Request/QueryInterfaceRequest.swift | 125 ++++++++++++------ .../Request/RequestProtocols.swift | 92 ++++++++++++- GRDB/QueryInterface/SQL/SQLAssociation.swift | 2 +- GRDB/QueryInterface/SQL/SQLQuery.swift | 88 ++++++++---- GRDB/QueryInterface/SQL/SQLRelation.swift | 61 ++++----- 7 files changed, 285 insertions(+), 219 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 2ff915f14..27cc272fd 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -20,16 +20,6 @@ public protocol Association: DerivableRequest { /// } 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 - /// :nodoc: var sqlAssociation: SQLAssociation { get } @@ -53,6 +43,33 @@ public protocol Association: DerivableRequest { init(sqlAssociation: SQLAssociation) } +extension Association { + /// :nodoc: + public func _including(all association: SQLAssociation) -> Self { + return mapDestinationRelation { $0._including(all: association) } + } + + /// :nodoc: + public func _including(optional association: SQLAssociation) -> Self { + return mapDestinationRelation { $0._including(optional: association) } + } + + /// :nodoc: + public func _including(required association: SQLAssociation) -> Self { + return mapDestinationRelation { $0._including(required: association) } + } + + /// :nodoc: + public func _joining(optional association: SQLAssociation) -> Self { + return mapDestinationRelation { $0._joining(optional: association) } + } + + /// :nodoc: + public func _joining(required association: SQLAssociation) -> Self { + return mapDestinationRelation { $0._joining(required: association) } + } +} + extension Association { private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { return Self.init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform)) @@ -273,51 +290,6 @@ extension Association { } } -extension Association { - /// Creates an association that prefetches another one. - public func including(all association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapDestinationRelation { - $0.including(all: association.sqlAssociation) - } - } - - /// Creates an association that includes another one. 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) -> Self where A.OriginRowDecoder == RowDecoder { - return mapDestinationRelation { - $0.including(optional: association.sqlAssociation) - } - } - - /// 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 mapDestinationRelation { - $0.including(required: association.sqlAssociation) - } - } - - /// 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 mapDestinationRelation { - $0.joining(optional: association.sqlAssociation) - } - } - - /// 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 mapDestinationRelation { - $0.joining(required: association.sqlAssociation) - } - } -} - // Allow association.filter(key: ...) extension Association where Self: TableRequest, RowDecoder: TableRecord { /// :nodoc: diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift index 8ef57e1d9..ccc080857 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift @@ -1,58 +1,4 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { - // MARK: - Associations - - /// Creates a request that prefetches an association. - public func including(all association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return mapQuery { - $0.mapRelation { - $0.including(all: association.sqlAssociation) - } - } - } - - /// Creates a request that includes an association. The columns of the - /// associated record are selected. The returned request does not - /// require that the associated database table contains a matching row. - public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return mapQuery { - $0.mapRelation { - $0.including(optional: association.sqlAssociation) - } - } - } - - /// Creates a request that includes an association. The columns of the - /// associated record are selected. The returned request requires - /// that the associated database table contains a matching row. - public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return mapQuery { - $0.mapRelation { - $0.including(required: association.sqlAssociation) - } - } - } - - /// Creates a request that joins an association. The columns of the - /// associated record are not selected. The returned request does not - /// require that the associated database table contains a matching row. - public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return mapQuery { - $0.mapRelation { - $0.joining(optional: association.sqlAssociation) - } - } - } - - /// Creates a request that joins an association. The columns of the - /// associated record are not selected. The returned request requires - /// that the associated database table contains a matching row. - public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return mapQuery { - $0.mapRelation { - $0.joining(required: association.sqlAssociation) - } - } - } // MARK: - Association Aggregates diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 6c710e103..22ae9c18e 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -28,7 +28,7 @@ /// } /// /// See https://github.com/groue/GRDB.swift#the-query-interface -public struct QueryInterfaceRequest { +public struct QueryInterfaceRequest: DerivableRequest { var query: SQLQuery init(query: SQLQuery) { @@ -44,7 +44,7 @@ public struct QueryInterfaceRequest { } } -extension QueryInterfaceRequest : FetchRequest { +extension QueryInterfaceRequest: FetchRequest { public typealias RowDecoder = T /// Returns a tuple that contains a prepared statement that is ready to be @@ -108,10 +108,9 @@ extension QueryInterfaceRequest : FetchRequest { } } -extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { - +extension QueryInterfaceRequest: SelectionRequest { // MARK: Request Derivation - + /// Creates a request which selects *selection*. /// /// // SELECT id, email FROM player @@ -214,20 +213,11 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { // From raw rows? From copied rows? return mapQuery { $0.annotated(with: selection) } } +} + +extension QueryInterfaceRequest: FilteredRequest { + // MARK: Request Derivation - /// Creates a request which returns distinct rows. - /// - /// // SELECT DISTINCT * FROM player - /// var request = Player.all() - /// request = request.distinct() - /// - /// // SELECT DISTINCT name FROM player - /// var request = Player.select(Column("name")) - /// request = request.distinct() - public func distinct() -> QueryInterfaceRequest { - return mapQuery { $0.distinct() } - } - /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// @@ -237,28 +227,11 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { return mapQuery { $0.filter(predicate) } } - - /// Creates a request which expects a single result. - /// - /// It is unlikely you need to call this method. Its net effect is that - /// QueryInterfaceRequest does not use any `LIMIT 1` sql clause when you - /// call a `fetchOne` method. - /// - /// :nodoc: - public func expectingSingleResult() -> QueryInterfaceRequest { - return mapQuery { $0.expectingSingleResult() } - } - - /// Creates a request grouped according to *expressions promise*. - 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 mapQuery { $0.having(predicate) } - } + +} + +extension QueryInterfaceRequest: OrderedRequest { + // MARK: Request Derivation /// Creates a request with the provided *orderings promise*. /// @@ -300,6 +273,78 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { public func unordered() -> QueryInterfaceRequest { return mapQuery { $0.unordered() } } +} + +extension QueryInterfaceRequest: AggregatingRequest { + // MARK: Request Derivation + + /// Creates a request grouped according to *expressions promise*. + 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 mapQuery { $0.having(predicate) } + } +} + +extension QueryInterfaceRequest: JoinableRequest { + /// :nodoc: + public func _including(all association: SQLAssociation) -> QueryInterfaceRequest { + return mapQuery { $0._including(all: association) } + } + + /// :nodoc: + public func _including(optional association: SQLAssociation) -> QueryInterfaceRequest { + return mapQuery { $0._including(optional: association) } + } + + /// :nodoc: + public func _including(required association: SQLAssociation) -> QueryInterfaceRequest { + return mapQuery { $0._including(required: association) } + } + + /// :nodoc: + public func _joining(optional association: SQLAssociation) -> QueryInterfaceRequest { + return mapQuery { $0._joining(optional: association) } + } + + /// :nodoc: + public func _joining(required association: SQLAssociation) -> QueryInterfaceRequest { + return mapQuery { $0._joining(required: association) } + } +} + +extension QueryInterfaceRequest { + + // MARK: Request Derivation + + /// Creates a request which returns distinct rows. + /// + /// // SELECT DISTINCT * FROM player + /// var request = Player.all() + /// request = request.distinct() + /// + /// // SELECT DISTINCT name FROM player + /// var request = Player.select(Column("name")) + /// request = request.distinct() + public func distinct() -> QueryInterfaceRequest { + return mapQuery { $0.distinct() } + } + + /// Creates a request which expects a single result. + /// + /// It is unlikely you need to call this method. Its net effect is that + /// QueryInterfaceRequest does not use any `LIMIT 1` sql clause when you + /// call a `fetchOne` method. + /// + /// :nodoc: + public func expectingSingleResult() -> QueryInterfaceRequest { + return mapQuery { $0.expectingSingleResult() } + } + /// Creates a request which fetches *limit* rows, starting at *offset*. /// diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 9d6e09ed6..c8c467d4f 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -384,7 +384,7 @@ extension AggregatingRequest { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// -/// The protocol for all requests that be ordered. +/// The protocol for all requests that can be ordered. /// /// :nodoc: public protocol OrderedRequest { @@ -494,6 +494,92 @@ extension OrderedRequest { } } +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// Type-unsafe support for the JoinableRequest protocol. +/// +/// :nodoc: +public protocol _JoinableRequest { + /// Creates a request that prefetches an association. + func _including(all association: SQLAssociation) -> Self + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned request does not + /// require that the associated database table contains a matching row. + func _including(optional association: SQLAssociation) -> Self + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned request requires + /// that the associated database table contains a matching row. + func _including(required association: SQLAssociation) -> Self + + /// Creates a request that joins an association. The columns of the + /// associated record are not selected. The returned request does not + /// require that the associated database table contains a matching row. + func _joining(optional association: SQLAssociation) -> Self + + /// Creates a request that joins an association. The columns of the + /// associated record are not selected. The returned request requires + /// that the associated database table contains a matching row. + func _joining(required association: SQLAssociation) -> Self +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The protocol for all requests that can be associated. +/// +/// :nodoc: +public protocol JoinableRequest: _JoinableRequest { + /// The record type that can be associated to. + /// + /// In the request below, it is Book: + /// + /// let request = Book.all() + /// + /// In the `belongsTo` association below, it is Author: + /// + /// struct Book: TableRecord { + /// // BelongsToAssociation + /// static let author = belongsTo(Author.self) + /// } + associatedtype RowDecoder +} + +extension JoinableRequest { + /// Creates a request that prefetches an association. + public func including(all association: A) -> Self where A.OriginRowDecoder == RowDecoder { + return _including(all: association.sqlAssociation) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned request does not + /// require that the associated database table contains a matching row. + public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { + return _including(optional: association.sqlAssociation) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned request requires + /// that the associated database table contains a matching row. + public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { + return _including(required: association.sqlAssociation) + } + + /// Creates a request that joins an association. The columns of the + /// associated record are not selected. The returned request does not + /// require that the associated database table contains a matching row. + public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { + return _joining(optional: association.sqlAssociation) + } + + /// Creates a request that joins an association. The columns of the + /// associated record are not selected. The returned request requires + /// that the associated database table contains a matching row. + public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { + return _joining(required: association.sqlAssociation) + } +} + // MARK: - DerivableRequest /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -501,6 +587,4 @@ extension OrderedRequest { /// The base protocol for all requests that can be refined. /// /// :nodoc: -public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest { - associatedtype RowDecoder -} +public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest, JoinableRequest { } diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index a918fcea5..6419373fe 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -208,7 +208,7 @@ public /* TODO: internal */ struct SQLAssociation { reversedAssociation = reversedAssociation.mapDestinationRelation { _ in filteredPivotRelation.select([]).deletingChildren() } - return destination.relation.appending(reversedAssociation, kind: .oneRequired) + return destination.relation.appendingChild(for: reversedAssociation, kind: .oneRequired) } } diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index 454f4f523..ad3e1b2fb 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -29,13 +29,12 @@ struct SQLQuery { } } -extension SQLQuery: SelectionRequest, FilteredRequest, OrderedRequest { - func select(_ selection: [SQLSelectable]) -> SQLQuery { - return mapRelation { $0.select(selection) } - } - - func annotated(with selection: [SQLSelectable]) -> SQLQuery { - return mapRelation { $0.annotated(with: selection) } +extension SQLQuery { + /// Returns a query whose relation is transformed by the given closure. + func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> SQLQuery { + var query = self + query.relation = transform(relation) + return query } func distinct() -> SQLQuery { @@ -43,29 +42,41 @@ extension SQLQuery: SelectionRequest, FilteredRequest, OrderedRequest { query.isDistinct = true return query } - + func expectingSingleResult() -> SQLQuery { var query = self query.expectsSingleResult = true return query } + func limit(_ limit: Int, offset: Int? = nil) -> SQLQuery { + var query = self + query.limit = SQLLimit(limit: limit, offset: offset) + return query + } + + func qualified(with alias: TableAlias) -> SQLQuery { + return mapRelation { $0.qualified(with: alias) } + } +} + +extension SQLQuery: SelectionRequest { + func select(_ selection: [SQLSelectable]) -> SQLQuery { + return mapRelation { $0.select(selection) } + } + + func annotated(with selection: [SQLSelectable]) -> SQLQuery { + return mapRelation { $0.annotated(with: selection) } + } +} + +extension SQLQuery: FilteredRequest { func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLQuery { return mapRelation { $0.filter(predicate) } } - - func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> SQLQuery { - var query = self - query.groupPromise = DatabasePromise { db in try expressions(db).map { $0.sqlExpression } } - return query - } - - func having(_ predicate: SQLExpressible) -> SQLQuery { - var query = self - query.havingExpressions.append(predicate.sqlExpression) - return query - } +} +extension SQLQuery: OrderedRequest { func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> SQLQuery { return mapRelation { $0.order(orderings) } } @@ -77,22 +88,41 @@ extension SQLQuery: SelectionRequest, FilteredRequest, OrderedRequest { func unordered() -> SQLQuery { return mapRelation { $0.unordered() } } +} - func limit(_ limit: Int, offset: Int? = nil) -> SQLQuery { +extension SQLQuery: AggregatingRequest { + func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> SQLQuery { var query = self - query.limit = SQLLimit(limit: limit, offset: offset) + query.groupPromise = DatabasePromise { db in try expressions(db).map { $0.sqlExpression } } return query } - func qualified(with alias: TableAlias) -> SQLQuery { - return mapRelation { $0.qualified(with: alias) } + func having(_ predicate: SQLExpressible) -> SQLQuery { + var query = self + query.havingExpressions.append(predicate.sqlExpression) + return query + } +} + +extension SQLQuery: _JoinableRequest { + func _including(all association: SQLAssociation) -> SQLQuery { + return mapRelation { $0._including(all: association) } } - /// Returns a query whose relation is transformed by the given closure. - func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> SQLQuery { - var query = self - query.relation = transform(relation) - return query + func _including(optional association: SQLAssociation) -> SQLQuery { + return mapRelation { $0._including(optional: association) } + } + + func _including(required association: SQLAssociation) -> SQLQuery { + return mapRelation { $0._including(required: association) } + } + + func _joining(optional association: SQLAssociation) -> SQLQuery { + return mapRelation { $0._joining(optional: association) } + } + + func _joining(required association: SQLAssociation) -> SQLQuery { + return mapRelation { $0._joining(required: association) } } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index f29b0ec03..ec5123fa2 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -244,39 +244,6 @@ extension SQLRelation { return relation } - /// Creates a relation that prefetches another one. - func including(all association: SQLAssociation) -> SQLRelation { - return appending(association, kind: .allPrefetched) - } - - /// Creates a relation that includes another one. The columns of the - /// associated record are selected. The returned relation does not - /// require that the associated database table contains a matching row. - func including(optional association: SQLAssociation) -> SQLRelation { - return appending(association, kind: .oneOptional) - } - - /// Creates a relation that includes another one. The columns of the - /// associated record are selected. The returned relation requires - /// that the associated database table contains a matching row. - func including(required association: SQLAssociation) -> SQLRelation { - return appending(association, kind: .oneRequired) - } - - /// Creates a relation that joins another one. The columns of the - /// associated record are not selected. The returned relation does not - /// require that the associated database table contains a matching row. - func joining(optional association: SQLAssociation) -> SQLRelation { - return appending(association.mapDestinationRelation { $0.select([]) }, kind: .oneOptional) - } - - /// Creates a relation that joins another one. The columns of the - /// associated record are not selected. The returned relation requires - /// that the associated database table contains a matching row. - func joining(required association: SQLAssociation) -> SQLRelation { - return appending(association.mapDestinationRelation { $0.select([]) }, kind: .oneRequired) - } - /// Returns a relation extended with an association. /// /// This method provides support for public joining methods such @@ -309,7 +276,7 @@ extension SQLRelation { /// HasMany in the above examples, but also for indirect associations such /// as HasManyThrough, which have any number of pivot relations between the /// origin and the destination. - func appending(_ association: SQLAssociation, kind: SQLRelation.Child.Kind) -> SQLRelation { + func appendingChild(for association: SQLAssociation, kind: SQLRelation.Child.Kind) -> SQLRelation { let childCardinality = (kind == .allNotPrefetched) // preserve association cardinality in intermediate steps of including(all:) ? association.destination.cardinality @@ -359,7 +326,7 @@ extension SQLRelation { switch kind { case .oneRequired, .oneOptional, .allNotPrefetched: - return appending(reducedAssociation, kind: kind) + return appendingChild(for: reducedAssociation, kind: kind) case .allPrefetched: // Intermediate steps of indirect associations are not prefetched. // @@ -371,7 +338,7 @@ extension SQLRelation { // static let citizens = hasMany(Citizens.self, through: passports, using: Passport.citizen) // } // let request = Country.including(all: Country.citizens) - return appending(reducedAssociation, kind: .allNotPrefetched) + return appendingChild(for: reducedAssociation, kind: .allNotPrefetched) } } @@ -390,6 +357,28 @@ extension SQLRelation { } } +extension SQLRelation: _JoinableRequest { + func _including(all association: SQLAssociation) -> SQLRelation { + return appendingChild(for: association, kind: .allPrefetched) + } + + func _including(optional association: SQLAssociation) -> SQLRelation { + return appendingChild(for: association, kind: .oneOptional) + } + + func _including(required association: SQLAssociation) -> SQLRelation { + return appendingChild(for: association, kind: .oneRequired) + } + + func _joining(optional association: SQLAssociation) -> SQLRelation { + return appendingChild(for: association.mapDestinationRelation { $0.select([]) }, kind: .oneOptional) + } + + func _joining(required association: SQLAssociation) -> SQLRelation { + return appendingChild(for: association.mapDestinationRelation { $0.select([]) }, kind: .oneRequired) + } +} + // MARK: - SQLSource enum SQLSource {