diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 4a264ad8d..760ef2cb5 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -657,6 +657,8 @@ 56E5D82D1B4D438800430942 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56E8CE111BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */; }; + 56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; }; + 56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; }; 56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; @@ -1098,6 +1100,7 @@ 56E5D7F91B4D422D00430942 /* GRDBOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; @@ -1348,6 +1351,7 @@ children = ( 5653EABF20944B1300F46237 /* Association */, 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */, + 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, @@ -2561,6 +2565,7 @@ 562756471E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */, 56A238481B9C74A90082EB20 /* RowCopiedFromStatementTests.swift in Sources */, + 56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 5698AC071D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, @@ -2722,6 +2727,7 @@ 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */, 56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */, 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, + 56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */, 5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 8023699f2..4fc93f130 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -2,9 +2,9 @@ /// /// The base protocol for all associations that define a connection between two /// record types. -public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { - associatedtype LeftAssociated - associatedtype RightAssociated +public protocol Association: DerivableRequest { + associatedtype OriginRowDecoder + associatedtype RowDecoder /// The association key defines how rows fetched from this association /// should be consumed. @@ -50,14 +50,14 @@ public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. /// :nodoc: - var request: AssociationRequest { get } + var request: AssociationRequest { get } // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. /// :nodoc: func joinCondition(_ db: Database) throws -> JoinCondition /// :nodoc: - func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self + func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self } extension Association { @@ -240,33 +240,33 @@ extension Association { /// 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.LeftAssociated == RightAssociated { + public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { return mapRequest { $0.joining(.optional, association) } } /// 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.LeftAssociated == RightAssociated { + public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { return mapRequest { $0.joining(.required, association) } } /// 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.LeftAssociated == RightAssociated { + public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { return mapRequest { $0.joining(.optional, association.select([])) } } /// 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.LeftAssociated == RightAssociated { + public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { return mapRequest { $0.joining(.required, association.select([])) } } } -extension Association where LeftAssociated: MutablePersistableRecord { +extension Association where OriginRowDecoder: MutablePersistableRecord { /// Support for MutablePersistableRecord.request(for:). /// /// For example: @@ -280,11 +280,11 @@ extension Association where LeftAssociated: MutablePersistableRecord { /// /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] - func request(from record: LeftAssociated) -> QueryInterfaceRequest { + func request(from record: OriginRowDecoder) -> QueryInterfaceRequest { // Turn `JOIN associated ON associated.recordId = record.id` // into `FROM associated WHERE associated.recordId = 1` let associationAlias = TableAlias() - let recordAlias = TableAlias(tableName: LeftAssociated.databaseTableName) + let recordAlias = TableAlias(tableName: OriginRowDecoder.databaseTableName) return QueryInterfaceRequest(request) .aliased(associationAlias) .filter { db in diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index ba9f08ade..789e1326a 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -37,7 +37,7 @@ extension AssociationRequest { func joining(_ joinOperator: AssociationJoinOperator, _ association: A) -> AssociationRequest - where A.LeftAssociated == T + where A.OriginRowDecoder == T { let join = AssociationJoin( joinOperator: joinOperator, diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 7a6623eaa..b2f7b111d 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -1,21 +1,18 @@ -public struct BelongsToAssociation : Association, TableRequest where - Left: TableRecord, - Right: TableRecord -{ - public typealias LeftAssociated = Left - public typealias RightAssociated = Right +public struct BelongsToAssociation: Association { + fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest + /// :nodoc: + public typealias OriginRowDecoder = Origin + + /// :nodoc: + public typealias RowDecoder = Destination + public var key: String /// :nodoc: - public var databaseTableName: String { return RightAssociated.databaseTableName } - - /// :nodoc: - public var request: AssociationRequest - - let foreignKeyRequest: ForeignKeyRequest + public var request: AssociationRequest - public func forKey(_ key: String) -> BelongsToAssociation { + public func forKey(_ key: String) -> BelongsToAssociation { var association = self association.key = key return association @@ -23,45 +20,43 @@ public struct BelongsToAssociation : Association, TableRequest wher /// :nodoc: public func joinCondition(_ db: Database) throws -> JoinCondition { - return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: true).fetch(db) + return try joinConditionRequest.fetch(db) } /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { var association = self association.request = transform(request) return association } } +extension BelongsToAssociation: TableRequest where Destination: TableRecord { + /// :nodoc: + public var databaseTableName: String { return Destination.databaseTableName } +} + extension TableRecord { - // TODO: Make it public if and only if we really want to build an association from any request - static func belongsTo( - _ rightRequest: QueryInterfaceRequest, + /// TODO + public static func belongsTo( + _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> BelongsToAssociation - where Right: TableRecord + -> BelongsToAssociation + where Destination: TableRecord { let foreignKeyRequest = ForeignKeyRequest( originTable: databaseTableName, - destinationTable: Right.databaseTableName, + destinationTable: Destination.databaseTableName, foreignKey: foreignKey) + let joinConditionRequest = ForeignKeyJoinConditionRequest( + foreignKeyRequest: foreignKeyRequest, + originIsLeft: true) + return BelongsToAssociation( - key: key ?? Right.databaseTableName, - request: AssociationRequest(rightRequest), - foreignKeyRequest: foreignKeyRequest) - } - - /// TODO - public static func belongsTo( - _ right: Right.Type, - key: String? = nil, - using foreignKey: ForeignKey? = nil) - -> BelongsToAssociation - where Right: TableRecord - { - return belongsTo(Right.all(), key: key, using: foreignKey) + joinConditionRequest: joinConditionRequest, + key: key ?? Destination.databaseTableName, + request: AssociationRequest(Destination.all())) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 4c9d88edf..249593787 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -1,21 +1,18 @@ -public struct HasManyAssociation : Association, TableRequest where - Left: TableRecord, - Right: TableRecord -{ - public typealias LeftAssociated = Left - public typealias RightAssociated = Right +public struct HasManyAssociation: Association { + fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest + + /// :nodoc: + public typealias OriginRowDecoder = Origin + /// :nodoc: + public typealias RowDecoder = Destination + public var key: String /// :nodoc: - public var databaseTableName: String { return RightAssociated.databaseTableName } + public var request: AssociationRequest - /// :nodoc: - public var request: AssociationRequest - - let foreignKeyRequest: ForeignKeyRequest - - public func forKey(_ key: String) -> HasManyAssociation { + public func forKey(_ key: String) -> HasManyAssociation { var association = self association.key = key return association @@ -23,45 +20,43 @@ public struct HasManyAssociation : Association, TableRequest where /// :nodoc: public func joinCondition(_ db: Database) throws -> JoinCondition { - return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: false).fetch(db) + return try joinConditionRequest.fetch(db) } /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { var association = self association.request = transform(request) return association } } +extension HasManyAssociation: TableRequest where Destination: TableRecord { + /// :nodoc: + public var databaseTableName: String { return Destination.databaseTableName } +} + extension TableRecord { - // TODO: Make it public if and only if we really want to build an association from any request - static func hasMany( - _ rightRequest: QueryInterfaceRequest, + /// TODO + public static func hasMany( + _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> HasManyAssociation - where Right: TableRecord + -> HasManyAssociation + where Destination: TableRecord { let foreignKeyRequest = ForeignKeyRequest( - originTable: Right.databaseTableName, + originTable: Destination.databaseTableName, destinationTable: databaseTableName, foreignKey: foreignKey) + let joinConditionRequest = ForeignKeyJoinConditionRequest( + foreignKeyRequest: foreignKeyRequest, + originIsLeft: false) + return HasManyAssociation( - key: key ?? Right.databaseTableName, - request: AssociationRequest(rightRequest), - foreignKeyRequest: foreignKeyRequest) - } - - /// TODO - public static func hasMany( - _ right: Right.Type, - key: String? = nil, - using foreignKey: ForeignKey? = nil) - -> HasManyAssociation - where Right: TableRecord - { - return hasMany(Right.all(), key: key, using: foreignKey) + joinConditionRequest: joinConditionRequest, + key: key ?? Destination.databaseTableName, + request: AssociationRequest(Destination.all())) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index b3c70de9e..b5ef7be12 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -1,21 +1,18 @@ -public struct HasOneAssociation : Association, TableRequest where - Left: TableRecord, - Right: TableRecord -{ - public typealias LeftAssociated = Left - public typealias RightAssociated = Right +public struct HasOneAssociation : Association { + fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest + + /// :nodoc: + public typealias OriginRowDecoder = Origin + + /// :nodoc: + public typealias RowDecoder = Destination public var key: String /// :nodoc: - public var databaseTableName: String { return RightAssociated.databaseTableName } + public var request: AssociationRequest - /// :nodoc: - public var request: AssociationRequest - - let foreignKeyRequest: ForeignKeyRequest - - public func forKey(_ key: String) -> HasOneAssociation { + public func forKey(_ key: String) -> HasOneAssociation { var association = self association.key = key return association @@ -23,45 +20,43 @@ public struct HasOneAssociation : Association, TableRequest where /// :nodoc: public func joinCondition(_ db: Database) throws -> JoinCondition { - return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: false).fetch(db) + return try joinConditionRequest.fetch(db) } /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { var association = self association.request = transform(request) return association } } +extension HasOneAssociation: TableRequest where Destination: TableRecord { + /// :nodoc: + public var databaseTableName: String { return Destination.databaseTableName } +} + extension TableRecord { - // TODO: Make it public if and only if we really want to build an association from any request - static func hasOne( - _ rightRequest: QueryInterfaceRequest, + /// TODO + public static func hasOne( + _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> HasOneAssociation - where Right: TableRecord + -> HasOneAssociation + where Destination: TableRecord { let foreignKeyRequest = ForeignKeyRequest( - originTable: Right.databaseTableName, + originTable: Destination.databaseTableName, destinationTable: databaseTableName, foreignKey: foreignKey) + let joinConditionRequest = ForeignKeyJoinConditionRequest( + foreignKeyRequest: foreignKeyRequest, + originIsLeft: false) + return HasOneAssociation( - key: key ?? Right.databaseTableName, - request: AssociationRequest(rightRequest), - foreignKeyRequest: foreignKeyRequest) - } - - /// TODO - public static func hasOne( - _ right: Right.Type, - key: String? = nil, - using foreignKey: ForeignKey? = nil) - -> HasOneAssociation - where Right: TableRecord - { - return hasOne(Right.all(), key: key, using: foreignKey) + joinConditionRequest: joinConditionRequest, + key: key ?? Destination.databaseTableName, + request: AssociationRequest(Destination.all())) } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 32dafae77..cf627a845 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -1,7 +1,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { func joining(_ joinOperator: AssociationJoinOperator, _ association: A) -> QueryInterfaceRequest - where A.LeftAssociated == RowDecoder + where A.OriginRowDecoder == RowDecoder { let join = AssociationJoin( joinOperator: joinOperator, @@ -16,28 +16,28 @@ 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.LeftAssociated == RowDecoder { + public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { return joining(.optional, association) } /// 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.LeftAssociated == RowDecoder { + public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { return joining(.required, association) } /// 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.LeftAssociated == RowDecoder { + public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { return joining(.optional, association.select([])) } /// 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.LeftAssociated == RowDecoder { + public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { return joining(.required, association.select([])) } } @@ -56,7 +56,7 @@ extension MutablePersistableRecord { /// /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] - public func request(for association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public func request(for association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return association.request(from: self) } } @@ -68,28 +68,28 @@ extension 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 static func including(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public static func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return all().including(optional: association) } /// 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 static func including(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public static func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return all().including(required: association) } /// 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 static func joining(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public static func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return all().joining(optional: association) } /// 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 static func joining(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public static func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return all().joining(required: association) } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 38ab39e52..d6af81c04 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -43,7 +43,7 @@ extension QueryInterfaceRequest : FetchRequest { } } -extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, AggregatingRequest, OrderedRequest { +extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { // MARK: Request Derivation @@ -192,7 +192,7 @@ extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord { } } -extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { +extension QueryInterfaceRequest where T: MutablePersistableRecord { // MARK: Deleting diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index 8ae46b0a4..3588a77d3 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -319,3 +319,12 @@ extension OrderedRequest { return order([expression]) } } + +// MARK: - DerivableRequest + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The base protocol for all requests that can be refined. +public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest { + associatedtype RowDecoder +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index c498b799b..6286c1471 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -824,6 +824,10 @@ 56DAA2DF1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; 56E06F131E859068008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; 56E06F161E85906C008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; + 56EA63CC209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CD209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CE209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CF209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; 56F26C241CEE3F34007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; 56F3E74A1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F3E74B1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; @@ -1164,6 +1168,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.102.0.swift"; sourceTree = ""; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; @@ -1416,6 +1421,7 @@ children = ( 5653EBA420961FD300F46237 /* Association */, 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */, + 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, @@ -2263,6 +2269,7 @@ 560FC56C1CB00B880014AA8E /* UpdateStatementTests.swift in Sources */, 5653EBE020961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 560FC56D1CB00B880014AA8E /* DatabaseMigratorTests.swift in Sources */, + 56EA63CC209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */, 560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */, 560FC5721CB00B880014AA8E /* StatementColumnConvertibleTests.swift in Sources */, @@ -2424,6 +2431,7 @@ 5671562F1CB16729007DC145 /* RecordPrimaryKeySingleTests.swift in Sources */, 5653EBE120961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 567156301CB16729007DC145 /* StatementColumnConvertibleTests.swift in Sources */, + 56EA63CD209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56B021CB1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, @@ -2695,6 +2703,7 @@ 56AFCA3E1CB1AA9900F48B96 /* DatabasePoolCollationTests.swift in Sources */, 5653EBE220961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, + 56EA63CE209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 56AFCA3F1CB1AA9900F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 56AFCA411CB1AA9900F48B96 /* StatementColumnConvertibleTests.swift in Sources */, 56AFCA421CB1AA9900F48B96 /* DatabasePoolFunctionTests.swift in Sources */, @@ -2856,6 +2865,7 @@ 56AFCA931CB1ABC800F48B96 /* UpdateStatementTests.swift in Sources */, 5653EBE320961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56AFCA941CB1ABC800F48B96 /* DatabaseMigratorTests.swift in Sources */, + 56EA63CF209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 5657AB641D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 56FF455C1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56AFCA971CB1ABC800F48B96 /* DatabasePoolCollationTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 90f2ee9c5..fcf06e10f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -318,6 +318,8 @@ 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; 56E06F141E859069008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; 56E06F171E85906D008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; + 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; }; 56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; @@ -827,6 +829,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.102.0.swift"; sourceTree = ""; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; @@ -1062,6 +1065,7 @@ children = ( 5653EB5620961F8900F46237 /* Association */, 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */, + 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, @@ -1938,6 +1942,7 @@ F3BA80F81CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, 5653EB7D20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698AC0A1D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, + 56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, @@ -2209,6 +2214,7 @@ F3BA80E61CFB3012003DC1BA /* DatabaseFunctionTests.swift in Sources */, 5653EB7C20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698ACDA1DA925430056AF8C /* RowTestCase.swift in Sources */, + 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, 5698ACB91DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift new file mode 100644 index 000000000..bc5a9381a --- /dev/null +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -0,0 +1,85 @@ +import XCTest +#if GRDBCIPHER +import GRDBCipher +#elseif GRDBCUSTOMSQLITE +import GRDBCustomSQLite +#else +import GRDB +#endif + +private struct Author: FetchableRecord, PersistableRecord, Codable { + var id: Int64 + var name: String + var country: String + + static let databaseTableName = "author" + static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { + return request(for: Author.books) + } +} +private struct Book: FetchableRecord, PersistableRecord, Codable { + var id: Int64 + var authorId: Int64 + var title: String + + static let databaseTableName = "book" + static let author = belongsTo(Author.self) + var author: QueryInterfaceRequest { + return request(for: Book.author) + } +} + +private var libraryMigrator: DatabaseMigrator = { + var migrator = DatabaseMigrator() + migrator.registerMigration("library") { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + t.column("country", .text).notNull() + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer).notNull().references("author") + t.column("title", .text).notNull() + } + } + migrator.registerMigration("fixture") { db in + try Author(id: 1, name: "Melville", country: "US").insert(db) + try Author(id: 2, name: "Proust", country: "FR").insert(db) + try Book(id: 1, authorId: 1, title: "Moby-Dick").insert(db) + try Book(id: 2, authorId: 2, title: "Du côté de chez Swann").insert(db) + try Book(id: 3, authorId: 2, title: "Le Côté de Guermantes").insert(db) + } + return migrator +}() + +// One extension... +extension DerivableRequest where RowDecoder == Author { + func filter(country: String) -> Self { + return filter(Column("country") == country) + } +} + +class DerivableRequestTests: GRDBTestCase { + func testDerivation() throws { + let dbQueue = try makeDatabaseQueue() + try libraryMigrator.migrate(dbQueue) + try dbQueue.inDatabase { db in + // ... for two requests (1) + let frenchAuthorNames = try Author.all() + .filter(country: "FR") + .fetchAll(db) + .map { $0.name } + XCTAssertEqual(frenchAuthorNames, ["Proust"]) + + // ... for two requests (2) + let frenchBookTitles = try Book + .joining(required: Book.author.filter(country: "FR")) + .order(Column("title")) + .fetchAll(db) + .map { $0.title } + XCTAssertEqual(frenchBookTitles, ["Du côté de chez Swann", "Le Côté de Guermantes"]) + } + } +} diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index 68c2beb6a..d54e3d1ab 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -65,7 +65,7 @@ class SQLRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = CustomRequest() - let sqlRequest = try SQLRequest(db, request: request) + let sqlRequest = try SQLRequest(db, request: request) XCTAssertEqual(sqlRequest.sql, "SELECT ? AS a, ? AS b") XCTAssertEqual(sqlRequest.arguments, [1, "foo"]) XCTAssertEqual(try sqlRequest.fetchOne(db)!, ["a": 1, "b": "foo"])