From c42cf38fc2b438980d71b0e95db92e98b8cde30c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 30 May 2019 20:32:18 +0200 Subject: [PATCH 1/9] TODO --- TODO.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/TODO.md b/TODO.md index bff48778b..489d3f961 100644 --- a/TODO.md +++ b/TODO.md @@ -44,12 +44,7 @@ - [ ] Look at the jazzy configuration of https://github.com/bignerdranch/Deferred - [ ] FTS: prefix queries - [ ] Test NOT TESTED methods -- [ ] Update RxGRDB: https://github.com/RxSwiftCommunity/RxGRDB/pull/51 -- [ ] Update [GRDBObjc](https://github.com/groue/GRDBObjc) - -GRDB 4.0 - -- [ ] Review @inlinable stuff +- [ ] A way to stop a ValueObservation observer without waiting for deinit Swift 4.2 From ce95590b8a07703a0fd52c23128bce9224c7dea5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 31 May 2019 07:59:33 +0200 Subject: [PATCH 2/9] New example of record definition --- CHANGELOG.md | 2 + README.md | 105 +++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 96 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2f357230..fada449ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: The [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter of the The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) has been rewritten. Yes, good practices evolve. +The [Examples of Record Definitions](README.md#examples-of-record-definitions) has been extended with a sample record optimized for fetching performance. + ## 4.0.1 diff --git a/README.md b/README.md index 3b2a5a5bb..503a44e10 100644 --- a/README.md +++ b/README.md @@ -3355,7 +3355,7 @@ try dbQueue.write { db in try db.create(table: "place") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() - t.column("favorite", .boolean).notNull().defaults(to: false) + t.column("isFavorite", .boolean).notNull().defaults(to: false) t.column("longitude", .double).notNull() t.column("latitude", .double).notNull() } @@ -3375,9 +3375,9 @@ See the [Record Protocols Overview](#record-protocols-overview), and [Codable Re struct Place: Codable { var id: Int64? var title: String - var favorite: Bool - var latitude: CLLocationDegrees - var longitude: CLLocationDegrees + var isFavorite: Bool + private var latitude: CLLocationDegrees + private var longitude: CLLocationDegrees var coordinate: CLLocationCoordinate2D { get { @@ -3393,7 +3393,16 @@ struct Place: Codable { } // SQL generation -extension Place: TableRecord { } +extension Place: TableRecord { + /// The table columns + enum Columns { + static let id = Column(CodingKeys.id) + static let title = Column(CodingKeys.title) + static let isFavorite = Column(CodingKeys.isFavorite) + static let latitude = Column(CodingKeys.latitude) + static let longitude = Column(CodingKeys.longitude) + } +} // Fetching methods extension Place: FetchableRecord { } @@ -3426,7 +3435,7 @@ struct Place { extension Place: TableRecord { /// The table columns enum Columns: String, ColumnExpression { - case id, title, favorite, latitude, longitude + case id, title, isFavorite, latitude, longitude } } @@ -3436,7 +3445,7 @@ extension Place: FetchableRecord { init(row: Row) { id = row[Columns.id] title = row[Columns.title] - isFavorite = row[Columns.favorite] + isFavorite = row[Columns.isFavorite] coordinate = CLLocationCoordinate2D( latitude: row[Columns.latitude], longitude: row[Columns.longitude]) @@ -3449,7 +3458,7 @@ extension Place: MutablePersistableRecord { func encode(to container: inout PersistenceContainer) { container[Columns.id] = id container[Columns.title] = title - container[Columns.favorite] = isFavorite + container[Columns.isFavorite] = isFavorite container[Columns.latitude] = coordinate.latitude container[Columns.longitude] = coordinate.longitude } @@ -3490,14 +3499,14 @@ class Place: Record { /// The table columns enum Columns: String, ColumnExpression { - case id, title, favorite, latitude, longitude + case id, title, isFavorite, latitude, longitude } /// Creates a record from a database row required init(row: Row) { id = row[Columns.id] title = row[Columns.title] - isFavorite = row[Columns.favorite] + isFavorite = row[Columns.isFavorite] coordinate = CLLocationCoordinate2D( latitude: row[Columns.latitude], longitude: row[Columns.longitude]) @@ -3508,7 +3517,7 @@ class Place: Record { override func encode(to container: inout PersistenceContainer) { container[Columns.id] = id container[Columns.title] = title - container[Columns.favorite] = isFavorite + container[Columns.isFavorite] = isFavorite container[Columns.latitude] = coordinate.latitude container[Columns.longitude] = coordinate.longitude } @@ -3522,6 +3531,80 @@ class Place: Record { +
+ Define a struct optimized for fetching performance + +This struct derives is persistence methpds from the standard Encodable protocol (see [Codable Records]), but performs optimized row decoding by accessing database columns with numeric indexes. + +See the [Record Protocols Overview](#record-protocols-overview) for more information. + +```swift +struct Place: Encodable { + var id: Int64? + var title: String + var isFavorite: Bool + private var latitude: CLLocationDegrees + private var longitude: CLLocationDegrees + + var coordinate: CLLocationCoordinate2D { + get { + return CLLocationCoordinate2D( + latitude: latitude, + longitude: longitude) + } + set { + latitude = newValue.latitude + longitude = newValue.longitude + } + } +} + +// SQL generation +extension Place: TableRecord { + /// The table columns + enum Columns { + static let id = Column(CodingKeys.id) + static let title = Column(CodingKeys.title) + static let isFavorite = Column(CodingKeys.isFavorite) + static let latitude = Column(CodingKeys.latitude) + static let longitude = Column(CodingKeys.longitude) + } + + /// Arrange the selected columns and lock their order + static let databaseSelection: [SQLSelectable] = [ + Columns.id, + Columns.title, + Columns.favorite, + Columns.latitude, + Columns.longitude] +} + +// Fetching methods +extension Place: FetchableRecord { + /// Creates a record from a database row + init(row: Row) { + // For high performance, use numeric indexes that match the + // order of Place.databaseSelection + id = row[0] + title = row[1] + isFavorite = row[2] + coordinate = CLLocationCoordinate2D( + latitude: row[3], + longitude: row[4]) + } +} + +// Persistence methods +extension Place: MutablePersistableRecord { + // Update auto-incremented id upon successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +
+ ## List of Record Methods From 7e5390154431b5222b22d97ce2fdab77f1cf6825 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 31 May 2019 08:19:25 +0200 Subject: [PATCH 3/9] New example of record definition --- README.md | 120 +++++++++++++++++++++++++++--------------------------- 1 file changed, 60 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 503a44e10..653a206be 100644 --- a/README.md +++ b/README.md @@ -3473,66 +3473,7 @@ extension Place: MutablePersistableRecord {
- Subclass the Record class - -See the [Record class](#record-class) for more information. - -```swift -class Place: Record { - var id: Int64? - var title: String - var isFavorite: Bool - var coordinate: CLLocationCoordinate2D - - init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { - self.id = id - self.title = title - self.isFavorite = isFavorite - self.coordinate = coordinate - super.init() - } - - /// The table name - override class var databaseTableName: String { - return "place" - } - - /// The table columns - enum Columns: String, ColumnExpression { - case id, title, isFavorite, latitude, longitude - } - - /// Creates a record from a database row - required init(row: Row) { - id = row[Columns.id] - title = row[Columns.title] - isFavorite = row[Columns.isFavorite] - coordinate = CLLocationCoordinate2D( - latitude: row[Columns.latitude], - longitude: row[Columns.longitude]) - super.init(row: row) - } - - /// The values persisted in the database - override func encode(to container: inout PersistenceContainer) { - container[Columns.id] = id - container[Columns.title] = title - container[Columns.isFavorite] = isFavorite - container[Columns.latitude] = coordinate.latitude - container[Columns.longitude] = coordinate.longitude - } - - // Update auto-incremented id upon successful insertion - override func didInsert(with rowID: Int64, for column: String?) { - id = rowID - } -} -``` - -
- -
- Define a struct optimized for fetching performance + Define a plain struct optimized for fetching performance This struct derives is persistence methpds from the standard Encodable protocol (see [Codable Records]), but performs optimized row decoding by accessing database columns with numeric indexes. @@ -3605,6 +3546,65 @@ extension Place: MutablePersistableRecord {
+
+ Subclass the Record class + +See the [Record class](#record-class) for more information. + +```swift +class Place: Record { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D + + init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { + self.id = id + self.title = title + self.isFavorite = isFavorite + self.coordinate = coordinate + super.init() + } + + /// The table name + override class var databaseTableName: String { + return "place" + } + + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, isFavorite, latitude, longitude + } + + /// Creates a record from a database row + required init(row: Row) { + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.isFavorite] + coordinate = CLLocationCoordinate2D( + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) + super.init(row: row) + } + + /// The values persisted in the database + override func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.title] = title + container[Columns.isFavorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude + } + + // Update auto-incremented id upon successful insertion + override func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +
+ ## List of Record Methods From deaf60263d46906aea6e609ffd9c6be6bd90b851 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 31 May 2019 08:44:54 +0200 Subject: [PATCH 4/9] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 489d3f961..7d565ce9b 100644 --- a/TODO.md +++ b/TODO.md @@ -45,6 +45,7 @@ - [ ] FTS: prefix queries - [ ] Test NOT TESTED methods - [ ] A way to stop a ValueObservation observer without waiting for deinit +- [ ] Expose prefetchedAssociations on FetchRequest (remove the QueryInterface special case) Swift 4.2 From 872f394339bb5af15aa04cd77243ec73e701a6a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Jun 2019 11:49:27 +0200 Subject: [PATCH 5/9] Move eager loading of hasMany associations to FetchRequest --- GRDB.xcodeproj/project.pbxproj | 16 -- GRDB/Core/DatabaseValueConvertible.swift | 20 +- GRDB/Core/FetchRequest.swift | 105 +++++++-- GRDB/Core/Row.swift | 19 +- GRDB/Core/SQLRequest.swift | 11 +- GRDB/Core/StatementColumnConvertible.swift | 20 +- ...etchableRecord+QueryInterfaceRequest.swift | 120 ---------- .../Request/QueryInterfaceRequest.swift | 106 ++++++++- .../Row+QueryInterfaceRequest.swift | 219 ------------------ GRDB/Record/FetchableRecord.swift | 27 ++- GRDBCustom.xcodeproj/project.pbxproj | 12 - TODO.md | 1 - .../GRDBTests/CompilationProtocolTests.swift | 2 + Tests/GRDBTests/FetchRequestTests.swift | 61 +++-- Tests/GRDBTests/GRDBTestCase.swift | 8 +- Tests/GRDBTests/SQLRequestTests.swift | 8 +- 16 files changed, 298 insertions(+), 457 deletions(-) delete mode 100644 GRDB/QueryInterface/FetchableRecord+QueryInterfaceRequest.swift delete mode 100644 GRDB/QueryInterface/Row+QueryInterfaceRequest.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index a5bd51109..62383dfdc 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -352,12 +352,6 @@ 5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AA2295BFD6001FF3FF /* TableRecord+QueryInterfaceRequest.swift */; }; 5656A8B12295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AA2295BFD6001FF3FF /* TableRecord+QueryInterfaceRequest.swift */; }; 5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AA2295BFD6001FF3FF /* TableRecord+QueryInterfaceRequest.swift */; }; - 5656A8B32295BFD7001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AB2295BFD6001FF3FF /* Row+QueryInterfaceRequest.swift */; }; - 5656A8B42295BFD7001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AB2295BFD6001FF3FF /* Row+QueryInterfaceRequest.swift */; }; - 5656A8B52295BFD7001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AB2295BFD6001FF3FF /* Row+QueryInterfaceRequest.swift */; }; - 5656A8B62295BFD7001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AC2295BFD6001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */; }; - 5656A8B72295BFD7001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AC2295BFD6001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */; }; - 5656A8B82295BFD7001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AC2295BFD6001FF3FF /* FetchableRecord+QueryInterfaceRequest.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 */; }; @@ -1078,8 +1072,6 @@ 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLAssociation.swift; sourceTree = ""; }; 5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+Association.swift"; sourceTree = ""; }; 5656A8AA2295BFD6001FF3FF /* TableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequest.swift"; sourceTree = ""; }; - 5656A8AB2295BFD6001FF3FF /* Row+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+QueryInterfaceRequest.swift"; sourceTree = ""; }; - 5656A8AC2295BFD6001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequest.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 = ""; }; @@ -1596,11 +1588,9 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( - 5656A8AC2295BFD6001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterface.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5656A8182295B044001FF3FF /* Request */, - 5656A8AB2295BFD6001FF3FF /* Row+QueryInterfaceRequest.swift */, 5656A8142295AF75001FF3FF /* Schema */, 5656A8172295B00E001FF3FF /* SQL */, 5656A8162295AFD6001FF3FF /* SQLGeneration */, @@ -2607,7 +2597,6 @@ files = ( 5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 5656A8B82295BFD7001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */, 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, 5656A8202295B12F001FF3FF /* SQLAssociation.swift in Sources */, @@ -2723,7 +2712,6 @@ 565490CB1D5AE252005622CB /* (null) in Sources */, 563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, - 5656A8B52295BFD7001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, @@ -2777,7 +2765,6 @@ 5605F1641C672E4000235C62 /* Date.swift in Sources */, 5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, - 5656A8B42295BFD7001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */, 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, @@ -2804,7 +2791,6 @@ 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, - 5656A8B72295BFD7001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, @@ -3308,7 +3294,6 @@ 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */, - 5656A8B32295BFD7001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, @@ -3335,7 +3320,6 @@ 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, - 5656A8B62295BFD7001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */, diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 3c0095e4b..e1ddaef50 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -306,8 +306,8 @@ extension DatabaseValueConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: R) throws -> DatabaseValueCursor { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchCursor(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + return try fetchCursor(request.statement, adapter: request.adapter) } /// Returns an array of values fetched from a fetch request. @@ -321,8 +321,8 @@ extension DatabaseValueConvertible { /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchAll(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + return try fetchAll(request.statement, adapter: request.adapter) } /// Returns a single value fetched from a fetch request. @@ -339,8 +339,8 @@ extension DatabaseValueConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { - let (statement, adapter) = try request.prepare(db, forSingleResult: true) - return try fetchOne(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: true) + return try fetchOne(request.statement, adapter: request.adapter) } } @@ -516,8 +516,8 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchCursor(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + return try fetchCursor(request.statement, adapter: request.adapter) } /// Returns an array of optional values fetched from a fetch request. @@ -531,8 +531,8 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: R) throws -> [Wrapped?] { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchAll(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + return try fetchAll(request.statement, adapter: request.adapter) } } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 70b3f2170..4377cb573 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -1,3 +1,40 @@ +// MARK: - PreparedRequest + +/// A PreparedRequest is a request that is ready to be executed. +public struct PreparedRequest { + /// A prepared statement + public var statement: SelectStatement + + /// An eventual adapter for rows fetched by the select statement + public var adapter: RowAdapter? + + /// Support for eager loading of hasMany associations. + var supplementaryFetch: (([Row]) throws -> Void)? + + /// Creates a PreparedRequest. + /// + /// - parameter statement: A prepared statement that is ready to + /// be executed. + /// - parameter adapter: An eventual adapter for rows fetched by the + /// select statement. + public init( + statement: SelectStatement, + adapter: RowAdapter? = nil) + { + self.init(statement: statement, adapter: adapter, supplementaryFetch: nil) + } + + init( + statement: SelectStatement, + adapter: RowAdapter?, + supplementaryFetch: (([Row]) throws -> Void)?) + { + self.statement = statement + self.adapter = adapter + self.supplementaryFetch = supplementaryFetch + } +} + // MARK: - FetchRequest /// The protocol for all requests that run from a single select statement, and @@ -11,16 +48,30 @@ public protocol FetchRequest: DatabaseRegionConvertible { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder - + + // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method + /// This method is deprecated. Use + /// preparedRequest(_:forSingleResult:) instead. + /// /// Returns a tuple that contains a prepared statement that is ready to be /// executed, and an eventual row adapter. /// /// - parameter db: A database connection. - /// - parameter singleResult: A hint that the query should return a single - /// result. Implementations can optionally use - /// this to optimize the prepared statement. + /// - parameter singleResult: A hint that a single result row will be + /// consumed. Implementations can optionally use this to optimize the + /// prepared statement. /// - returns: A prepared statement and an eventual row adapter. func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) + + /// Returns a PreparedRequest made of a prepared statement that is ready to + /// be executed, and an eventual row adapter. + /// + /// - parameter db: A database connection. + /// - parameter singleResult: A hint that a single result row will be + /// consumed. Implementations can optionally use this to optimize the + /// prepared statement. + /// - returns: A prepared request. + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest /// Returns the number of rows fetched by the request. /// @@ -49,9 +100,9 @@ extension FetchRequest { /// /// - parameter db: A database connection. public func fetchCount(_ db: Database) throws -> Int { - let (statement, _) = try prepare(db, forSingleResult: false) - let sql = "SELECT COUNT(*) FROM (\(statement.sql))" - return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)! + let request = try preparedRequest(db, forSingleResult: false) + let sql = "SELECT COUNT(*) FROM (\(request.statement.sql))" + return try Int.fetchOne(db, sql: sql, arguments: request.statement.arguments)! } /// Returns the database region that the request looks into. @@ -61,8 +112,19 @@ extension FetchRequest { /// /// - parameter db: A database connection. public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - let (statement, _) = try prepare(db, forSingleResult: false) - return statement.databaseRegion + let request = try preparedRequest(db, forSingleResult: false) + return request.statement.databaseRegion + } + + public func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + let (statement, adapter) = try prepare(db, forSingleResult: singleResult) + return PreparedRequest(statement: statement, adapter: adapter) + } + + // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method + public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { + let request = try preparedRequest(db, forSingleResult: singleResult) + return (request.statement, request.adapter) } } @@ -83,13 +145,14 @@ public struct AdaptedFetchRequest : FetchRequest { } /// :nodoc: - public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - let (statement, baseAdapter) = try base.prepare(db, forSingleResult: singleResult) - if let baseAdapter = baseAdapter { - return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db))) + public func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + var request = try base.preparedRequest(db, forSingleResult: singleResult) + if let baseAdapter = request.adapter { + request.adapter = try ChainedAdapter(first: baseAdapter, second: adapter(db)) } else { - return try (statement, adapter(db)) + request.adapter = try adapter(db) } + return request } /// :nodoc: @@ -112,22 +175,24 @@ public struct AdaptedFetchRequest : FetchRequest { public struct AnyFetchRequest : FetchRequest { public typealias RowDecoder = T - private let _prepare: (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?) + private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest private let _fetchCount: (Database) throws -> Int private let _databaseRegion: (Database) throws -> DatabaseRegion /// Creates a request that wraps and forwards operations to `request`. public init(_ request: Request) { - _prepare = request.prepare + _preparedRequest = request.preparedRequest _fetchCount = request.fetchCount _databaseRegion = request.databaseRegion } /// Creates a request whose `prepare()` method wraps and forwards /// operations the argument closure. + @available(*, deprecated, message: "Define your own FetchRequest type instead.") public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) { - _prepare = { db, singleResult in - try prepare(db, singleResult) + _preparedRequest = { db, singleResult in + let (statement, adapter) = try prepare(db, singleResult) + return PreparedRequest(statement: statement, adapter: adapter) } _fetchCount = { db in @@ -143,8 +208,8 @@ public struct AnyFetchRequest : FetchRequest { } /// :nodoc: - public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - return try _prepare(db, singleResult) + public func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + return try _preparedRequest(db, singleResult) } /// :nodoc: diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index c204fdeee..e4bf25d51 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -980,8 +980,9 @@ extension Row { /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: R) throws -> RowCursor { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchCursor(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with prefetched associations") + return try fetchCursor(request.statement, adapter: request.adapter) } /// Returns an array of rows fetched from a fetch request. @@ -995,8 +996,10 @@ extension Row { /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: R) throws -> [Row] { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchAll(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + let rows = try fetchAll(request.statement, adapter: request.adapter) + try request.supplementaryFetch?(rows) + return rows } /// Returns a single row fetched from a fetch request. @@ -1010,8 +1013,12 @@ extension Row { /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: R) throws -> Row? { - let (statement, adapter) = try request.prepare(db, forSingleResult: true) - return try fetchOne(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: true) + guard let row = try fetchOne(request.statement, adapter: request.adapter) else { + return nil + } + try request.supplementaryFetch?([row]) + return row } } diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 46efea693..2b6360f16 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -90,8 +90,11 @@ public struct SQLRequest : FetchRequest { /// prepared statement. /// - returns: An SQLRequest public init(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - self.init(literal: SQLLiteral(sql: statement.sql, arguments: statement.arguments), adapter: adapter, cached: cached) + let request = try request.preparedRequest(db, forSingleResult: false) + self.init( + literal: SQLLiteral(sql: request.statement.sql, arguments: request.statement.arguments), + adapter: request.adapter, + cached: cached) } /// Creates a request from an SQLLiteral, and optional row adapter. @@ -128,7 +131,7 @@ public struct SQLRequest : FetchRequest { /// - parameter singleResult: SQLRequest disregards this hint. /// /// :nodoc: - public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { + public func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { let statement: SelectStatement switch cache { case .none: @@ -139,7 +142,7 @@ public struct SQLRequest : FetchRequest { statement = try db.internalCachedSelectStatement(sql: sqlLiteral.sql) } try statement.setArgumentsWithValidation(sqlLiteral.arguments) - return (statement, adapter) + return PreparedRequest(statement: statement, adapter: adapter) } } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index f0a03fac6..9794a8b41 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -305,8 +305,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchCursor(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + return try fetchCursor(request.statement, adapter: request.adapter) } /// Returns an array of values fetched from a fetch request. @@ -320,8 +320,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchAll(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + return try fetchAll(request.statement, adapter: request.adapter) } /// Returns a single value fetched from a fetch request. @@ -335,8 +335,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { - let (statement, adapter) = try request.prepare(db, forSingleResult: true) - return try fetchOne(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: true) + return try fetchOne(request.statement, adapter: request.adapter) } } @@ -512,8 +512,8 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchCursor(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + return try fetchCursor(request.statement, adapter: request.adapter) } /// Returns an array of optional values fetched from a fetch request. @@ -527,8 +527,8 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: R) throws -> [Wrapped?] { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchAll(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + return try fetchAll(request.statement, adapter: request.adapter) } } diff --git a/GRDB/QueryInterface/FetchableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FetchableRecord+QueryInterfaceRequest.swift deleted file mode 100644 index c600e87f1..000000000 --- a/GRDB/QueryInterface/FetchableRecord+QueryInterfaceRequest.swift +++ /dev/null @@ -1,120 +0,0 @@ -extension QueryInterfaceRequest where RowDecoder: FetchableRecord { - /// A cursor over fetched records. - /// - /// let request: QueryInterfaceRequest = ... - /// let players = try request.fetchCursor(db) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RecordCursor { - return try RowDecoder.fetchCursor(db, self) - } - - /// An array of fetched records. - /// - /// let request: QueryInterfaceRequest = ... - /// let players = try request.fetchAll(db) // [Player] - /// - /// - parameter db: A database connection. - /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) - } - - /// The first fetched record. - /// - /// let request: QueryInterfaceRequest = ... - /// let player = try request.fetchOne(db) // Player? - /// - /// - parameter db: A database connection. - /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) - } -} - -extension FetchableRecord { - - // MARK: Fetching From QueryInterfaceRequest - - /// Returns a cursor over records fetched from a fetch request. - /// - /// let request = try Player.all() - /// let players = try Player.fetchCursor(db, request) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - sql: a FetchRequest. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: QueryInterfaceRequest) throws -> RecordCursor { - precondition(request.prefetchedAssociations.isEmpty, "Not implemented: fetchCursor with prefetched associations") - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of records fetched from a query interface request. - /// - /// let request = try Player.all() - /// let players = try Player.fetchAll(db, request) // [Player] - /// - /// - parameters: - /// - db: A database connection. - /// - sql: a FetchRequest. - /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: QueryInterfaceRequest) throws -> [Self] { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - let associations = request.prefetchedAssociations - if associations.isEmpty { - return try fetchAll(statement, adapter: adapter) - } else { - let rows = try Row.fetchAll(statement, adapter: adapter) - try Row.prefetch(db, associations: associations, in: rows) - return rows.map(Self.init(row:)) - } - } - - /// Returns a single record fetched from a query interface request. - /// - /// let request = try Player.filter(key: 1) - /// let player = try Player.fetchOne(db, request) // Player? - /// - /// - parameters: - /// - db: A database connection. - /// - sql: a FetchRequest. - /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: QueryInterfaceRequest) throws -> Self? { - let (statement, adapter) = try request.prepare(db, forSingleResult: true) - let associations = request.prefetchedAssociations - if associations.isEmpty { - return try fetchOne(statement, adapter: adapter) - } else { - guard let row = try Row.fetchOne(statement, adapter: adapter) else { - return nil - } - try Row.prefetch(db, associations: associations, in: [row]) - return Self.init(row: row) - } - } -} diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 22ae9c18e..4012845f0 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -38,10 +38,6 @@ public struct QueryInterfaceRequest: DerivableRequest { init(relation: SQLRelation) { self.init(query: SQLQuery(relation: relation)) } - - var prefetchedAssociations: [SQLAssociation] { - return query.relation.prefetchedAssociations - } } extension QueryInterfaceRequest: FetchRequest { @@ -54,15 +50,26 @@ extension QueryInterfaceRequest: FetchRequest { /// - parameter singleResult: A hint as to whether the query should be optimized for a single result. /// - returns: A prepared statement and an eventual row adapter. /// :nodoc: - public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { + public func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { var query = self.query // Optimize query by setting a limit of 1 when appropriate if singleResult && !query.expectsSingleResult { query.limit = SQLLimit(limit: 1, offset: query.limit?.offset) } - - return try SQLQueryGenerator(query).prepare(db) + + let (statement, adapter) = try SQLQueryGenerator(query).prepare(db) + let associations = query.relation.prefetchedAssociations + if associations.isEmpty { + return PreparedRequest(statement: statement, adapter: adapter) + } else { + return PreparedRequest( + statement: statement, + adapter: adapter, + supplementaryFetch: { rows in + try prefetch(db, associations: associations, in: rows) + }) + } } /// Returns the number of rows fetched by the request. @@ -86,7 +93,7 @@ extension QueryInterfaceRequest: FetchRequest { let association = fifo.removeFirst() // Build the query for prefetched rows. - // CAUTION: Keep this code in sync with Row.prefetch(_:associations:in:) + // CAUTION: Keep this code in sync with prefetch(_:associations:in:) let pivotMappings = try association.pivot.condition.columnMappings(db) let pivotColumns = pivotMappings.map { $0.right } let pivotAlias = TableAlias() @@ -467,3 +474,86 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord { return db.changesCount } } + +// MARK: - Eager loading of hasMany associations + +/// Append rows from prefetched associations into the argument rows. +fileprivate func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws { + guard let firstRow = rows.first else { + // No rows -> no prefetch + return + } + + // CAUTION: Keep this code in sync with QueryInterfaceRequest.databaseRegion(_:) + for association in associations { + let pivotMappings = try association.pivot.condition.columnMappings(db) + + let prefetchedRows: [[DatabaseValue] : [Row]] + do { + // Annotate prefetched rows with pivot columns, so that we can + // group them. + // + // Those pivot columns are necessary when we prefetch + // indirect associations: + // + // // SELECT country.*, passport.citizenId AS grdb_citizenId + // // -- ^ the necessary pivot column + // // FROM country + // // JOIN passport ON passport.countryCode = country.code + // // AND passport.citizenId IN (1, 2, 3) + // Citizen.including(all: Citizen.countries) + // + // Those pivot columns are redundant when we prefetch direct + // associations (maybe we'll remove this redundancy later): + // + // // SELECT *, authorId AS grdb_authorId + // // -- ^ the redundant pivot column + // // FROM book + // // WHERE authorId IN (1, 2, 3) + // Author.including(all: Author.books) + let pivotColumns = pivotMappings.map { $0.right } + let pivotAlias = TableAlias() + let prefetchedRelation = association + .mapPivotRelation { $0.qualified(with: pivotAlias) } + .destinationRelation(fromOriginRows: { _ in rows }) + .annotated(with: pivotColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") }) + prefetchedRows = try QueryInterfaceRequest(relation: prefetchedRelation) + .fetchAll(db) + .grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" }) + // TODO: can we remove those grdb_ columns now that grouping has been done? + } + + let groupingIndexes = firstRow.indexes(ofColumns: pivotMappings.map { $0.left }) + for row in rows { + let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } + let prefetchedRows = prefetchedRows[groupingKey, default: []] + row.prefetchedRows.setRows(prefetchedRows, forKeyPath: association.keyPath) + } + } +} + +extension Array where Element == Row { + /// - precondition: Columns all exist in all rows. All rows have the same + /// columnns, in the same order. + fileprivate func grouped(byDatabaseValuesOnColumns columns: [String]) -> [[DatabaseValue]: [Row]] { + guard let firstRow = first else { + return [:] + } + let indexes = firstRow.indexes(ofColumns: columns) + return Dictionary(grouping: self, by: { row in + indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } + }) + } +} + +extension Row { + /// - precondition: Columns all exist in the row. + fileprivate func indexes(ofColumns columns: [String]) -> [Int] { + return columns.map { column -> Int in + guard let index = index(ofColumn: column) else { + fatalError("Column \(column) is not selected") + } + return index + } + } +} diff --git a/GRDB/QueryInterface/Row+QueryInterfaceRequest.swift b/GRDB/QueryInterface/Row+QueryInterfaceRequest.swift deleted file mode 100644 index 4efd97c5e..000000000 --- a/GRDB/QueryInterface/Row+QueryInterfaceRequest.swift +++ /dev/null @@ -1,219 +0,0 @@ -extension QueryInterfaceRequest where RowDecoder == Row { - - // MARK: Fetching Rows - - /// A cursor over fetched rows. - /// - /// let request: QueryInterfaceRequest = ... - /// let rows = try request.fetchCursor(db) // RowCursor - /// while let row = try rows.next() { // Row - /// let id: Int64 = row[0] - /// let name: String = row[1] - /// } - /// - /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. - /// - /// For the same reason, make sure you make a copy whenever you extract a - /// row for later use: `row.copy()`. - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RowCursor { - return try Row.fetchCursor(db, self) - } - - /// An array of fetched rows. - /// - /// let request: QueryInterfaceRequest = ... - /// let rows = try request.fetchAll(db) - /// - /// - parameter db: A database connection. - /// - returns: An array of fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [Row] { - return try Row.fetchAll(db, self) - } - - /// The first fetched row. - /// - /// let request: QueryInterfaceRequest = ... - /// let row = try request.fetchOne(db) - /// - /// - parameter db: A database connection. - /// - returns: An optional row. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> Row? { - return try Row.fetchOne(db, self) - } -} - -extension Row { - - // MARK: - Fetching From QueryInterfaceRequest - - /// Returns a cursor over rows fetched from a fetch request. - /// - /// let request = Player.all() - /// let rows = try Row.fetchCursor(db, request) // RowCursor - /// while let row = try rows.next() { // Row - /// let id: Int64 = row["id"] - /// let name: String = row["name"] - /// } - /// - /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. - /// - /// For the same reason, make sure you make a copy whenever you extract a - /// row for later use: `row.copy()`. - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A FetchRequest. - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: QueryInterfaceRequest) throws -> RowCursor { - precondition(request.prefetchedAssociations.isEmpty, "Not implemented: fetchCursor with prefetched associations") - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of rows fetched from a fetch request. - /// - /// let request = Player.all() - /// let rows = try Row.fetchAll(db, request) - /// - /// - parameters: - /// - db: A database connection. - /// - request: A FetchRequest. - /// - returns: An array of rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: QueryInterfaceRequest) throws -> [Row] { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - let rows = try fetchAll(statement, adapter: adapter) - - let associations = request.prefetchedAssociations - if associations.isEmpty == false { - try prefetch(db, associations: associations, in: rows) - } - return rows - } - - /// Returns a single row fetched from a fetch request. - /// - /// let request = Player.filter(key: 1) - /// let row = try Row.fetchOne(db, request) - /// - /// - parameters: - /// - db: A database connection. - /// - request: A FetchRequest. - /// - returns: An optional row. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: QueryInterfaceRequest) throws -> Row? { - let (statement, adapter) = try request.prepare(db, forSingleResult: true) - guard let row = try fetchOne(statement, adapter: adapter) else { - return nil - } - - let associations = request.prefetchedAssociations - if associations.isEmpty == false { - try prefetch(db, associations: associations, in: [row]) - } - return row - } - - /// Append rows from prefetched associations into the argument rows. - static func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws { - guard let firstRow = rows.first else { - return - } - - // CAUTION: Keep this code in sync with QueryInterfaceRequest.databaseRegion(_:) - for association in associations { - let pivotMappings = try association.pivot.condition.columnMappings(db) - - let prefetchedRows: [[DatabaseValue] : [Row]] - do { - // Annotate prefetched rows with pivot columns, so that we can - // group them. - // - // Those pivot columns are necessary when we prefetch - // indirect associations: - // - // // SELECT country.*, passport.citizenId AS grdb_citizenId - // // -- ^ the necessary pivot column - // // FROM country - // // JOIN passport ON passport.countryCode = country.code - // // AND passport.citizenId IN (1, 2, 3) - // Citizen.including(all: Citizen.countries) - // - // Those pivot columns are redundant when we prefetch direct - // associations (maybe we'll remove this redundancy later): - // - // // SELECT *, authorId AS grdb_authorId - // // -- ^ the redundant pivot column - // // FROM book - // // WHERE authorId IN (1, 2, 3) - // Author.including(all: Author.books) - let pivotColumns = pivotMappings.map { $0.right } - let pivotAlias = TableAlias() - let prefetchedRelation = association - .mapPivotRelation { $0.qualified(with: pivotAlias) } - .destinationRelation(fromOriginRows: { _ in rows }) - .annotated(with: pivotColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") }) - prefetchedRows = try QueryInterfaceRequest(relation: prefetchedRelation) - .fetchAll(db) - .grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" }) - // TODO: can we remove those grdb_ columns now that grouping has been done? - } - - let groupingIndexes = firstRow.indexes(ofColumns: pivotMappings.map { $0.left }) - for row in rows { - let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } - let prefetchedRows = prefetchedRows[groupingKey, default: []] - row.prefetchedRows.setRows(prefetchedRows, forKeyPath: association.keyPath) - } - } - } -} - -extension Array where Element == Row { - /// - precondition: Columns all exist in all rows. All rows have the same - /// columnns, in the same order. - fileprivate func grouped(byDatabaseValuesOnColumns columns: [String]) -> [[DatabaseValue]: [Row]] { - guard let firstRow = first else { - return [:] - } - let indexes = firstRow.indexes(ofColumns: columns) - return Dictionary(grouping: self, by: { row in - indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } - }) - } -} - -extension Row { - /// - precondition: Columns all exist in the row. - fileprivate func indexes(ofColumns columns: [String]) -> [Int] { - return columns.map { column -> Int in - guard let index = index(ofColumn: column) else { - fatalError("Column \(column) is not selected") - } - return index - } - } -} diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index da3f35872..8add28200 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -276,8 +276,9 @@ extension FetchableRecord { /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: R) throws -> RecordCursor { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchCursor(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with prefetched associations") + return try fetchCursor(request.statement, adapter: request.adapter) } /// Returns an array of records fetched from a fetch request. @@ -291,8 +292,14 @@ extension FetchableRecord { /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { - let (statement, adapter) = try request.prepare(db, forSingleResult: false) - return try fetchAll(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: false) + if let supplementaryFetch = request.supplementaryFetch { + let rows = try Row.fetchAll(request.statement, adapter: request.adapter) + try supplementaryFetch(rows) + return rows.map(Self.init(row:)) + } else { + return try fetchAll(request.statement, adapter: request.adapter) + } } /// Returns a single record fetched from a fetch request. @@ -306,8 +313,16 @@ extension FetchableRecord { /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { - let (statement, adapter) = try request.prepare(db, forSingleResult: true) - return try fetchOne(statement, adapter: adapter) + let request = try request.preparedRequest(db, forSingleResult: true) + if let supplementaryFetch = request.supplementaryFetch { + guard let row = try Row.fetchOne(request.statement, adapter: request.adapter) else { + return nil + } + try supplementaryFetch([row]) + return Self.init(row: row) + } else { + return try fetchOne(request.statement, adapter: request.adapter) + } } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3a9f1b1bf..ec7397276 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -181,8 +181,6 @@ 5656A8602295BD56001FF3FF /* FTS3+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A82F2295BD56001FF3FF /* FTS3+QueryInterface.swift */; }; 5656A8612295BD56001FF3FF /* TableRecord+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8312295BD56001FF3FF /* TableRecord+Association.swift */; }; 5656A8622295BD56001FF3FF /* TableRecord+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8312295BD56001FF3FF /* TableRecord+Association.swift */; }; - 5656A8632295BD56001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8322295BD56001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */; }; - 5656A8642295BD56001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8322295BD56001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */; }; 5656A8652295BD56001FF3FF /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8342295BD56001FF3FF /* BelongsToAssociation.swift */; }; 5656A8662295BD56001FF3FF /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8342295BD56001FF3FF /* BelongsToAssociation.swift */; }; 5656A8672295BD56001FF3FF /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8352295BD56001FF3FF /* HasOneAssociation.swift */; }; @@ -203,8 +201,6 @@ 5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83C2295BD56001FF3FF /* RequestProtocols.swift */; }; 5656A8772295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83D2295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift */; }; 5656A8782295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83D2295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift */; }; - 5656A8792295BD56001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83E2295BD56001FF3FF /* Row+QueryInterfaceRequest.swift */; }; - 5656A87A2295BD56001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83E2295BD56001FF3FF /* Row+QueryInterfaceRequest.swift */; }; 5656A87B2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83F2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift */; }; 5656A87C2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83F2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift */; }; 5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8412295BD56001FF3FF /* SQLAssociation.swift */; }; @@ -818,7 +814,6 @@ 5656A82E2295BD56001FF3FF /* VirtualTableModule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VirtualTableModule.swift; sourceTree = ""; }; 5656A82F2295BD56001FF3FF /* FTS3+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterface.swift"; sourceTree = ""; }; 5656A8312295BD56001FF3FF /* TableRecord+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+Association.swift"; sourceTree = ""; }; - 5656A8322295BD56001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequest.swift"; sourceTree = ""; }; 5656A8342295BD56001FF3FF /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; 5656A8352295BD56001FF3FF /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; 5656A8362295BD56001FF3FF /* AssociationAggregate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = ""; }; @@ -829,7 +824,6 @@ 5656A83B2295BD56001FF3FF /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 5656A83C2295BD56001FF3FF /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 5656A83D2295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequest.swift"; sourceTree = ""; }; - 5656A83E2295BD56001FF3FF /* Row+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+QueryInterfaceRequest.swift"; sourceTree = ""; }; 5656A83F2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; 5656A8412295BD56001FF3FF /* SQLAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLAssociation.swift; sourceTree = ""; }; 5656A8422295BD56001FF3FF /* SQLForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLForeignKeyRequest.swift; sourceTree = ""; }; @@ -1364,11 +1358,9 @@ 5656A8252295BD56001FF3FF /* QueryInterface */ = { isa = PBXGroup; children = ( - 5656A8322295BD56001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */, 5656A82F2295BD56001FF3FF /* FTS3+QueryInterface.swift */, 5656A8282295BD56001FF3FF /* FTS5+QueryInterface.swift */, 5656A8302295BD56001FF3FF /* Request */, - 5656A83E2295BD56001FF3FF /* Row+QueryInterfaceRequest.swift */, 5656A82C2295BD56001FF3FF /* Schema */, 5656A8402295BD56001FF3FF /* SQL */, 5656A8292295BD56001FF3FF /* SQLGeneration */, @@ -2116,7 +2108,6 @@ 5656A87C2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */, F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */, F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */, - 5656A87A2295BD56001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */, 56E9FAC52210468500C703A8 /* SQLInterpolation.swift in Sources */, 563EF421215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80161CFB2876003DC1BA /* Row.swift in Sources */, @@ -2206,7 +2197,6 @@ F3BA800E1CFB2876003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80191CFB2876003DC1BA /* Statement.swift in Sources */, 5656A8962295BD56001FF3FF /* SQLCollatedExpression.swift in Sources */, - 5656A8642295BD56001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */, 56B964A21DA51B4C0002DA19 /* FTS5.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2448,7 +2438,6 @@ 5656A87B2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */, F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */, F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */, - 5656A8792295BD56001FF3FF /* Row+QueryInterfaceRequest.swift in Sources */, 56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */, 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */, @@ -2538,7 +2527,6 @@ F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80751CFB2E55003DC1BA /* Statement.swift in Sources */, 5656A8952295BD56001FF3FF /* SQLCollatedExpression.swift in Sources */, - 5656A8632295BD56001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift in Sources */, 56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/TODO.md b/TODO.md index 7d565ce9b..489d3f961 100644 --- a/TODO.md +++ b/TODO.md @@ -45,7 +45,6 @@ - [ ] FTS: prefix queries - [ ] Test NOT TESTED methods - [ ] A way to stop a ValueObservation observer without waiting for deinit -- [ ] Expose prefetchedAssociations on FetchRequest (remove the QueryInterface special case) Swift 4.2 diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index ef810ff89..8aa0b9870 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -110,7 +110,9 @@ private class UserPersistableRecord2 : PersistableRecord { private struct UserRowRequest : FetchRequest { struct CustomType { } typealias RowDecoder = CustomType + // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { preconditionFailure() } } // MARK: - FetchableRecord diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift index e0dfb6f7f..29a0974e5 100644 --- a/Tests/GRDBTests/FetchRequestTests.swift +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -7,11 +7,38 @@ import XCTest class FetchRequestTests: GRDBTestCase { + // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method + func testDeprecatedPrepareMethod() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + // This method is deprecated but we must support it + func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement(sql: "SELECT * FROM table1"), nil) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES") + try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let rows = try request.fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM table1") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0], ["id": 1]) + XCTAssertEqual(rows[1], ["id": 2]) + } + } + func testRequestFetchRows() throws { struct CustomRequest : FetchRequest { typealias RowDecoder = Row - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement(sql: "SELECT * FROM table1"), nil) + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM table1")) } } @@ -35,8 +62,8 @@ class FetchRequestTests: GRDBTestCase { func testRequestFetchValues() throws { struct CustomRequest : FetchRequest { typealias RowDecoder = Int - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement(sql: "SELECT id FROM table1"), nil) + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT id FROM table1")) } } @@ -63,8 +90,8 @@ class FetchRequestTests: GRDBTestCase { } struct CustomRequest : FetchRequest { typealias RowDecoder = CustomRecord - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement(sql: "SELECT id FROM table1"), nil) + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT id FROM table1")) } } @@ -88,8 +115,8 @@ class FetchRequestTests: GRDBTestCase { func testRequestFetchCount() throws { struct CustomRequest : FetchRequest { typealias RowDecoder = Row - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement(sql: "SELECT * FROM table1"), nil) + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM table1")) } } @@ -111,8 +138,8 @@ class FetchRequestTests: GRDBTestCase { func testRequestCustomizedFetchCount() throws { struct CustomRequest : FetchRequest { typealias RowDecoder = Row - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement(sql: "INVALID"), nil) + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + return try PreparedRequest(statement: db.makeSelectStatement(sql: "INVALID")) } func fetchCount(_ db: Database) throws -> Int { @@ -140,11 +167,11 @@ class FetchRequestTests: GRDBTestCase { func testSingleResultHint() throws { struct CustomRequest: FetchRequest { typealias RowDecoder = T - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { if singleResult { - return try (db.makeSelectStatement(sql: "SELECT 'single' AS hint"), nil) + return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT 'single' AS hint")) } else { - return try (db.makeSelectStatement(sql: "SELECT 'multiple' AS hint"), nil) + return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT 'multiple' AS hint")) } } } @@ -342,9 +369,9 @@ class FetchRequestTests: GRDBTestCase { func testSingleResultHintIsNotUsedForDefaultFetchCount() throws { struct CustomRequest: FetchRequest { typealias RowDecoder = Void - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { if singleResult { fatalError("not implemented") } - return try (db.makeSelectStatement(sql: "SELECT 'multiple'"), nil) + return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT 'multiple'")) } } @@ -359,9 +386,9 @@ class FetchRequestTests: GRDBTestCase { func testSingleResultHintIsNotUsedForDefaultDatabaseRegion() throws { struct CustomRequest: FetchRequest { typealias RowDecoder = Void - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { if singleResult { fatalError("not implemented") } - return try (db.makeSelectStatement(sql: "SELECT * FROM multiple"), nil) + return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM multiple")) } } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index f16109cfa..4673f1f8b 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -146,8 +146,8 @@ class GRDBTestCase: XCTestCase { // Compare SQL strings (ignoring leading and trailing white space and semicolons. func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { - let (statement, _) = try request.prepare(db, forSingleResult: false) - try statement.makeCursor().next() + let request = try request.preparedRequest(db, forSingleResult: false) + try request.statement.makeCursor().next() assertEqualSQL(lastSQLQuery, sql, file: file, line: line) } @@ -160,8 +160,8 @@ class GRDBTestCase: XCTestCase { func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { return try! databaseReader.unsafeRead { db in - let (statement, _) = try request.prepare(db, forSingleResult: false) - try statement.makeCursor().next() + let request = try request.preparedRequest(db, forSingleResult: false) + try request.statement.makeCursor().next() return lastSQLQuery } } diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index fb05a6d94..ddc70a2ed 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -54,10 +54,10 @@ class SQLRequestTests: GRDBTestCase { func testRequestInitializer() throws { struct CustomRequest: FetchRequest { typealias RowDecoder = Row - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { let statement = try db.makeSelectStatement(sql: "SELECT ? AS a, ? AS b") statement.arguments = [1, "foo"] - return (statement, nil) + return PreparedRequest(statement: statement) } } let dbQueue = try makeDatabaseQueue() @@ -73,9 +73,9 @@ class SQLRequestTests: GRDBTestCase { func testRequestInitializerAndSingleResultHint() throws { struct CustomRequest: FetchRequest { typealias RowDecoder = Row - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { if singleResult { fatalError("not implemented") } - return try (db.makeSelectStatement(sql: "SELECT 'multiple'"), nil) + return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT 'multiple'")) } } let dbQueue = try makeDatabaseQueue() From 92c13c3ea80c0201407306c90ea028244b89c986 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Jun 2019 17:01:42 +0200 Subject: [PATCH 6/9] Documentation --- GRDB/Core/FetchRequest.swift | 4 ++++ GRDB/Core/Row.swift | 2 +- GRDB/QueryInterface/Request/QueryInterfaceRequest.swift | 1 + GRDB/Record/FetchableRecord.swift | 2 +- 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 4377cb573..cb2435eb4 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -116,12 +116,16 @@ extension FetchRequest { return request.statement.databaseRegion } + // Support for legacy requests which only define prepare(_:forSingleResult:) + // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method + /// :nodoc: public func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { let (statement, adapter) = try prepare(db, forSingleResult: singleResult) return PreparedRequest(statement: statement, adapter: adapter) } // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method + /// :nodoc: public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { let request = try preparedRequest(db, forSingleResult: singleResult) return (request.statement, request.adapter) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index e4bf25d51..1a60b8b1f 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -981,7 +981,7 @@ extension Row { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: R) throws -> RowCursor { let request = try request.preparedRequest(db, forSingleResult: false) - precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with prefetched associations") + precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch") return try fetchCursor(request.statement, adapter: request.adapter) } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 4012845f0..15fc004b1 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -63,6 +63,7 @@ extension QueryInterfaceRequest: FetchRequest { if associations.isEmpty { return PreparedRequest(statement: statement, adapter: adapter) } else { + // Eager loading of prefetched associations return PreparedRequest( statement: statement, adapter: adapter, diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 8add28200..49364f2be 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -277,7 +277,7 @@ extension FetchableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: R) throws -> RecordCursor { let request = try request.preparedRequest(db, forSingleResult: false) - precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with prefetched associations") + precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch") return try fetchCursor(request.statement, adapter: request.adapter) } From 50993052577e349bb18ddfb90c4429ef04de7eef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Jun 2019 17:11:09 +0200 Subject: [PATCH 7/9] Documentation --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 653a206be..26d198cbc 100644 --- a/README.md +++ b/README.md @@ -4725,8 +4725,9 @@ protocol FetchRequest: DatabaseRegionConvertible { /// The type that tells how fetched rows should be decoded associatedtype RowDecoder - /// A tuple that contains a prepared statement, and an eventual row adapter. - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) + /// Returns a PreparedRequest made of a prepared statement that is ready to + /// be executed, and an eventual row adapter. + func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest /// The number of rows fetched by the request. func fetchCount(_ db: Database) throws -> Int @@ -4735,7 +4736,7 @@ protocol FetchRequest: DatabaseRegionConvertible { When the `RowDecoder` associated type is [Row](#fetching-rows), or a [value](#value-queries), or a type that conforms to [FetchableRecord], the request can fetch: see [Fetching From Custom Requests](#fetching-from-custom-requests) below. -The `prepare(_:forSingleResult:)` method accepts a database connection, a `singleResult` hint, and returns a prepared statement and an optional row adapter. Conforming types can use the `singleResult` hint as an optimization opportunity, and return a [prepared statement](#prepared-statements) that fetches at most one row, with a `LIMIT` SQL clause, when possible. The optional row adapter helps presenting the fetched rows in the way expected by the row decoders (see [row adapters](#row-adapters)). +The `preparedRequest(_:forSingleResult:)` method accepts a database connection, a `singleResult` hint, and returns a "prepared request" made of a [prepared statement](#prepared-statements) and an optional [row adapter](#row-adapters). Conforming types can use the `singleResult` hint as an optimization opportunity, and return a statement that fetches at most one row, with a `LIMIT` SQL clause, when possible. The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. From 91ff9ce0b8b9a086b508546ebe523c6fc5100079 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Jun 2019 17:16:04 +0200 Subject: [PATCH 8/9] Documentation --- GRDB/Core/FetchRequest.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index cb2435eb4..fd7474d56 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -37,8 +37,8 @@ public struct PreparedRequest { // MARK: - FetchRequest -/// The protocol for all requests that run from a single select statement, and -/// tell how fetched rows should be interpreted. +/// The protocol for all requests that fetch database rows, and tell how those +/// rows should be interpreted. /// /// struct Player: FetchableRecord { ... } /// let request: ... // Some FetchRequest that fetches Player @@ -51,7 +51,7 @@ public protocol FetchRequest: DatabaseRegionConvertible { // TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method /// This method is deprecated. Use - /// preparedRequest(_:forSingleResult:) instead. + /// `preparedRequest(_:forSingleResult:)` instead. /// /// Returns a tuple that contains a prepared statement that is ready to be /// executed, and an eventual row adapter. From 1416c6e179f56f53f951753b5fb61df169d0ed79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Jun 2019 17:20:20 +0200 Subject: [PATCH 9/9] CHANGELOG --- CHANGELOG.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fada449ed..76b57122c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#537](https://github.com/groue/GRDB.swift/pull/537): Remove useless parenthesis from generated SQL - [#538](https://github.com/groue/GRDB.swift/pull/538) by [@Timac](https://github.com/Timac): Add FAQ to clarify "Wrong number of statement arguments" error with "like '%?%'" - [#539](https://github.com/groue/GRDB.swift/pull/539): Expose joining methods of both requests and associations +- [#542](https://github.com/groue/GRDB.swift/pull/542): Move eager loading of hasMany associations to FetchRequest ### Documentation Diff @@ -61,6 +62,22 @@ The [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes. The [Examples of Record Definitions](README.md#examples-of-record-definitions) has been extended with a sample record optimized for fetching performance. +### API Diff + +```diff ++struct PreparedRequest { ++ var statement: SelectStatement ++ var adapter: RowAdapter? ++ init(statement: SelectStatement, adapter: RowAdapter? = nil) ++} + + protocol FetchRequest { ++ // deprecated + func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) ++ func preparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest + } +``` + ## 4.0.1