mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-26 04:07:50 +00:00
Merge pull request #328 from groue/GRDB3-DatabaseRequest
Allow observation of complex fetching strategies
This commit is contained in:
3 files changed
+167
-84
No files matched your search
@@ -1,39 +1,39 @@
|
||||
/// The protocol for all types that define a way to fetch database content.
|
||||
///
|
||||
/// struct Player: FetchableRecord { ... }
|
||||
/// let request: ... // Some FetchRequest that fetches Player
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchOne(db) // Player?
|
||||
public protocol FetchRequest {
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
associatedtype RowDecoder
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// Default implementation builds a naive SQL query based on the statement
|
||||
/// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// Adopting types can refine this countRequest method and return more
|
||||
/// efficient SQL.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
|
||||
/// The database region that the request looks into.
|
||||
///
|
||||
/// This method has a default implementation.
|
||||
// MARK: - DatabaseRequest
|
||||
|
||||
/// The protocol for all types that request database values.
|
||||
public protocol DatabaseRequest {
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
/// The number of rows fetched by the request.
|
||||
// MARK: - SelectStatementRequest
|
||||
|
||||
/// The protocol for all requests that run from a single select statement.
|
||||
public protocol SelectStatementRequest: DatabaseRequest {
|
||||
/// Returns a tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A prepared statement and an eventual row adapter.
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// The default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method:
|
||||
/// `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// Adopting types can refine this method in order to use more
|
||||
/// efficient SQL.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
extension SelectStatementRequest {
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// This default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
@@ -45,7 +45,10 @@ extension FetchRequest {
|
||||
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// This default implementation returns a region built from the statement
|
||||
/// returned by the `prepare` method.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
@@ -54,6 +57,21 @@ extension FetchRequest {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FetchRequest
|
||||
|
||||
/// The protocol for all requests that run from a single select statement, and
|
||||
/// tell how fetched rows should be interpreted.
|
||||
///
|
||||
/// struct Player: FetchableRecord { ... }
|
||||
/// let request: ... // Some FetchRequest that fetches Player
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchOne(db) // Player?
|
||||
public protocol FetchRequest: SelectStatementRequest {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
/// Returns a request bound to type T.
|
||||
///
|
||||
@@ -78,6 +96,8 @@ extension FetchRequest {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AdaptedFetchRequest
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
@@ -113,6 +133,8 @@ public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AnyFetchRequest
|
||||
|
||||
/// A type-erased FetchRequest.
|
||||
///
|
||||
/// An AnyFetchRequest forwards its operations to an underlying request,
|
||||
@@ -124,14 +146,14 @@ public struct AnyFetchRequest<T> : FetchRequest {
|
||||
private let _fetchCount: (Database) throws -> Int
|
||||
private let _fetchedRegion: (Database) throws -> DatabaseRegion
|
||||
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init<Request: FetchRequest>(_ request: Request) {
|
||||
_prepare = request.prepare
|
||||
_fetchCount = request.fetchCount
|
||||
_fetchedRegion = request.fetchedRegion
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// Creates a request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = { db in
|
||||
@@ -166,24 +188,22 @@ public struct AnyFetchRequest<T> : FetchRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Request built from raw SQL.
|
||||
// MARK: - SQLRequest
|
||||
|
||||
/// A FetchRequest built from raw SQL.
|
||||
public struct SQLRequest<T> : FetchRequest {
|
||||
public typealias RowDecoder = T
|
||||
|
||||
public let sql: String
|
||||
public let arguments: StatementArguments?
|
||||
public let adapter: RowAdapter?
|
||||
public var sql: String
|
||||
public var arguments: StatementArguments?
|
||||
public var adapter: RowAdapter?
|
||||
private let cache: Cache?
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = SQLRequest<Player>("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let player = try request.fetchOne(db) // Player?
|
||||
/// }
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
@@ -196,18 +216,7 @@ public struct SQLRequest<T> : FetchRequest {
|
||||
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
|
||||
}
|
||||
|
||||
/// Creates a new SQL request from any other fetch request.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Player.filter(Column("name") == "Arthur")
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let sqlRequest = try SQLRequest(db, request: request) // SQLRequest<Player>
|
||||
/// print(sqlRequest.sql)
|
||||
/// // Prints "SELECT * FROM players WHERE name = ?"
|
||||
/// print(sqlRequest.arguments)
|
||||
/// // Prints ["Arthur"]
|
||||
/// }
|
||||
/// Creates an SQL request from any other fetch request.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
@@ -220,17 +229,17 @@ public struct SQLRequest<T> : FetchRequest {
|
||||
self.init(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
|
||||
}
|
||||
|
||||
/// Creates a new SQL request from an SQL string, optional arguments, and
|
||||
/// Creates an SQL request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// The *cache* arguments should be `.internal` for requests generated by
|
||||
/// GRDB, and `.public` for requests generated by the user.
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cache: Optional statement cache name.
|
||||
/// - statementCacheName: Optional statement cache name.
|
||||
/// - returns: A SQLRequest
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
|
||||
self.sql = sql
|
||||
|
||||
@@ -12,27 +12,27 @@ public struct QueryInterfaceRequest<T> {
|
||||
extension QueryInterfaceRequest : FetchRequest {
|
||||
public typealias RowDecoder = T
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// Returns a tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// - returns: A prepared statement and an eventual row adapter.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try query.prepare(db)
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try query.fetchCount(db)
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try query.fetchedRegion(db)
|
||||
|
||||
@@ -3694,7 +3694,7 @@ try request.fetchCount(db) // Int
|
||||
try Player.fetchAll(db, "SELECT ...") // [Player]
|
||||
```
|
||||
|
||||
But you may prefer to bring some elegance back in, and build custom requests on top of the `FetchRequest` protocol:
|
||||
But you may prefer to bring some elegance back in, and build custom requests:
|
||||
|
||||
```swift
|
||||
// No custom SQL in sight
|
||||
@@ -3711,39 +3711,104 @@ Player.customRequest(...).rx
|
||||
})
|
||||
```
|
||||
|
||||
- [DatabaseRequest Protocol](#databaserequest-protocol)
|
||||
- [SelectStatementRequest Protocol](#selectstatementrequest-protocol)
|
||||
- [FetchRequest Protocol](#fetchrequest-protocol)
|
||||
- [Building Custom Requests](#building-custom-requests)
|
||||
- [Fetching From Custom Requests](#fetching-from-custom-requests)
|
||||
|
||||
### FetchRequest Protocol
|
||||
|
||||
**FetchRequest is the protocol for all types that define a way to fetch database rows:**
|
||||
### DatabaseRequest Protocol
|
||||
|
||||
**DatabaseRequest** is the highest-level protocol for all types that request database values. It does not tell how values are fetched, but it allows database observation tools ([transaction observers](#transactionobserver-protocol) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB)) the ability to notify changes in the request content.
|
||||
|
||||
```swift
|
||||
protocol FetchRequest {
|
||||
/// The type that tells how fetched rows should be decoded
|
||||
associatedtype RowDecoder
|
||||
protocol DatabaseRequest {
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
```
|
||||
|
||||
**You'll use DatabaseRequest when you want to encapsulate your most complex fetching strategies.**
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
struct LibraryRequest: DatabaseRequest {
|
||||
func fetchAll(_ db: Database) throws -> [(Author, [Books])] {
|
||||
let authors = try Author.fetchAll(db)
|
||||
let books = try Dictionary(
|
||||
grouping: Book.fetchAll(db),
|
||||
by: { book in book.authorId })
|
||||
return authors.map { author in (author, books[author.id]!) }
|
||||
}
|
||||
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let authorsRegion = try Author.all().fetchedRegion(db)
|
||||
let booksRegion = try Book.all().fetchedRegion(db)
|
||||
return authorsRegion.union(booksRegion)
|
||||
}
|
||||
}
|
||||
|
||||
// Track library content with RxGRDB
|
||||
let request = LibraryRequest()
|
||||
dbQueue.rx
|
||||
.fetchTokens(in: [request])
|
||||
.mapFetch { db in try request.fetchAll(db) }
|
||||
.subscribe(onNext: { library: [(Author, [Books])] in
|
||||
print("Library has changed.")
|
||||
})
|
||||
```
|
||||
|
||||
See [DatabaseRegion](https://groue.github.io/GRDB.swift/docs/2.10/Structs/DatabaseRegion.html) reference for more information.
|
||||
|
||||
|
||||
### SelectStatementRequest Protocol
|
||||
|
||||
**SelectStatementRequest** is the protocol for all requests that run a single select statement:
|
||||
|
||||
```swift
|
||||
protocol SelectStatementRequest: DatabaseRequest {
|
||||
/// A tuple that contains a prepared statement, and an eventual row adapter.
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
|
||||
/// The database region that the request looks into.
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
```
|
||||
|
||||
The `RowDecoder` associated type tells a request how to decode rows. It can be any type, but not all types have built-in support. See [Fetching From Custom Requests](#fetching-from-custom-requests) below.
|
||||
|
||||
The `prepare` method returns a prepared statement and an optional row adapter. The [prepared statement](#prepared-statements) tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see [row adapter](#row-adapters)).
|
||||
|
||||
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.
|
||||
|
||||
The `fetchedRegion` method helps [transaction observers](#transactionobserver-protocol) efficiently track modifications in requests results. It has a default implementation that you can't really improve in the current state of the API.
|
||||
The `fetchedRegion` method inherited from [DatabaseRequest](#databaserequest-protocol) is also given a default implementation, based on the statement returned by `prepare`.
|
||||
|
||||
There are few use cases for SelectStatementRequest. Usually, your custom requests will adopt its derivative [FetchRequest](#fetchrequest-protocol), introduced below:
|
||||
|
||||
|
||||
### FetchRequest Protocol
|
||||
|
||||
**FetchRequest** is the protocol for all requests that run from a single select statement, and know how fetched rows should be interpreted:
|
||||
|
||||
```swift
|
||||
protocol FetchRequest: SelectStatementRequest {
|
||||
/// The type that tells how fetched rows should be decoded
|
||||
associatedtype RowDecoder
|
||||
}
|
||||
```
|
||||
|
||||
The `RowDecoder` associated type can be any type. Yet, not all types have built-in support: see [Fetching From Custom Requests](#fetching-from-custom-requests) below.
|
||||
|
||||
FetchRequest is adopted, for example, by [query interface requests](#requests):
|
||||
|
||||
```swift
|
||||
// A FetchRequest whose RowDecoder associated type is Player:
|
||||
let request = Player.all()
|
||||
```
|
||||
|
||||
|
||||
### Building Custom Requests
|
||||
|
||||
**To build custom requests**, you can create your own type that adopts the [FetchRequest](#fetchrequest-protocol) protocol, derive requests from other requests, or use one of the built-in concrete types:
|
||||
**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts one of the request protocols described above ([FetchRequest](#fetchrequest-protocol), [SelectStatementRequest](#selectstatementrequest-protocol), or [DatabaseRequest](#databaserequest-protocol)).
|
||||
|
||||
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.10/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
|
||||
|
||||
@@ -3776,22 +3841,31 @@ The `fetchedRegion` method helps [transaction observers](#transactionobserver-pr
|
||||
|
||||
### Fetching From Custom Requests
|
||||
|
||||
A fetch request knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [records](#records)):
|
||||
A type adopting [FetchRequest](#fetchrequest-protocol) knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [FetchableRecord]):
|
||||
|
||||
```swift
|
||||
let rowRequest = ... // Some TypedRequest that fetches Row
|
||||
let rowRequest = ... // Some FetchRequest that fetches Row
|
||||
try request.fetchCursor(db) // A cursor of rows
|
||||
|
||||
let playerRequest = ... // Some TypedRequest that fetches Player
|
||||
let playerRequest = ... // Some FetchRequest that fetches Player
|
||||
try request.fetchAll(db) // [Player]
|
||||
|
||||
let intRequest = ... // Some TypedRequest that fetches Int
|
||||
let intRequest = ... // Some FetchRequest that fetches Int
|
||||
try request.fetchOne(db) // Int?
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
let playerRequest = SQLRequest<Player>(
|
||||
"SELECT * FROM players WHERE color = ?"
|
||||
arguments: [color])
|
||||
try request.fetchAll(db) // [Player]
|
||||
```
|
||||
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods.
|
||||
|
||||
When RowDecoder is another type, you can write your own convenience methods.
|
||||
When the RowDecoder type associated with the FetchRequest is not Row, DatabaseValueConvertible, or FetchableRecord, you can write your own convenience methods in an extension of the FetchRequest protocol.
|
||||
|
||||
|
||||
Application Tools
|
||||
|
||||
Reference in new issue
Block a user