mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e9eed9374 | ||
|
|
383581938a | ||
|
|
df50da9024 | ||
|
|
d3a65303a1 | ||
|
|
9a2bf923d2 | ||
|
|
9b27c0c651 | ||
|
|
2af85e7347 | ||
|
|
071f0f4443 | ||
|
|
903e8c96aa | ||
|
|
79a5fb9c15 | ||
|
|
46ef4b27bb | ||
|
|
1838797d38 | ||
|
|
c7d500b8ba | ||
|
|
95a09cb644 |
No files matched your search
+65
-2
@@ -1,6 +1,69 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## 2.5.0
|
||||
|
||||
Released January 11, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.4.2...v2.5.0)
|
||||
|
||||
### Fixed
|
||||
|
||||
- [Transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) used to be notified of some database changes they were not interested into, in case of complex statements with side effects (foreign key cascades or sql triggers). This has been fixed.
|
||||
|
||||
|
||||
### New
|
||||
|
||||
- The query interface has learned to build requests from any key (primary keys and unique keys) ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#fetching-by-key)):
|
||||
|
||||
```swift
|
||||
// SELECT * FROM players WHERE id = 1
|
||||
let request = Player.filter(key: 1)
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
|
||||
// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
|
||||
let request = Country.filter(keys: ["FR", "US"])
|
||||
let countries = try request.fetchAll(db) // [Country]
|
||||
|
||||
// SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
let request = Player.filter(key: ["email": "arthur@example.com"])
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
```
|
||||
|
||||
This feature has been introduced in order to ease the use of [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
|
||||
|
||||
```swift
|
||||
// New
|
||||
Player.filter(key: 1).rx
|
||||
.fetchOne(in: dbQueue)
|
||||
.subscribe(onNext: { player: Player? in
|
||||
print("Player 1 has changed")
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
extension TableMapping {
|
||||
+ static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self>
|
||||
+ static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible
|
||||
+ static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self>
|
||||
+ static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self>
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where T: TableMapping {
|
||||
+ func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T>
|
||||
+ func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible
|
||||
+ func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T>
|
||||
+ func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T>
|
||||
}
|
||||
|
||||
extension RowConvertible where Self: TableMapping {
|
||||
- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self?
|
||||
+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.4.2
|
||||
|
||||
Released January 6, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.4.1...v2.4.2)
|
||||
@@ -125,14 +188,14 @@ Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
extension Request {
|
||||
extension Request {
|
||||
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
|
||||
}
|
||||
struct SQLRequest {
|
||||
+ let sql: String
|
||||
+ let arguments: StatementArguments?
|
||||
+ let adapter: RowAdapter?
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout v2.4.2
|
||||
git checkout v2.5.0
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
|
||||
|
||||
@@ -497,7 +497,7 @@ Build a `value BETWEEN min AND max` expression from Swift ranges:
|
||||
|
||||
#### The COUNT Function
|
||||
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) functions:
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.5/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.5/Functions.html) functions:
|
||||
|
||||
```swift
|
||||
// SQLExpression: COUNT(email)
|
||||
@@ -588,4 +588,4 @@ You may want to compare it to another protocol, SQLSpecificExpressible, which ha
|
||||
|
||||
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
|
||||
|
||||
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/SQLExpression.html) protocol.
|
||||
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.5/Protocols/SQLExpression.html) protocol.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '2.4.2'
|
||||
s.version = '2.5.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
|
||||
@@ -166,8 +166,8 @@ class DatabaseObservationBroker {
|
||||
unowned var database: Database
|
||||
var savepointStack = SavepointStack()
|
||||
var transactionState: TransactionState = .none
|
||||
var transactionObservations = [TransactionObservation]()
|
||||
var activeTransactionObservations = [TransactionObservation]()
|
||||
var transactionObservations: [TransactionObservation] = []
|
||||
var statementObservations: [StatementObservation] = []
|
||||
|
||||
init(_ database: Database) {
|
||||
self.database = database
|
||||
@@ -219,17 +219,59 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) {
|
||||
// Activate the transaction observers that are interested in the actions
|
||||
// performed by the statement.
|
||||
// Fill statementObservations with observations that are interested in
|
||||
// the kind of events performed by the statement.
|
||||
//
|
||||
// Those statementObservations will be notified of individual changes
|
||||
// in databaseWillChange() and databaseDidChange().
|
||||
let databaseEventKinds = statement.databaseEventKinds
|
||||
activeTransactionObservations = transactionObservations.filter { observer in
|
||||
return databaseEventKinds.contains(where: observer.observes)
|
||||
|
||||
switch databaseEventKinds.count {
|
||||
case 0:
|
||||
// Statement has no effect on any database table.
|
||||
//
|
||||
// For example: PRAGMA foreign_keys = ON
|
||||
statementObservations = []
|
||||
case 1:
|
||||
// We'll execute a simple statement without any side effect.
|
||||
// Eventual database events will thus all have the same kind. All
|
||||
// detabase events can be notified to interested observations.
|
||||
//
|
||||
// For example, if one observes all deletions in the table T, then
|
||||
// all individual deletions of DELETE FROM T are notified:
|
||||
statementObservations = transactionObservations.flatMap { observation in
|
||||
guard databaseEventKinds.contains(where: observation.observes) else {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
// observation will be notified of all individual events
|
||||
return (observation, DatabaseEventPredicate.true)
|
||||
}
|
||||
default:
|
||||
// We'll execute a complex statement with side effects performed by
|
||||
// an SQL trigger or a foreign key action. Eventual database events
|
||||
// may not all have the same kind: we need to filter them before
|
||||
// notifying interested observations.
|
||||
//
|
||||
// For example, if DELETE FROM T1 generates deletions in T1 and T2
|
||||
// by the mean of a foreign key action, then when one only observes
|
||||
// deletions in T1, one must not be notified of deletions in T2:
|
||||
statementObservations = transactionObservations.flatMap { observation in
|
||||
let observedKinds = databaseEventKinds.filter(observation.observes)
|
||||
if observedKinds.isEmpty {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
// observation will only be notified of individual events that
|
||||
// match one of the observed kinds.
|
||||
return (observation, DatabaseEventPredicate.matching(observedKinds))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Wait for next statement
|
||||
activeTransactionObservations = []
|
||||
statementObservations = []
|
||||
|
||||
// Reset transactionState before databaseDidRollback eventually
|
||||
// executes other statements.
|
||||
@@ -252,7 +294,7 @@ class DatabaseObservationBroker {
|
||||
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
// Wait for next statement
|
||||
activeTransactionObservations = []
|
||||
statementObservations = []
|
||||
|
||||
// Has statement any effect on transaction/savepoints?
|
||||
if let transactionEffect = statement.transactionEffect {
|
||||
@@ -319,12 +361,12 @@ class DatabaseObservationBroker {
|
||||
private func databaseWillChange(with event: DatabasePreUpdateEvent) {
|
||||
if savepointStack.isEmpty {
|
||||
// Notify now
|
||||
for observation in activeTransactionObservations {
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
observation.databaseWillChange(with: event)
|
||||
}
|
||||
} else {
|
||||
// Buffer
|
||||
savepointStack.eventsBuffer.append((event: event.copy(), observations: activeTransactionObservations))
|
||||
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -333,12 +375,12 @@ class DatabaseObservationBroker {
|
||||
private func databaseDidChange(with event: DatabaseEvent) {
|
||||
if savepointStack.isEmpty {
|
||||
// Notify now
|
||||
for observation in activeTransactionObservations {
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
observation.databaseDidChange(with: event)
|
||||
}
|
||||
} else {
|
||||
// Buffer
|
||||
savepointStack.eventsBuffer.append((event: event.copy(), observations: activeTransactionObservations))
|
||||
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,8 +396,8 @@ class DatabaseObservationBroker {
|
||||
let eventsBuffer = savepointStack.eventsBuffer
|
||||
savepointStack.clear()
|
||||
|
||||
for (event, observations) in eventsBuffer {
|
||||
for observation in observations {
|
||||
for (event, statementObservations) in eventsBuffer {
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
event.send(to: observation)
|
||||
}
|
||||
}
|
||||
@@ -656,7 +698,6 @@ public enum DatabaseEventKind {
|
||||
return selectionInfo.contains(anyColumnIn: updatedColumnNames, from: tableName)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseEventKind {
|
||||
@@ -672,6 +713,7 @@ extension DatabaseEventKind {
|
||||
|
||||
protocol DatabaseEventProtocol {
|
||||
func send(to observer: TransactionObservation)
|
||||
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool
|
||||
}
|
||||
|
||||
/// A database event, notified to TransactionObserver.
|
||||
@@ -689,6 +731,8 @@ public struct DatabaseEvent {
|
||||
case update = 23
|
||||
}
|
||||
|
||||
private let impl: DatabaseEventImpl
|
||||
|
||||
/// The event kind
|
||||
public let kind: Kind
|
||||
|
||||
@@ -722,14 +766,22 @@ public struct DatabaseEvent {
|
||||
init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
|
||||
self.init(kind: kind, rowID: rowID, impl: MetalDatabaseEventImpl(databaseNameCString: databaseNameCString, tableNameCString: tableNameCString))
|
||||
}
|
||||
|
||||
private let impl: DatabaseEventImpl
|
||||
}
|
||||
|
||||
extension DatabaseEvent : DatabaseEventProtocol {
|
||||
func send(to observer: TransactionObservation) {
|
||||
observer.databaseDidChange(with: self)
|
||||
}
|
||||
|
||||
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
|
||||
switch (kind, databaseEventKind) {
|
||||
case (.insert, .insert(let tableName)): return self.tableName == tableName
|
||||
case (.delete, .delete(let tableName)): return self.tableName == tableName
|
||||
case (.update, .update(let tableName, _)): return self.tableName == tableName
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Protocol for internal implementation of DatabaseEvent
|
||||
@@ -883,6 +935,16 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
|
||||
func send(to observer: TransactionObservation) {
|
||||
observer.databaseWillChange(with: self)
|
||||
}
|
||||
|
||||
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
|
||||
switch (kind, databaseEventKind) {
|
||||
case (.insert, .insert(let tableName)): return self.tableName == tableName
|
||||
case (.delete, .delete(let tableName)): return self.tableName == tableName
|
||||
case (.update, .update(let tableName, _)): return self.tableName == tableName
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Protocol for internal implementation of DatabaseEvent
|
||||
@@ -1008,6 +1070,25 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
|
||||
|
||||
#endif
|
||||
|
||||
// A predicate that filters database events
|
||||
enum DatabaseEventPredicate {
|
||||
// Yes filter
|
||||
case `true`
|
||||
// Only events that match one of those kinds
|
||||
case matching([DatabaseEventKind])
|
||||
|
||||
func evaluate(_ event: DatabaseEventProtocol) -> Bool {
|
||||
switch self {
|
||||
case .true:
|
||||
return true
|
||||
case .matching(let kinds):
|
||||
return kinds.contains { event.matchesKind($0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate)
|
||||
|
||||
/// The SQLite savepoint stack is described at
|
||||
/// https://www.sqlite.org/lang_savepoint.html
|
||||
///
|
||||
@@ -1018,8 +1099,8 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
|
||||
/// notifying transaction observers of database events that could be
|
||||
/// rollbacked.
|
||||
class SavepointStack {
|
||||
/// The buffered events. See Database.didChange(with:)
|
||||
var eventsBuffer: [(event: DatabaseEventProtocol, observations: [TransactionObservation])] = []
|
||||
/// The buffered events (see DatabaseObservationBroker.databaseDidChange(with:))
|
||||
var eventsBuffer: [(event: DatabaseEventProtocol, statementObservations: [StatementObservation])] = []
|
||||
|
||||
/// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array).
|
||||
/// Indexes let us drop rollbacked events from the event buffer.
|
||||
|
||||
@@ -104,13 +104,13 @@ extension QueryInterfaceRequest {
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(Column("email") == "arthur@example.com")
|
||||
public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
if let whereExpression = query.whereExpression {
|
||||
query.whereExpression = whereExpression && predicate.sqlExpression
|
||||
} else {
|
||||
query.whereExpression = predicate.sqlExpression
|
||||
}
|
||||
return QueryInterfaceRequest(query: query)
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
if let expression = expression {
|
||||
return expression && predicate.sqlExpression
|
||||
} else {
|
||||
return predicate.sqlExpression
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *predicate* added to the
|
||||
@@ -235,6 +235,125 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where T: TableMapping {
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id = 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(key: 1)
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T> {
|
||||
guard let key = key else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(keys: [1, 2, 3])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible {
|
||||
let keys = Array(keys)
|
||||
let makePredicate: (Column) -> SQLExpression
|
||||
switch keys.count {
|
||||
case 0:
|
||||
return T.none()
|
||||
case 1:
|
||||
makePredicate = { $0 == keys[0] }
|
||||
default:
|
||||
makePredicate = { keys.contains($0) }
|
||||
}
|
||||
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
let primaryKey = try db.primaryKey(T.databaseTableName)
|
||||
GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)")
|
||||
let keysPredicate = makePredicate(Column(primaryKey.columns[0]))
|
||||
if let expression = expression {
|
||||
return expression && keysPredicate
|
||||
} else {
|
||||
return keysPredicate
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(key: ["personId": 1, "countryCode": "FR"])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T> {
|
||||
guard let key = key else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
|
||||
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T> {
|
||||
guard !keys.isEmpty else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
let keyPredicates: [SQLExpression] = try keys.map { key in
|
||||
// Prevent filter(db, keys: [[:]])
|
||||
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
|
||||
|
||||
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
|
||||
// ("foo", "bar") is not a unique key (primary key or columns of a
|
||||
// unique index)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else {
|
||||
fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))")
|
||||
}
|
||||
|
||||
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
|
||||
let columnPredicates: [SQLExpression] = key
|
||||
// Sort key columns in the same order as the unique index
|
||||
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
|
||||
.map { (column, value) in Column(column) == value }
|
||||
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
|
||||
}
|
||||
|
||||
let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keys is not emmpty
|
||||
|
||||
if let expression = expression {
|
||||
return expression && keysPredicate
|
||||
} else {
|
||||
return keysPredicate
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
|
||||
|
||||
// MARK: Deleting
|
||||
@@ -308,6 +427,60 @@ extension TableMapping {
|
||||
return all().filter(predicate)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id = 1
|
||||
/// let request = Player.filter(key: 1)
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(key: key)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
|
||||
/// let request = Player.filter(keys: [1, 2, 3])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
return all().filter(keys: keys)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
|
||||
/// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(key: key)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
|
||||
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(keys: keys)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
|
||||
@@ -1,10 +1,28 @@
|
||||
// MARK: - QueryInterfaceSelectQueryDefinition
|
||||
|
||||
struct DatabasePromise<T> {
|
||||
let resolve: (Database) throws -> T
|
||||
|
||||
init(value: T) {
|
||||
self.resolve = { _ in value }
|
||||
}
|
||||
|
||||
init(_ resolve: @escaping (Database) throws -> T) {
|
||||
self.resolve = resolve
|
||||
}
|
||||
|
||||
func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise {
|
||||
return DatabasePromise { db in
|
||||
try transform(db, self.resolve(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QueryInterfaceSelectQueryDefinition {
|
||||
var selection: [SQLSelectable]
|
||||
var isDistinct: Bool
|
||||
var source: SQLSource?
|
||||
var whereExpression: SQLExpression?
|
||||
var wherePromise: DatabasePromise<SQLExpression?>
|
||||
var groupByExpressions: [SQLExpression]
|
||||
var orderings: [SQLOrderingTerm]
|
||||
var isReversed: Bool
|
||||
@@ -25,7 +43,7 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
self.selection = selection
|
||||
self.isDistinct = isDistinct
|
||||
self.source = source
|
||||
self.whereExpression = whereExpression
|
||||
self.wherePromise = DatabasePromise(value: whereExpression)
|
||||
self.groupByExpressions = groupByExpressions
|
||||
self.orderings = orderings
|
||||
self.isReversed = isReversed
|
||||
@@ -33,7 +51,13 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
func sql(_ arguments: inout StatementArguments?) -> String {
|
||||
func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceSelectQueryDefinition {
|
||||
var query = self
|
||||
query.wherePromise = query.wherePromise.map(transform)
|
||||
return query
|
||||
}
|
||||
|
||||
func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
|
||||
var sql = "SELECT"
|
||||
|
||||
if isDistinct {
|
||||
@@ -44,10 +68,10 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ")
|
||||
|
||||
if let source = source {
|
||||
sql += " FROM " + source.sourceSQL(&arguments)
|
||||
sql += try " FROM " + source.sourceSQL(db, &arguments)
|
||||
}
|
||||
|
||||
if let whereExpression = whereExpression {
|
||||
if let whereExpression = try wherePromise.resolve(db) {
|
||||
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
@@ -86,10 +110,10 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
|
||||
if let source = source {
|
||||
sql += " FROM " + source.sourceSQL(&arguments)
|
||||
sql += try " FROM " + source.sourceSQL(db, &arguments)
|
||||
}
|
||||
|
||||
if let whereExpression = whereExpression {
|
||||
if let whereExpression = try wherePromise.resolve(db) {
|
||||
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
@@ -147,7 +171,7 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
let sql = self.sql(&arguments)
|
||||
let sql = try self.sql(db, &arguments)
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
try statement.setArgumentsWithValidation(arguments!)
|
||||
return (statement, nil)
|
||||
@@ -206,7 +230,7 @@ indirect enum SQLSource {
|
||||
case table(name: String, alias: String?)
|
||||
case query(query: QueryInterfaceSelectQueryDefinition, alias: String?)
|
||||
|
||||
func sourceSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
|
||||
switch self {
|
||||
case .table(let table, let alias):
|
||||
if let alias = alias {
|
||||
@@ -216,9 +240,9 @@ indirect enum SQLSource {
|
||||
}
|
||||
case .query(let query, let alias):
|
||||
if let alias = alias {
|
||||
return "(" + query.sql(&arguments) + ") AS " + alias.quotedDatabaseIdentifier
|
||||
return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier
|
||||
} else {
|
||||
return "(" + query.sql(&arguments) + ")"
|
||||
return try "(" + query.sql(db, &arguments) + ")"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -572,7 +572,7 @@ extension MutablePersistable {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(db, keys: keys).deleteAll(db)
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
@@ -623,7 +623,7 @@ extension MutablePersistable {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(db, keys: keys).deleteAll(db)
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by a unique key (the primary key or any key
|
||||
|
||||
@@ -78,7 +78,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
return try filter(db, keys: keys).fetchCursor(db)
|
||||
return try filter(keys: keys).fetchCursor(db)
|
||||
}
|
||||
|
||||
/// Returns an array of records, given their primary keys.
|
||||
@@ -98,7 +98,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
}
|
||||
return try filter(db, keys: keys).fetchAll(db)
|
||||
return try filter(keys: keys).fetchAll(db)
|
||||
}
|
||||
|
||||
/// Returns a single record given its primary key.
|
||||
@@ -115,7 +115,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
// Avoid hitting the database
|
||||
return nil
|
||||
}
|
||||
return try filter(db, keys: [key]).fetchOne(db)
|
||||
return try filter(key: key).fetchOne(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor<Self> {
|
||||
return try filter(db, keys: keys).fetchCursor(db)
|
||||
return try filter(keys: keys).fetchCursor(db)
|
||||
}
|
||||
|
||||
/// Returns an array of records identified by the provided unique keys
|
||||
@@ -155,12 +155,11 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] {
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
}
|
||||
return try filter(db, keys: keys).fetchAll(db)
|
||||
return try filter(keys: keys).fetchAll(db)
|
||||
}
|
||||
|
||||
/// Returns a single record identified by a unique key (the primary key or
|
||||
@@ -173,7 +172,11 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? {
|
||||
return try filter(db, keys: [key]).fetchOne(db)
|
||||
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self? {
|
||||
guard let key = key else {
|
||||
// Avoid hitting the database
|
||||
return nil
|
||||
}
|
||||
return try filter(key: key).fetchOne(db)
|
||||
}
|
||||
}
|
||||
@@ -68,65 +68,3 @@ extension TableMapping {
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Key Requests
|
||||
|
||||
static func filter<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
let columns = primaryKey.columns.map { Column($0) }
|
||||
GRDBPrecondition(columns.count == 1, "table \(databaseTableName) has multiple columns in its primary key")
|
||||
let column = columns[0]
|
||||
|
||||
let keys = Array(keys)
|
||||
switch keys.count {
|
||||
case 0:
|
||||
return none()
|
||||
case 1:
|
||||
return filter(column == keys[0])
|
||||
default:
|
||||
return filter(keys.contains(column))
|
||||
}
|
||||
}
|
||||
|
||||
// Raises a fatal error if there is no unique index on the columns (unless
|
||||
// fatalErrorOnMissingUniqueIndex is false, for testability).
|
||||
//
|
||||
// TODO: think about
|
||||
// - allowing non unique keys in Type.fetchOne(db, key: ...) ???
|
||||
// - allowing non unique keys in Type.fetchAll/Cursor(db, keys: ...)
|
||||
// - forbidding nil values: Player.deleteOne(db, key: ["email": nil]) may delete several rows (case of a nullable unique key)
|
||||
static func filter(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> QueryInterfaceRequest<Self> {
|
||||
// SELECT * FROM table WHERE ((a=? AND b=?) OR (c=? AND d=?) OR ...)
|
||||
let keyPredicates: [SQLExpression] = try keys.map { key in
|
||||
// Prevent filter(db, keys: [[:]])
|
||||
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
|
||||
|
||||
// Prevent filter(db, keys: [["foo": 1, "bar": 2]]) where
|
||||
// ("foo", "bar") is not a unique key (primary key or columns of a
|
||||
// unique index)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
|
||||
let message = "table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))"
|
||||
if fatalErrorOnMissingUniqueIndex {
|
||||
fatalError(message)
|
||||
} else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
|
||||
let columnPredicates: [SQLExpression] = key
|
||||
// Sort key columns in the same order as the unique index
|
||||
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
|
||||
.map { (column, value) in Column(column) == value }
|
||||
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
|
||||
}
|
||||
|
||||
guard let predicate = SQLBinaryOperator.or.join(keyPredicates) else {
|
||||
// No key
|
||||
return none()
|
||||
}
|
||||
|
||||
return filter(predicate)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDBCipher'
|
||||
s.version = '2.4.2'
|
||||
s.version = '2.5.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
|
||||
@@ -41,7 +41,8 @@
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
|
||||
@@ -296,10 +296,10 @@ ifdef JAZZY
|
||||
--author 'Gwendal Roué' \
|
||||
--author_url https://github.com/groue \
|
||||
--github_url https://github.com/groue/GRDB.swift \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.4.2 \
|
||||
--module-version 2.4 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.5.0 \
|
||||
--module-version 2.5 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/2.4/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/2.5/ \
|
||||
--output Documentation/Reference \
|
||||
--podspec GRDB.swift.podspec
|
||||
else
|
||||
|
||||
@@ -3,7 +3,7 @@ GRDB 2 [](ht
|
||||
|
||||
### A toolkit for SQLite databases, with a focus on application development
|
||||
|
||||
**Latest release**: January 5, 2018 • version 2.4.2 • [CHANGELOG](CHANGELOG.md)
|
||||
**Latest release**: January 11, 2018 • version 2.5.0 • [CHANGELOG](CHANGELOG.md)
|
||||
|
||||
**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4.0 / Xcode 9+
|
||||
|
||||
@@ -14,7 +14,7 @@ GRDB 2 [](ht
|
||||
| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) |
|
||||
| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
|
||||
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
|
||||
| **Swift 4** | **v2.4.2** |
|
||||
| **Swift 4** | **v2.5.0** |
|
||||
|
||||
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
|
||||
|
||||
@@ -197,7 +197,7 @@ Documentation
|
||||
|
||||
**Reference**
|
||||
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.4/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.5/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
|
||||
**Getting Started**
|
||||
|
||||
@@ -265,7 +265,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di
|
||||
```swift
|
||||
let package = Package(
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.4.2")
|
||||
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.5.0")
|
||||
]
|
||||
)
|
||||
```
|
||||
@@ -282,7 +282,7 @@ If you decide to use Carthage despite this warning, and get any Carthage-related
|
||||
|
||||
## Manually
|
||||
|
||||
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.4.2) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.4.2` command.
|
||||
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.5.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.5.0` command.
|
||||
|
||||
2. Embed the `GRDB.xcodeproj` project in your own project.
|
||||
|
||||
@@ -379,7 +379,7 @@ let dbQueue = try DatabaseQueue(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.5/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
## Database Pools
|
||||
@@ -460,7 +460,7 @@ let dbPool = try DatabasePool(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.5/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
|
||||
@@ -650,7 +650,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
|
||||
- Cursors can not be used on any thread: you must consume them in a protected database queue.
|
||||
- Cursors iterate database results in a lazy fashion, and don't consume much memory.
|
||||
- Cursors can be iterated only one time.
|
||||
- Cursors are granted with direct access to SQLite: you can especially expect the best performance from cursors of raw database rows and some primitive types like `Int`, `String`, or `Bool` that adopt the [StatementColumnConvertible](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/StatementColumnConvertible.html) protocol.
|
||||
- Cursors are granted with direct access to SQLite: you can especially expect the best performance from cursors of raw database rows and some primitive types like `Int`, `String`, or `Bool` that adopt the [StatementColumnConvertible](http://groue.github.io/GRDB.swift/docs/2.5/Protocols/StatementColumnConvertible.html) protocol.
|
||||
|
||||
If you don't see, or don't care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate.
|
||||
|
||||
@@ -663,7 +663,7 @@ Date.fetchCursor(...) // DatabaseValueCursor<Date>
|
||||
Player.fetchCursor(...) // RecordCursor<Player>
|
||||
```
|
||||
|
||||
All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift. As such, cursors come with many methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`:
|
||||
All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.5/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift. As such, cursors come with many methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`:
|
||||
|
||||
```swift
|
||||
// Iterate all Github links
|
||||
@@ -734,7 +734,7 @@ let rows = try Row.fetchAll(db,
|
||||
arguments: ["name": "Arthur"])
|
||||
```
|
||||
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.5/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
|
||||
|
||||
@@ -1005,7 +1005,7 @@ GRDB ships with built-in support for the following value types:
|
||||
|
||||
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
|
||||
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1397,7 +1397,7 @@ try dbQueue.inDatabase { db in
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.5/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
|
||||
```swift
|
||||
updateStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
@@ -1659,7 +1659,7 @@ row["consumed"] // "Hello"
|
||||
row["produced"] // nil
|
||||
```
|
||||
|
||||
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters:
|
||||
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.5/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters:
|
||||
|
||||
|
||||
### ColumnMapping
|
||||
@@ -1786,8 +1786,8 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used
|
||||
- `sqlite3_aggregate_context`, `sqlite3_create_function_v2`, `sqlite3_result_blob`, `sqlite3_result_double`, `sqlite3_result_error`, `sqlite3_result_error_code`, `sqlite3_result_int64`, `sqlite3_result_null`, `sqlite3_result_text`, `sqlite3_user_data`, `sqlite3_value_blob`, `sqlite3_value_bytes`, `sqlite3_value_double`, `sqlite3_value_int64`, `sqlite3_value_text`, `sqlite3_value_type`: see [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates)
|
||||
- `sqlite3_backup_finish`, `sqlite3_backup_init`, `sqlite3_backup_step`: see [Backup](#backup)
|
||||
- `sqlite3_bind_blob`, `sqlite3_bind_double`, `sqlite3_bind_int64`, `sqlite3_bind_null`, `sqlite3_bind_parameter_count`, `sqlite3_bind_parameter_name`, `sqlite3_bind_text`, `sqlite3_clear_bindings`, `sqlite3_column_blob`, `sqlite3_column_bytes`, `sqlite3_column_count`, `sqlite3_column_double`, `sqlite3_column_int64`, `sqlite3_column_name`, `sqlite3_column_text`, `sqlite3_column_type`, `sqlite3_exec`, `sqlite3_finalize`, `sqlite3_prepare_v2`, `sqlite3_reset`, `sqlite3_step`: see [Executing Updates](#executing-updates), [Fetch Queries](#fetch-queries), [Prepared Statements](#prepared-statements), [Values](#values)
|
||||
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html)
|
||||
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.4/Classes/Database.html)
|
||||
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.5/Structs/Configuration.html)
|
||||
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.5/Classes/Database.html)
|
||||
- `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections)
|
||||
- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [FetchedRecordsController](#fetchedrecordscontroller)
|
||||
- `sqlite3_config`: see [Error Log](#error-log)
|
||||
@@ -1798,9 +1798,9 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used
|
||||
- `sqlite3_last_insert_rowid`: see [Executing Updates](#executing-updates)
|
||||
- `sqlite3_preupdate_count`, `sqlite3_preupdate_depth`, `sqlite3_preupdate_hook`, `sqlite3_preupdate_new`, `sqlite3_preupdate_old`: see [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks)
|
||||
- `sqlite3_set_authorizer`: **reserved by GRDB**
|
||||
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.4/Classes/Statement.html)
|
||||
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html)
|
||||
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.4/Classes/DatabasePool.html)
|
||||
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.5/Classes/Statement.html)
|
||||
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.5/Structs/Configuration.html)
|
||||
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.5/Classes/DatabasePool.html)
|
||||
|
||||
|
||||
Records
|
||||
@@ -2125,7 +2125,7 @@ try Place.fetchAll(db, "SELECT ...", arguments:...) // [Place]
|
||||
try Place.fetchOne(db, "SELECT ...", arguments:...) // Place?
|
||||
```
|
||||
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.5/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
|
||||
|
||||
## TableMapping Protocol
|
||||
@@ -3189,7 +3189,7 @@ Player // SELECT * FROM players
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM players WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -3493,6 +3493,44 @@ try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Ci
|
||||
try Player.fetchOne(db, key: ["email": "arthur@example.com"]) // Player?
|
||||
```
|
||||
|
||||
**When you want to build a request and plan to fetch from it later**, use the `filter(key:)` and `filter(keys:)` methods:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM players WHERE id = 1
|
||||
let request = Player.filter(key: 1)
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
|
||||
// SELECT * FROM players WHERE id IN (1, 2, 3)
|
||||
let request = Player.filter(keys: [1, 2, 3])
|
||||
let players = try request.fetchAll(db) // [Player]
|
||||
|
||||
// SELECT * FROM players WHERE isoCode = 'FR'
|
||||
let request = Country.filter(key: "FR")
|
||||
let country = try request.fetchOne(db) // Country?
|
||||
|
||||
// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
|
||||
let request = Country.filter(keys: ["FR", "US"])
|
||||
let countries = try request.fetchAll(db) // [Country]
|
||||
|
||||
// SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR'
|
||||
let request = Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"])
|
||||
let citizenship = request.fetchOne(db) // Citizenship?
|
||||
|
||||
// SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
let request = Player.filter(key: ["email": "arthur@example.com"])
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
```
|
||||
|
||||
Those requests help observing the database with [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
|
||||
|
||||
```swift
|
||||
Player.filter(key: 1).rx
|
||||
.fetchOne(in: dbQueue)
|
||||
.subscribe(onNext: { player: Player? in
|
||||
print("Player 1 has changed")
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
## Fetching Aggregated Values
|
||||
|
||||
@@ -3658,9 +3696,9 @@ try request.fetchOne(db) // Player?
|
||||
|
||||
**To build custom requests**, you can create your own type that adopts the protocols, or derive requests from other requests, or use one of the built-in concrete types:
|
||||
|
||||
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.4/Structs/SQLRequest.html): a Request built from raw SQL
|
||||
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.4/Structs/AnyRequest.html): a type-erased Request
|
||||
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.4/Structs/AnyTypedRequest.html): a type-erased TypedRequest
|
||||
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.5/Structs/SQLRequest.html): a Request built from raw SQL
|
||||
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.5/Structs/AnyRequest.html): a type-erased Request
|
||||
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.5/Structs/AnyTypedRequest.html): a type-erased TypedRequest
|
||||
|
||||
Use the `asRequest(of:)` method to define the type fetched by the request:
|
||||
|
||||
@@ -4090,7 +4128,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -4303,7 +4341,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -5130,7 +5168,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout v2.4.2
|
||||
git checkout v2.5.0
|
||||
git submodule update --init SQLCipher/src
|
||||
```
|
||||
|
||||
@@ -5237,7 +5275,7 @@ DROP TABLE students;
|
||||
--' WHERE id = 1
|
||||
```
|
||||
|
||||
To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.4/Structs/StatementArguments.html) to your SQL queries:
|
||||
To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.5/Structs/StatementArguments.html) to your SQL queries:
|
||||
|
||||
```swift
|
||||
// Good
|
||||
@@ -5818,7 +5856,7 @@ try dbPool.write { db in
|
||||
|
||||
### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/DatabaseWriter.html) protocols.
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.5/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.5/Protocols/DatabaseWriter.html) protocols.
|
||||
|
||||
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
|
||||
|
||||
@@ -5912,7 +5950,7 @@ If you absolutely need multiple connections, then:
|
||||
- Read about [isolation in SQLite](https://www.sqlite.org/isolation.html)
|
||||
- Learn about [locks and transactions](https://www.sqlite.org/lang_transaction.html)
|
||||
- Become a master of the [WAL mode](https://www.sqlite.org/wal.html)
|
||||
- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.4/Structs/Configuration.html)
|
||||
- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.5/Structs/Configuration.html)
|
||||
- [Ask questions](https://github.com/groue/GRDB.swift/issues)
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>2.4.2</string>
|
||||
<string>2.5.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -59,7 +59,7 @@ class FTS5PatternTests: GRDBTestCase {
|
||||
func testInvalidFTS5Pattern() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
dbQueue.inDatabase { db in
|
||||
let invalidRawPatterns = ["", "?!", "^", "^foo", "NOT", "(", "AND", "OR", "\"", "missing:foo"]
|
||||
let invalidRawPatterns = ["", "?!", "^", "NOT", "(", "AND", "OR", "\"", "missing:foo"]
|
||||
for rawPattern in invalidRawPatterns {
|
||||
do {
|
||||
_ = try db.makeFTS5Pattern(rawPattern: rawPattern, forTable: "books")
|
||||
|
||||
@@ -310,6 +310,76 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Key Request
|
||||
|
||||
func testFetchCursorWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = MinimalRowID()
|
||||
try record1.insert(db)
|
||||
let record2 = MinimalRowID()
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let cursor = try MinimalRowID.filter(keys: []).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try MinimalRowID.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try MinimalRowID.filter(keys: [["id": record1.id], ["id": nil]]).fetchCursor(db)
|
||||
let fetchedRecord = try cursor.next()!
|
||||
XCTAssertEqual(fetchedRecord.id!, record1.id!)
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = MinimalRowID()
|
||||
try record1.insert(db)
|
||||
let record2 = MinimalRowID()
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let fetchedRecords = try MinimalRowID.filter(keys: []).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try MinimalRowID.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try MinimalRowID.filter(keys: [["id": record1.id], ["id": nil]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 1)
|
||||
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalRowID()
|
||||
try record.insert(db)
|
||||
|
||||
let fetchedRecord = try MinimalRowID.filter(key: ["id": record.id]).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.id == record.id)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key
|
||||
|
||||
@@ -379,6 +449,75 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key Request
|
||||
|
||||
func testFetchCursorWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = MinimalRowID()
|
||||
try record1.insert(db)
|
||||
let record2 = MinimalRowID()
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let ids: [Int64] = []
|
||||
let cursor = try MinimalRowID.filter(keys: ids).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let ids = [record1.id!, record2.id!]
|
||||
let cursor = try MinimalRowID.filter(keys: ids).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = MinimalRowID()
|
||||
try record1.insert(db)
|
||||
let record2 = MinimalRowID()
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let ids: [Int64] = []
|
||||
let fetchedRecords = try MinimalRowID.filter(keys: ids).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let ids = [record1.id!, record2.id!]
|
||||
let fetchedRecords = try MinimalRowID.filter(keys: ids).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithPrimaryKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalRowID()
|
||||
try record.insert(db)
|
||||
|
||||
do {
|
||||
let id: Int64? = nil
|
||||
let fetchedRecord = try MinimalRowID.filter(key: id).fetchOne(db)
|
||||
XCTAssertTrue(fetchedRecord == nil)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecord = try MinimalRowID.filter(key: record.id).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.id == record.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
|
||||
@@ -321,6 +321,81 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Key Request
|
||||
|
||||
func testFetchCursorWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = MinimalSingle()
|
||||
record1.UUID = "theUUID1"
|
||||
try record1.insert(db)
|
||||
let record2 = MinimalSingle()
|
||||
record2.UUID = "theUUID2"
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let cursor = try MinimalSingle.filter(keys: []).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchCursor(db)
|
||||
let fetchedRecord = try cursor.next()!
|
||||
XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!)
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = MinimalSingle()
|
||||
record1.UUID = "theUUID1"
|
||||
try record1.insert(db)
|
||||
let record2 = MinimalSingle()
|
||||
record2.UUID = "theUUID2"
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let fetchedRecords = try MinimalSingle.filter(keys: []).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 1)
|
||||
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalSingle()
|
||||
record.UUID = "theUUID"
|
||||
try record.insert(db)
|
||||
|
||||
let fetchedRecord = try MinimalSingle.filter(key: ["UUID": record.UUID]).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key
|
||||
|
||||
@@ -395,6 +470,80 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key Request
|
||||
|
||||
func testFetchCursorWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = MinimalSingle()
|
||||
record1.UUID = "theUUID1"
|
||||
try record1.insert(db)
|
||||
let record2 = MinimalSingle()
|
||||
record2.UUID = "theUUID2"
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let UUIDs: [String] = []
|
||||
let cursor = try MinimalSingle.filter(keys: UUIDs).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let UUIDs = [record1.UUID!, record2.UUID!]
|
||||
let cursor = try MinimalSingle.filter(keys: UUIDs).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = MinimalSingle()
|
||||
record1.UUID = "theUUID1"
|
||||
try record1.insert(db)
|
||||
let record2 = MinimalSingle()
|
||||
record2.UUID = "theUUID2"
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let UUIDs: [String] = []
|
||||
let fetchedRecords = try MinimalSingle.filter(keys: UUIDs).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let UUIDs = [record1.UUID!, record2.UUID!]
|
||||
let fetchedRecords = try MinimalSingle.filter(keys: UUIDs).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithPrimaryKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalSingle()
|
||||
record.UUID = "theUUID"
|
||||
try record.insert(db)
|
||||
|
||||
do {
|
||||
let id: String? = nil
|
||||
let fetchedRecord = try MinimalSingle.filter(key: id).fetchOne(db)
|
||||
XCTAssertTrue(fetchedRecord == nil)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecord = try MinimalSingle.filter(key: record.UUID).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
|
||||
@@ -390,6 +390,79 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Key Request
|
||||
|
||||
func testFetchCursorWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Person(name: "Arthur")
|
||||
try record1.insert(db)
|
||||
let record2 = Person(name: "Barbara")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let cursor = try Person.filter(keys: []).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Person.filter(keys: [["rowid": record1.id], ["rowid": record2.id]]).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Person.filter(keys: [["rowid": record1.id], ["rowid": nil]]).fetchCursor(db)
|
||||
let fetchedRecord = try cursor.next()!
|
||||
XCTAssertEqual(fetchedRecord.id!, record1.id!)
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Person(name: "Arthur")
|
||||
try record1.insert(db)
|
||||
let record2 = Person(name: "Barbara")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Person.filter(keys: []).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Person.filter(keys: [["rowid": record1.id], ["rowid": record2.id]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Person.filter(keys: [["rowid": record1.id], ["rowid": nil]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 1)
|
||||
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Person(name: "Arthur")
|
||||
try record.insert(db)
|
||||
|
||||
let fetchedRecord = try Person.filter(key: ["rowid": record.id]).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.id == record.id)
|
||||
XCTAssertTrue(fetchedRecord.name == record.name)
|
||||
XCTAssertTrue(fetchedRecord.age == record.age)
|
||||
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key
|
||||
|
||||
@@ -462,6 +535,78 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key Request
|
||||
|
||||
func testFetchCursorWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Person(name: "Arthur")
|
||||
try record1.insert(db)
|
||||
let record2 = Person(name: "Barbara")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let ids: [Int64] = []
|
||||
let cursor = try Person.filter(keys: ids).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let ids = [record1.id!, record2.id!]
|
||||
let cursor = try Person.filter(keys: ids).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Person(name: "Arthur")
|
||||
try record1.insert(db)
|
||||
let record2 = Person(name: "Barbara")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let ids: [Int64] = []
|
||||
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let ids = [record1.id!, record2.id!]
|
||||
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithPrimaryKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Person(name: "Arthur")
|
||||
try record.insert(db)
|
||||
|
||||
do {
|
||||
let id: Int64? = nil
|
||||
let fetchedRecord = try Person.filter(key: id).fetchOne(db)
|
||||
XCTAssertTrue(fetchedRecord == nil)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecord = try Person.filter(key: record.id).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.id == record.id)
|
||||
XCTAssertTrue(fetchedRecord.name == record.name)
|
||||
XCTAssertTrue(fetchedRecord.age == record.age)
|
||||
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
|
||||
@@ -344,6 +344,78 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Key Request
|
||||
|
||||
func testFetchCursorWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Citizenship(personName: "Arthur", countryName: "France", native: true)
|
||||
try record1.insert(db)
|
||||
let record2 = Citizenship(personName: "Barbara", countryName: "France", native: false)
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let cursor = try Citizenship.filter(keys: []).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": record2.personName, "countryName": record2.countryName]]).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.personName }), Set([record1.personName, record2.personName]))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": nil, "countryName": nil]]).fetchCursor(db)
|
||||
let fetchedRecord = try cursor.next()!
|
||||
XCTAssertEqual(fetchedRecord.personName, record1.personName)
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Citizenship(personName: "Arthur", countryName: "France", native: true)
|
||||
try record1.insert(db)
|
||||
let record2 = Citizenship(personName: "Barbara", countryName: "France", native: false)
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Citizenship.filter(keys: []).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": record2.personName, "countryName": record2.countryName]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.personName }), Set([record1.personName, record2.personName]))
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": nil, "countryName": nil]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 1)
|
||||
XCTAssertEqual(fetchedRecords.first!.personName, record1.personName!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Citizenship(personName: "Arthur", countryName: "France", native: true)
|
||||
try record.insert(db)
|
||||
|
||||
let fetchedRecord = try Citizenship.filter(key: ["personName": record.personName, "countryName": record.countryName]).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.personName == record.personName)
|
||||
XCTAssertTrue(fetchedRecord.countryName == record.countryName)
|
||||
XCTAssertTrue(fetchedRecord.native == record.native)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
|
||||
@@ -103,6 +103,20 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Key Request
|
||||
|
||||
func testFetchOneWithKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Item(email: "item@example.com")
|
||||
try record.insert(db)
|
||||
|
||||
let fetchedRecord = try Item.filter(key: ["email": record.email]).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.email == record.email)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key
|
||||
|
||||
@@ -176,4 +190,78 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key Request
|
||||
|
||||
func testFetchCursorWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Item(name: "Table")
|
||||
try record1.insert(db)
|
||||
let id1 = db.lastInsertedRowID
|
||||
let record2 = Item(name: "Chair")
|
||||
try record2.insert(db)
|
||||
let id2 = db.lastInsertedRowID
|
||||
|
||||
do {
|
||||
let ids: [Int64] = []
|
||||
let cursor = try Item.filter(keys: ids).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let ids = [id1, id2]
|
||||
let cursor = try Item.filter(keys: ids).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.name! }), Set([record1, record2].map { $0.name! }))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Item(name: "Table")
|
||||
try record1.insert(db)
|
||||
let id1 = db.lastInsertedRowID
|
||||
let record2 = Item(name: "Chair")
|
||||
try record2.insert(db)
|
||||
let id2 = db.lastInsertedRowID
|
||||
|
||||
do {
|
||||
let ids: [Int64] = []
|
||||
let fetchedRecords = try Item.filter(keys: ids).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let ids = [id1, id2]
|
||||
let fetchedRecords = try Item.filter(keys: ids).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.name! }), Set([record1, record2].map { $0.name! }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithPrimaryKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Item(name: "Table")
|
||||
try record.insert(db)
|
||||
let id = db.lastInsertedRowID
|
||||
|
||||
do {
|
||||
let id: Int64? = nil
|
||||
let fetchedRecord = try Item.filter(key: id).fetchOne(db)
|
||||
XCTAssertTrue(fetchedRecord == nil)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecord = try Item.filter(key: id).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.name == record.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -386,6 +386,79 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Key Request
|
||||
|
||||
func testFetchCursorWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Person(name: "Arthur")
|
||||
try record1.insert(db)
|
||||
let record2 = Person(name: "Barbara")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let cursor = try Person.filter(keys: []).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Person.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Person.filter(keys: [["id": record1.id], ["id": nil]]).fetchCursor(db)
|
||||
let fetchedRecord = try cursor.next()!
|
||||
XCTAssertEqual(fetchedRecord.id!, record1.id!)
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Person(name: "Arthur")
|
||||
try record1.insert(db)
|
||||
let record2 = Person(name: "Barbara")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Person.filter(keys: []).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Person.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Person.filter(keys: [["id": record1.id], ["id": nil]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 1)
|
||||
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Person(name: "Arthur")
|
||||
try record.insert(db)
|
||||
|
||||
let fetchedRecord = try Person.filter(key: ["id": record.id]).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.id == record.id)
|
||||
XCTAssertTrue(fetchedRecord.name == record.name)
|
||||
XCTAssertTrue(fetchedRecord.age == record.age)
|
||||
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key
|
||||
|
||||
@@ -458,6 +531,78 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key Request
|
||||
|
||||
func testFetchCursorWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Person(name: "Arthur")
|
||||
try record1.insert(db)
|
||||
let record2 = Person(name: "Barbara")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let ids: [Int64] = []
|
||||
let cursor = try Person.filter(keys: ids).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let ids = [record1.id!, record2.id!]
|
||||
let cursor = try Person.filter(keys: ids).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Person(name: "Arthur")
|
||||
try record1.insert(db)
|
||||
let record2 = Person(name: "Barbara")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let ids: [Int64] = []
|
||||
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let ids = [record1.id!, record2.id!]
|
||||
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithPrimaryKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Person(name: "Arthur")
|
||||
try record.insert(db)
|
||||
|
||||
do {
|
||||
let id: Int64? = nil
|
||||
let fetchedRecord = try Person.filter(key: id).fetchOne(db)
|
||||
XCTAssertTrue(fetchedRecord == nil)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecord = try Person.filter(key: record.id).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.id == record.id)
|
||||
XCTAssertTrue(fetchedRecord.name == record.name)
|
||||
XCTAssertTrue(fetchedRecord.age == record.age)
|
||||
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
|
||||
@@ -336,6 +336,77 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Key Request
|
||||
|
||||
func testFetchCursorWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
|
||||
try record1.insert(db)
|
||||
let record2 = Pet(UUID: "CainUUID", name: "Cain")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let cursor = try Pet.filter(keys: []).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchCursor(db)
|
||||
let fetchedRecord = try cursor.next()!
|
||||
XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!)
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
|
||||
try record1.insert(db)
|
||||
let record2 = Pet(UUID: "CainUUID", name: "Cain")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Pet.filter(keys: []).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 1)
|
||||
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
|
||||
try record.insert(db)
|
||||
|
||||
let fetchedRecord = try Pet.filter(key: ["UUID": record.UUID]).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
|
||||
XCTAssertTrue(fetchedRecord.name == record.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key
|
||||
|
||||
@@ -406,6 +477,76 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key Request
|
||||
|
||||
func testFetchCursorWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
|
||||
try record1.insert(db)
|
||||
let record2 = Pet(UUID: "CainUUID", name: "Cain")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let UUIDs: [String] = []
|
||||
let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let UUIDs = [record1.UUID!, record2.UUID!]
|
||||
let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
|
||||
try record1.insert(db)
|
||||
let record2 = Pet(UUID: "CainUUID", name: "Cain")
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let UUIDs: [String] = []
|
||||
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let UUIDs = [record1.UUID!, record2.UUID!]
|
||||
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithPrimaryKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
|
||||
try record.insert(db)
|
||||
|
||||
do {
|
||||
let id: String? = nil
|
||||
let fetchedRecord = try Pet.filter(key: id).fetchOne(db)
|
||||
XCTAssertTrue(fetchedRecord == nil)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecord = try Pet.filter(key: record.UUID).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
|
||||
XCTAssertTrue(fetchedRecord.name == record.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
|
||||
@@ -327,6 +327,81 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Key Request
|
||||
|
||||
func testFetchCursorWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Email()
|
||||
record1.email = "me@domain.com"
|
||||
try record1.insert(db)
|
||||
let record2 = Email()
|
||||
record2.email = "you@domain.com"
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let cursor = try Email.filter(keys: []).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Email.filter(keys: [["email": record1.email], ["email": record2.email]]).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set([record1.email, record2.email]))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
|
||||
do {
|
||||
let cursor = try Email.filter(keys: [["email": record1.email], ["email": nil]]).fetchCursor(db)
|
||||
let fetchedRecord = try cursor.next()!
|
||||
XCTAssertEqual(fetchedRecord.email, record1.email)
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Email()
|
||||
record1.email = "me@domain.com"
|
||||
try record1.insert(db)
|
||||
let record2 = Email()
|
||||
record2.email = "you@domain.com"
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Email.filter(keys: []).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Email.filter(keys: [["email": record1.email], ["email": record2.email]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set([record1.email, record2.email]))
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecords = try Email.filter(keys: [["email": record1.email], ["email": nil]]).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 1)
|
||||
XCTAssertEqual(fetchedRecords.first!.email, record1.email!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Email()
|
||||
record.email = "me@domain.com"
|
||||
try record.insert(db)
|
||||
|
||||
let fetchedRecord = try Email.filter(key: ["email": record.email]).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.email == record.email)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key
|
||||
|
||||
@@ -401,6 +476,80 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key Request
|
||||
|
||||
func testFetchCursorWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Email()
|
||||
record1.email = "me@domain.com"
|
||||
try record1.insert(db)
|
||||
let record2 = Email()
|
||||
record2.email = "you@domain.com"
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let emails: [String] = []
|
||||
let cursor = try Email.filter(keys: emails).fetchCursor(db)
|
||||
try XCTAssertNil(cursor.next())
|
||||
}
|
||||
|
||||
do {
|
||||
let emails = [record1.email!, record2.email!]
|
||||
let cursor = try Email.filter(keys: emails).fetchCursor(db)
|
||||
let fetchedRecords = try [cursor.next()!, cursor.next()!]
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.email! }), Set(emails))
|
||||
XCTAssertTrue(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchAllWithPrimaryKeysRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record1 = Email()
|
||||
record1.email = "me@domain.com"
|
||||
try record1.insert(db)
|
||||
let record2 = Email()
|
||||
record2.email = "you@domain.com"
|
||||
try record2.insert(db)
|
||||
|
||||
do {
|
||||
let emails: [String] = []
|
||||
let fetchedRecords = try Email.filter(keys: emails).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let emails = [record1.email!, record2.email!]
|
||||
let fetchedRecords = try Email.filter(keys: emails).fetchAll(db)
|
||||
XCTAssertEqual(fetchedRecords.count, 2)
|
||||
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set(emails))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFetchOneWithPrimaryKeyRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Email()
|
||||
record.email = "me@domain.com"
|
||||
try record.insert(db)
|
||||
|
||||
do {
|
||||
let id: String? = nil
|
||||
let fetchedRecord = try Email.filter(key: id).fetchOne(db)
|
||||
XCTAssertTrue(fetchedRecord == nil)
|
||||
}
|
||||
|
||||
do {
|
||||
let fetchedRecord = try Email.filter(key: record.email).fetchOne(db)!
|
||||
XCTAssertTrue(fetchedRecord.email == record.email)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
|
||||
@@ -15,29 +15,13 @@ private struct Person : RowConvertible, TableMapping {
|
||||
|
||||
class RecordUniqueIndexTests: GRDBTestCase {
|
||||
|
||||
func testKeyFilterRequiresUniqueIndex() throws {
|
||||
func testKeyFilterAcceptsUniqueIndex() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
|
||||
|
||||
_ = try Person.filter(db, keys: [["id": nil]])
|
||||
_ = try Person.filter(db, keys: [["email": nil]])
|
||||
do {
|
||||
_ = try Person.filter(db, keys: [["id": nil, "email": nil]], fatalErrorOnMissingUniqueIndex: false)
|
||||
XCTFail()
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
|
||||
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) email, id")
|
||||
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) email, id")
|
||||
}
|
||||
do {
|
||||
_ = try Person.filter(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false)
|
||||
XCTFail()
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
|
||||
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) name")
|
||||
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) name")
|
||||
}
|
||||
_ = try Person.filter(keys: [["id": nil]]).fetchOne(db)
|
||||
_ = try Person.filter(keys: [["email": nil]]).fetchOne(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,8 +166,8 @@ class SelectStatementTests : GRDBTestCase {
|
||||
|
||||
try db.create(table: "table1") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("id3", .integer).notNull().references("table3", column: "id", onDelete: .cascade, onUpdate: .cascade)
|
||||
t.column("id4", .integer).references("table4", column: "id", onDelete: .setNull, onUpdate: .setNull)
|
||||
t.column("id3", .integer).references("table3", column: "id", onDelete: .cascade, onUpdate: .cascade)
|
||||
t.column("id4", .integer).references("table4", column: "id", onDelete: .setNull, onUpdate: .cascade)
|
||||
t.column("a", .integer)
|
||||
t.column("b", .integer)
|
||||
}
|
||||
@@ -185,7 +185,7 @@ class SelectStatementTests : GRDBTestCase {
|
||||
try db.create(table: "table5") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
}
|
||||
try db.execute("CREATE TRIGGER table5trigger AFTER INSERT ON table5 BEGIN DELETE FROM table1; END")
|
||||
try db.execute("CREATE TRIGGER table5trigger AFTER INSERT ON table5 BEGIN INSERT INTO table1 (id3, id4, a, b) VALUES (NULL, NULL, 0, 0); END")
|
||||
|
||||
let statements = try [
|
||||
db.makeSelectStatement("SELECT * FROM table1"),
|
||||
@@ -239,12 +239,16 @@ class SelectStatementTests : GRDBTestCase {
|
||||
try db.execute("UPDATE table4 SET id = 2 WHERE id = 1")
|
||||
XCTAssertEqual(observers.map { $0.triggered }, [true, false, false, true])
|
||||
|
||||
try db.execute("DELETE FROM table3")
|
||||
XCTAssertEqual(observers.map { $0.triggered }, [true, true, true, true])
|
||||
|
||||
try db.execute("DELETE FROM table4")
|
||||
XCTAssertEqual(observers.map { $0.triggered }, [true, false, false, true])
|
||||
|
||||
try db.execute("INSERT INTO table4 (id) VALUES (1)")
|
||||
try db.execute("DELETE FROM table4")
|
||||
XCTAssertEqual(observers.map { $0.triggered }, [false, false, false, doubtfulCountFunction])
|
||||
|
||||
try db.execute("DELETE FROM table3")
|
||||
XCTAssertEqual(observers.map { $0.triggered }, [true, true, true, true])
|
||||
|
||||
try db.execute("INSERT INTO table5 (id) VALUES (NULL)")
|
||||
XCTAssertEqual(observers.map { $0.triggered }, [true, true, true, true])
|
||||
}
|
||||
|
||||
@@ -1556,5 +1556,74 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
XCTAssertEqual(observer.lastCommittedEvents.count, 2)
|
||||
}
|
||||
}
|
||||
|
||||
func testComplexFilteredDatabaseEvents() throws {
|
||||
// When a statement impact several tables, only filtered events are
|
||||
// notified
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
// Observe deletions in table b
|
||||
let observer = Observer(observes: { eventKind in
|
||||
if case .delete(tableName: let tableName) = eventKind {
|
||||
return tableName == "b"
|
||||
}
|
||||
return false
|
||||
})
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
|
||||
// Delete from a and trigger b deletion
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("""
|
||||
CREATE TABLE a(id INTEGER PRIMARY KEY);
|
||||
CREATE TABLE b(id INTEGER PRIMARY KEY REFERENCES a(id) ON DELETE CASCADE);
|
||||
INSERT INTO a (id) VALUES (42);
|
||||
INSERT INTO b (id) VALUES (42);
|
||||
DELETE FROM a;
|
||||
""")
|
||||
return .commit
|
||||
}
|
||||
|
||||
XCTAssertEqual(observer.didChangeCount, 1)
|
||||
XCTAssertEqual(observer.willCommitCount, 1)
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
XCTAssertEqual(observer.lastCommittedEvents.count, 1)
|
||||
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .delete, tableName: "b", rowId: 42))
|
||||
}
|
||||
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
// Observe deletions in table b
|
||||
let observer = Observer(observes: { eventKind in
|
||||
if case .delete(tableName: let tableName) = eventKind {
|
||||
return tableName == "b"
|
||||
}
|
||||
return false
|
||||
})
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
|
||||
// Insert into c and trigger b deletion
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("""
|
||||
CREATE TABLE a(id INTEGER PRIMARY KEY);
|
||||
CREATE TABLE b(id INTEGER PRIMARY KEY);
|
||||
CREATE TABLE c(id INTEGER);
|
||||
INSERT INTO b (id) VALUES (42);
|
||||
CREATE TRIGGER t AFTER INSERT ON c BEGIN DELETE FROM b; END;
|
||||
INSERT INTO c (id) VALUES (1);
|
||||
""")
|
||||
return .commit
|
||||
}
|
||||
|
||||
XCTAssertEqual(observer.didChangeCount, 1)
|
||||
XCTAssertEqual(observer.willCommitCount, 1)
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
XCTAssertEqual(observer.lastCommittedEvents.count, 1)
|
||||
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .delete, tableName: "b", rowId: 42))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user