mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
Merge branch 'development' into dev/SQLite-3.28.0
# Conflicts: # CHANGELOG.md
This commit is contained in:
commit
30812792df
18 files changed
+423
-478
No files matched your search
@@ -55,11 +55,30 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
|
||||
- [#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
|
||||
- [#540](https://github.com/groue/GRDB.swift/pull/540): Update SQLite to 3.28.0 (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib))
|
||||
- [#542](https://github.com/groue/GRDB.swift/pull/542): Move eager loading of hasMany associations to FetchRequest
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
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.
|
||||
|
||||
### 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
|
||||
|
||||
|
||||
@@ -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 = "<group>"; };
|
||||
5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+Association.swift"; sourceTree = "<group>"; };
|
||||
5656A8AA2295BFD6001FF3FF /* TableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequest.swift"; sourceTree = "<group>"; };
|
||||
5656A8AB2295BFD6001FF3FF /* Row+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+QueryInterfaceRequest.swift"; sourceTree = "<group>"; };
|
||||
5656A8AC2295BFD6001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequest.swift"; sourceTree = "<group>"; };
|
||||
5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
|
||||
5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = "<group>"; };
|
||||
5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = "<group>"; };
|
||||
@@ -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 */,
|
||||
|
||||
@@ -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<R: FetchRequest>(_ db: Database, _ request: R) throws -> DatabaseValueCursor<Self> {
|
||||
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<R: FetchRequest>(_ 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<R: FetchRequest>(_ 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<R: FetchRequest>(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
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<R: FetchRequest>(_ 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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,44 @@
|
||||
// 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
|
||||
/// 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
|
||||
@@ -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,23 @@ 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
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,13 +149,14 @@ public struct AdaptedFetchRequest<Base: FetchRequest> : 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 +179,24 @@ public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
|
||||
public struct AnyFetchRequest<T> : 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: FetchRequest>(_ 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 +212,8 @@ public struct AnyFetchRequest<T> : 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:
|
||||
|
||||
+13
-6
@@ -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<R: FetchRequest>(_ 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 supplementary fetch")
|
||||
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<R: FetchRequest>(_ 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<R: FetchRequest>(_ 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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,8 +90,11 @@ public struct SQLRequest<T> : FetchRequest {
|
||||
/// prepared statement.
|
||||
/// - returns: An SQLRequest
|
||||
public init<Request: FetchRequest>(_ 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<T> : 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<T> : FetchRequest {
|
||||
statement = try db.internalCachedSelectStatement(sql: sqlLiteral.sql)
|
||||
}
|
||||
try statement.setArgumentsWithValidation(sqlLiteral.arguments)
|
||||
return (statement, adapter)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor<Self> {
|
||||
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<R: FetchRequest>(_ 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<R: FetchRequest>(_ 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<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor<Wrapped> {
|
||||
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<R: FetchRequest>(_ 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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
extension QueryInterfaceRequest where RowDecoder: FetchableRecord {
|
||||
/// A cursor over fetched records.
|
||||
///
|
||||
/// let request: QueryInterfaceRequest<Player> = ...
|
||||
/// 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<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched records.
|
||||
///
|
||||
/// let request: QueryInterfaceRequest<Player> = ...
|
||||
/// 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<Player> = ...
|
||||
/// 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<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> RecordCursor<Self> {
|
||||
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<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) 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<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,10 +38,6 @@ public struct QueryInterfaceRequest<T>: DerivableRequest {
|
||||
init(relation: SQLRelation) {
|
||||
self.init(query: SQLQuery(relation: relation))
|
||||
}
|
||||
|
||||
var prefetchedAssociations: [SQLAssociation] {
|
||||
return query.relation.prefetchedAssociations
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: FetchRequest {
|
||||
@@ -54,15 +50,27 @@ 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 {
|
||||
// Eager loading of prefetched associations
|
||||
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 +94,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 +475,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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
extension QueryInterfaceRequest where RowDecoder == Row {
|
||||
|
||||
// MARK: Fetching Rows
|
||||
|
||||
/// A cursor over fetched rows.
|
||||
///
|
||||
/// let request: QueryInterfaceRequest<Row> = ...
|
||||
/// 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<Row> = ...
|
||||
/// 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<Row> = ...
|
||||
/// 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<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) 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<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) 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<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<R: FetchRequest>(_ db: Database, _ request: R) throws -> RecordCursor<Self> {
|
||||
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 supplementary fetch")
|
||||
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<R: FetchRequest>(_ 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<R: FetchRequest>(_ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 = "<group>"; };
|
||||
5656A82F2295BD56001FF3FF /* FTS3+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
5656A8312295BD56001FF3FF /* TableRecord+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+Association.swift"; sourceTree = "<group>"; };
|
||||
5656A8322295BD56001FF3FF /* FetchableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequest.swift"; sourceTree = "<group>"; };
|
||||
5656A8342295BD56001FF3FF /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = "<group>"; };
|
||||
5656A8352295BD56001FF3FF /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = "<group>"; };
|
||||
5656A8362295BD56001FF3FF /* AssociationAggregate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = "<group>"; };
|
||||
@@ -829,7 +824,6 @@
|
||||
5656A83B2295BD56001FF3FF /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = "<group>"; };
|
||||
5656A83C2295BD56001FF3FF /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = "<group>"; };
|
||||
5656A83D2295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequest.swift"; sourceTree = "<group>"; };
|
||||
5656A83E2295BD56001FF3FF /* Row+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+QueryInterfaceRequest.swift"; sourceTree = "<group>"; };
|
||||
5656A83F2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = "<group>"; };
|
||||
5656A8412295BD56001FF3FF /* SQLAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLAssociation.swift; sourceTree = "<group>"; };
|
||||
5656A8422295BD56001FF3FF /* SQLForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLForeignKeyRequest.swift; sourceTree = "<group>"; };
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -3463,6 +3472,80 @@ extension Place: MutablePersistableRecord {
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Define a plain struct optimized for fetching performance</summary>
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Subclass the <code>Record</code> class</summary>
|
||||
|
||||
@@ -3490,14 +3573,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 +3591,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
|
||||
}
|
||||
@@ -4642,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
|
||||
@@ -4652,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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<T>: 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"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,8 +146,8 @@ class GRDBTestCase: XCTestCase {
|
||||
|
||||
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
|
||||
func assertEqualSQL<Request: FetchRequest>(_ 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<Request: FetchRequest>(_ 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user