#147: The fetch method have been removed, along with DatabaseSequence and DatabaseIterator.

This commit is contained in:
Gwendal Roué committed 2016-11-26 21:14:10 +01:00
1 parent 6f158e3382
commit af6e31dcdf
41 files changed
+932 -3027

No files matched your search

+22 -11
View File
@@ -5,27 +5,38 @@ Release Notes
**New**
- `DatabaseCursor` allows processing errors that happen when reading from the database. Compare:
- `DatabaseCursor` is the new way to efficiently iterate database results:
```swift
// May crash in case of I/O error, for example:
for person in Person.fetch(db) {
...
}
// Cursor expose all database errors:
let cursor = try Person.fetchCursor(db)
while person = try cursor.next() {
let persons = try Person.fetchCursor(db) // DatabaseCursor<Person>
while person = try persons.next() { // Person
...
}
```
**Breaking Change**
**Breaking Changes**
- The throwing `step()` method of DatabaseIterator has been removed. Use DatabaseCursor instead.
- `Database.tableExists(_:)` can now throw database errors.
- `Database.indexes(on:)` can now throw database errors.
- `Persistable.exists(_:)` can now throw database errors.
- The `fetch` method have been removed, along with `DatabaseSequence` and `DatabaseIterator`.
```swift
// No longer supported:
for person in Person.fetch(db) {
...
}
// Write instead:
let persons = try Person.fetchCursor(db)
while person = try persons.next() {
...
}
```
```diff
TODO
```
## 0.90.1
-44
View File
@@ -114,7 +114,6 @@
560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */; };
560FC5711CB00B880014AA8E /* PrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* PrimaryKeySingleTests.swift */; };
560FC5721CB00B880014AA8E /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; };
560FC5731CB00B880014AA8E /* RecordFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238311B9C74A90082EB20 /* RecordFetchTests.swift */; };
560FC5741CB00B880014AA8E /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; };
560FC5761CB00B880014AA8E /* DetachedRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381F1B9C74A90082EB20 /* DetachedRowTests.swift */; };
560FC5771CB00B880014AA8E /* DatabaseQueueSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */; };
@@ -189,11 +188,6 @@
563363F91C960711000BE133 /* PerformanceRealmTests.realm in Resources */ = {isa = PBXBuildFile; fileRef = 563363F81C960711000BE133 /* PerformanceRealmTests.realm */; };
563445051C4A7FD7003D3DC6 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; };
563445061C4A7FD7003D3DC6 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; };
5634B0741CF22BEF005360B9 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */; };
5634B0751CF22BEF005360B9 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */; };
5634B0761CF22BEF005360B9 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */; };
5634B0771CF22BEF005360B9 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */; };
5634B0781CF22BEF005360B9 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */; };
5634B1081CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; };
5634B1091CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; };
5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; };
@@ -427,7 +421,6 @@
5671562E1CB16729007DC145 /* DatabasePoolCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */; };
5671562F1CB16729007DC145 /* PrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* PrimaryKeySingleTests.swift */; };
567156301CB16729007DC145 /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; };
567156311CB16729007DC145 /* RecordFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238311B9C74A90082EB20 /* RecordFetchTests.swift */; };
567156321CB16729007DC145 /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; };
567156341CB16729007DC145 /* DetachedRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381F1B9C74A90082EB20 /* DetachedRowTests.swift */; };
567156351CB16729007DC145 /* DatabaseQueueSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */; };
@@ -714,7 +707,6 @@
56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; };
56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; };
56A238641B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238301B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift */; };
56A238661B9C74A90082EB20 /* RecordFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238311B9C74A90082EB20 /* RecordFetchTests.swift */; };
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; };
56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; };
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; };
@@ -826,7 +818,6 @@
56AFCA3D1CB1AA9900F48B96 /* RecordAwakeFromFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238301B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift */; };
56AFCA3E1CB1AA9900F48B96 /* DatabasePoolCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */; };
56AFCA3F1CB1AA9900F48B96 /* PrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* PrimaryKeySingleTests.swift */; };
56AFCA401CB1AA9900F48B96 /* RecordFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238311B9C74A90082EB20 /* RecordFetchTests.swift */; };
56AFCA411CB1AA9900F48B96 /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; };
56AFCA421CB1AA9900F48B96 /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; };
56AFCA441CB1AA9900F48B96 /* DetachedRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381F1B9C74A90082EB20 /* DetachedRowTests.swift */; };
@@ -893,7 +884,6 @@
56AFCA961CB1ABC800F48B96 /* RecordAwakeFromFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238301B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift */; };
56AFCA971CB1ABC800F48B96 /* DatabasePoolCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */; };
56AFCA981CB1ABC800F48B96 /* PrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* PrimaryKeySingleTests.swift */; };
56AFCA991CB1ABC800F48B96 /* RecordFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238311B9C74A90082EB20 /* RecordFetchTests.swift */; };
56AFCA9A1CB1ABC800F48B96 /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; };
56AFCA9B1CB1ABC800F48B96 /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; };
56AFCA9D1CB1ABC800F48B96 /* DetachedRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381F1B9C74A90082EB20 /* DetachedRowTests.swift */; };
@@ -1043,11 +1033,9 @@
56D496731D81309E008276D7 /* RecordAwakeFromFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238301B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift */; };
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; };
56D496751D81309E008276D7 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; };
56D496761D81309E008276D7 /* RecordFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238311B9C74A90082EB20 /* RecordFetchTests.swift */; };
56D496771D81309E008276D7 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; };
56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; };
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
56D4967B1D8130D3008276D7 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */; };
56D4967C1D8130DB008276D7 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56D4967E1D8130DB008276D7 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565049041CE32543000A97D8 /* FetchedRecordsControllerTests.swift */; };
56D4967F1D813131008276D7 /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; };
@@ -1356,8 +1344,6 @@
F3BA81031CFB303D003DC1BA /* FetchedRecordsControlleriOSTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControlleriOSTests.swift */; };
F3BA81041CFB3045003DC1BA /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565049041CE32543000A97D8 /* FetchedRecordsControllerTests.swift */; };
F3BA81051CFB3046003DC1BA /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565049041CE32543000A97D8 /* FetchedRecordsControllerTests.swift */; };
F3BA81061CFB3052003DC1BA /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */; };
F3BA81071CFB3053003DC1BA /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */; };
F3BA81081CFB3056003DC1BA /* DatabaseCoderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4361BE4C11200E39BBF /* DatabaseCoderTests.swift */; };
F3BA810A1CFB3056003DC1BA /* NSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* NSDateTests.swift */; };
F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */; };
@@ -1387,7 +1373,6 @@
F3BA81251CFB3063003DC1BA /* RecordAwakeFromFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238301B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift */; };
F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; };
F3BA81271CFB3063003DC1BA /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; };
F3BA81281CFB3063003DC1BA /* RecordFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238311B9C74A90082EB20 /* RecordFetchTests.swift */; };
F3BA81291CFB3063003DC1BA /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; };
F3BA812A1CFB3063003DC1BA /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; };
F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
@@ -1401,7 +1386,6 @@
F3BA81331CFB3064003DC1BA /* RecordAwakeFromFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238301B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift */; };
F3BA81341CFB3064003DC1BA /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; };
F3BA81351CFB3064003DC1BA /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; };
F3BA81361CFB3064003DC1BA /* RecordFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238311B9C74A90082EB20 /* RecordFetchTests.swift */; };
F3BA81371CFB3064003DC1BA /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; };
F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; };
F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
@@ -1670,7 +1654,6 @@
563363DE1C959295000BE133 /* DatabasePoolFileAttributesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolFileAttributesTests.swift; sourceTree = "<group>"; };
563363F81C960711000BE133 /* PerformanceRealmTests.realm */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceRealmTests.realm; sourceTree = "<group>"; };
563445041C4A7FD7003D3DC6 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = "<group>"; };
5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = "<group>"; };
563633981DA40F0100CB70CA /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = "<group>"; };
5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = "<group>"; };
@@ -1778,7 +1761,6 @@
56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordCopyTests.swift; sourceTree = "<group>"; };
56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordEditedTests.swift; sourceTree = "<group>"; };
56A238301B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordAwakeFromFetchTests.swift; sourceTree = "<group>"; };
56A238311B9C74A90082EB20 /* RecordFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordFetchTests.swift; sourceTree = "<group>"; };
56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordInitializersTests.swift; sourceTree = "<group>"; };
56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordSubClassTests.swift; sourceTree = "<group>"; };
56A238701B9C75030082EB20 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = "<group>"; };
@@ -2200,14 +2182,6 @@
path = DatabaseQueue;
sourceTree = "<group>";
};
5634B06A1CF22BD8005360B9 /* FetchRequest */ = {
isa = PBXGroup;
children = (
5634B0721CF22BEF005360B9 /* FetchRequestTests.swift */,
);
path = FetchRequest;
sourceTree = "<group>";
};
564A50BF1BFF4B6E00B3A3A2 /* Collation */ = {
isa = PBXGroup;
children = (
@@ -2332,7 +2306,6 @@
56B7F4281BE149F600E39BBF /* CoreGraphics */,
5671566F1CB18039007DC145 /* Encryption */,
56B15CFC1CD4C33A00A24C8B /* FetchedRecordsController */,
5634B06A1CF22BD8005360B9 /* FetchRequest */,
56F0B98C1B6001C600A2F135 /* Foundation */,
5698AC3E1DA2BEBB0056AF8C /* FTS */,
56A238231B9C74A90082EB20 /* Migrations */,
@@ -2471,7 +2444,6 @@
56A238301B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift */,
56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */,
56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */,
56A238311B9C74A90082EB20 /* RecordFetchTests.swift */,
56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */,
56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */,
56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */,
@@ -3676,7 +3648,6 @@
560FC5711CB00B880014AA8E /* PrimaryKeySingleTests.swift in Sources */,
560FC5721CB00B880014AA8E /* StatementColumnConvertibleTests.swift in Sources */,
56B021CA1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */,
560FC5731CB00B880014AA8E /* RecordFetchTests.swift in Sources */,
560FC5741CB00B880014AA8E /* DatabasePoolFunctionTests.swift in Sources */,
560FC5761CB00B880014AA8E /* DetachedRowTests.swift in Sources */,
560FC5771CB00B880014AA8E /* DatabaseQueueSchemaCacheTests.swift in Sources */,
@@ -3734,7 +3705,6 @@
560FC59C1CB00B880014AA8E /* StatementArguments+FoundationTests.swift in Sources */,
5657AB671D108BA9006283EF /* URLTests.swift in Sources */,
560FC59D1CB00B880014AA8E /* TableMapping+QueryInterfaceRequestTests.swift in Sources */,
5634B0741CF22BEF005360B9 /* FetchRequestTests.swift in Sources */,
560FC59E1CB00B880014AA8E /* NSDateTests.swift in Sources */,
560FC59F1CB00B880014AA8E /* DatabaseTests.swift in Sources */,
560FC5A01CB00B880014AA8E /* QueryInterfaceRequestTests.swift in Sources */,
@@ -3879,7 +3849,6 @@
56B021CB1D8C0D3900B239BB /* PersistenceConflictPolicyTests.swift in Sources */,
56B14E811D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */,
566AD8C81D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */,
567156311CB16729007DC145 /* RecordFetchTests.swift in Sources */,
567156321CB16729007DC145 /* DatabasePoolFunctionTests.swift in Sources */,
567156341CB16729007DC145 /* DetachedRowTests.swift in Sources */,
569C1EB41CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */,
@@ -3943,7 +3912,6 @@
5698ACD01DA8C2620056AF8C /* PrimaryKeyHiddenRowIDTests.swift in Sources */,
569178481CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */,
5634B1091CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */,
5634B0751CF22BEF005360B9 /* FetchRequestTests.swift in Sources */,
567156601CB16729007DC145 /* FunctionTests.swift in Sources */,
567156611CB16729007DC145 /* RecordWithColumnNameManglingTests.swift in Sources */,
56FF45581D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
@@ -4058,7 +4026,6 @@
56AFCA3E1CB1AA9900F48B96 /* DatabasePoolCollationTests.swift in Sources */,
56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
56AFCA3F1CB1AA9900F48B96 /* PrimaryKeySingleTests.swift in Sources */,
56AFCA401CB1AA9900F48B96 /* RecordFetchTests.swift in Sources */,
56AFCA411CB1AA9900F48B96 /* StatementColumnConvertibleTests.swift in Sources */,
56AFCA421CB1AA9900F48B96 /* DatabasePoolFunctionTests.swift in Sources */,
56AFCA441CB1AA9900F48B96 /* DetachedRowTests.swift in Sources */,
@@ -4133,7 +4100,6 @@
56AFCA6F1CB1AA9900F48B96 /* DatabaseTests.swift in Sources */,
56AFCA701CB1AA9900F48B96 /* QueryInterfaceRequestTests.swift in Sources */,
5634B10B1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */,
5634B0771CF22BEF005360B9 /* FetchRequestTests.swift in Sources */,
56AFCA721CB1AA9900F48B96 /* FunctionTests.swift in Sources */,
56AFCA731CB1AA9900F48B96 /* InMemoryDatabaseTests.swift in Sources */,
56AFCA741CB1AA9900F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */,
@@ -4178,7 +4144,6 @@
56AFCA971CB1ABC800F48B96 /* DatabasePoolCollationTests.swift in Sources */,
5657AB5C1D108BA9006283EF /* NSStringTests.swift in Sources */,
56AFCA981CB1ABC800F48B96 /* PrimaryKeySingleTests.swift in Sources */,
56AFCA991CB1ABC800F48B96 /* RecordFetchTests.swift in Sources */,
5698ACDD1DA925430056AF8C /* RowTestCase.swift in Sources */,
56AFCA9A1CB1ABC800F48B96 /* StatementColumnConvertibleTests.swift in Sources */,
56AFCA9B1CB1ABC800F48B96 /* DatabasePoolFunctionTests.swift in Sources */,
@@ -4258,7 +4223,6 @@
56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */,
5698ACA41DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
565EFAF41D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
5634B0781CF22BEF005360B9 /* FetchRequestTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -4359,7 +4323,6 @@
5657AB4A1D108BA9006283EF /* NSNullTests.swift in Sources */,
569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */,
56A2385A1B9C74A90082EB20 /* PrimaryKeySingleTests.swift in Sources */,
56A238661B9C74A90082EB20 /* RecordFetchTests.swift in Sources */,
56EE573E1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift in Sources */,
569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */,
56A238481B9C74A90082EB20 /* DetachedRowTests.swift in Sources */,
@@ -4438,7 +4401,6 @@
56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */,
56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */,
5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */,
5634B0761CF22BEF005360B9 /* FetchRequestTests.swift in Sources */,
560C97C81BFD0B8400BF8471 /* FunctionTests.swift in Sources */,
56A2383A1B9C74A90082EB20 /* InMemoryDatabaseTests.swift in Sources */,
56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */,
@@ -4472,7 +4434,6 @@
56D4968C1D81316E008276D7 /* RawRepresentableTests.swift in Sources */,
56D496C31D81375A008276D7 /* DatabaseQueueFileAttributesTests.swift in Sources */,
56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */,
56D4967B1D8130D3008276D7 /* FetchRequestTests.swift in Sources */,
56FC78681BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */,
56D4966B1D81309E008276D7 /* DeleteByKeyTests.swift in Sources */,
56D4965B1D81304E008276D7 /* NSDecimalNumberTests.swift in Sources */,
@@ -4529,7 +4490,6 @@
56D4965A1D81304E008276D7 /* NSDataTests.swift in Sources */,
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */,
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
56D496761D81309E008276D7 /* RecordFetchTests.swift in Sources */,
56D4966C1D81309E008276D7 /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */,
56D4965D1D81304E008276D7 /* NSNumberTests.swift in Sources */,
@@ -4717,7 +4677,6 @@
F3BA80DD1CFB300E003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */,
F3BA80BE1CFB2FD1003DC1BA /* DatabasePoolReadOnlyTests.swift in Sources */,
F3BA81061CFB3052003DC1BA /* FetchRequestTests.swift in Sources */,
F3BA80C61CFB2FD8003DC1BA /* DatabaseQueueConcurrencyTests.swift in Sources */,
F3BA81161CFB305E003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
F3BA80F41CFB301D003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */,
@@ -4809,7 +4768,6 @@
F3BA80E81CFB3016003DC1BA /* DictionaryRowTests.swift in Sources */,
F3BA80B41CFB2FC9003DC1BA /* ReadOnlyDatabaseTests.swift in Sources */,
F3BA81011CFB3032003DC1BA /* CGFloatTests.swift in Sources */,
F3BA81281CFB3063003DC1BA /* RecordFetchTests.swift in Sources */,
F3BA80501CFB2B59003DC1BA /* DatabasePoolSchemaCacheTests.swift in Sources */,
F3BA80BB1CFB2FD1003DC1BA /* DatabasePoolConcurrencyTests.swift in Sources */,
F3BA81141CFB305E003DC1BA /* QueryInterfaceRequestTests.swift in Sources */,
@@ -4917,7 +4875,6 @@
561667041D08A49900ADD404 /* NSDecimalNumberTests.swift in Sources */,
F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
566AD8C91D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */,
F3BA81361CFB3064003DC1BA /* RecordFetchTests.swift in Sources */,
56071A501DB54ED300CA6E47 /* FetchedRecordsControlleriOSTests.swift in Sources */,
F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */,
56A8C2461D1918EF0096E9D4 /* UUIDTests.swift in Sources */,
@@ -4990,7 +4947,6 @@
F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */,
F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */,
F3BA81351CFB3064003DC1BA /* RecordEditedTests.swift in Sources */,
F3BA81071CFB3053003DC1BA /* FetchRequestTests.swift in Sources */,
5657AB691D108BA9006283EF /* URLTests.swift in Sources */,
56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */,
F3BA81331CFB3064003DC1BA /* RecordAwakeFromFetchTests.swift in Sources */,
+1 -1
View File
@@ -657,7 +657,7 @@ extension Database {
throw error
}
// Force arguments validity. See UpdateStatement.execute(), and SelectStatement.fetchSequence()
// Force arguments validity. See UpdateStatement.execute(), and SelectStatement.fetchCursor()
try! validateRemainingArguments()
}
}
+2 -1
View File
@@ -65,7 +65,8 @@ public protocol DatabaseReader : class {
///
/// reader.nonIsolatedRead { db in
/// // no external update can mess with this iteration:
/// for row in Row.fetch(db, ...) { ... }
/// let rows = try Row.fetchCursor(db, ...)
/// while let row = try rows.next() { ... }
/// }
///
/// However, there is no guarantee that consecutive statements have the
+119 -159
View File
@@ -37,16 +37,16 @@ public protocol SQLExpressible {
/// Types that adopt DatabaseValueConvertible can be initialized from
/// database values.
///
/// The protocol comes with built-in methods that allow to fetch sequences,
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single values:
///
/// String.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String?>
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
/// String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// String.fetch(statement, arguments:...) // DatabaseSequence<String?>
/// String.fetchAll(statement, arguments:...) // [String?]
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
/// String.fetchAll(statement, arguments:...) // [String]
/// String.fetchOne(statement, arguments:...) // String?
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
@@ -77,14 +77,14 @@ extension DatabaseValueConvertible {
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// sequences, arrays, or single values:
/// cursors, arrays, or single values:
///
/// String.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String>
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String
/// String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// String.fetch(statement, arguments:...) // DatabaseSequence<String>
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
/// String.fetchAll(statement, arguments:...) // [String]
/// String.fetchOne(statement, arguments:...) // String
///
@@ -94,7 +94,25 @@ public extension DatabaseValueConvertible {
// MARK: Fetching From SelectStatement
/// TODO
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
/// while let name = try names.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
// Metal rows can be reused. And reusing them yields better performance.
let row = try Row(statement: statement).adaptedRow(adapter: adapter, statement: statement)
@@ -108,35 +126,9 @@ public extension DatabaseValueConvertible {
}
}
/// Returns a sequence of values fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let names = String.fetch(statement) // DatabaseSequence<String>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = String.fetch(statement)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence.
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
return DatabaseSequence { try fetchCursor(statement, arguments: arguments, adapter: adapter) }
}
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -153,7 +145,7 @@ public extension DatabaseValueConvertible {
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let name = String.fetchOne(statement) // String?
///
/// - parameters:
@@ -172,32 +164,28 @@ extension DatabaseValueConvertible {
// MARK: Fetching From FetchRequest
/// TODO
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns a sequence of values fetched from a fetch request.
/// Returns a cursor over values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = String.fetch(db, request) // DatabaseSequence<String>
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
/// for let name = try names.next() { // String
/// ...
/// }
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let names = String.fetch(db, request)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
/// The cursor must be iterated in a protected dispath queue.
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Self> {
let (statement, adapter) = try! request.prepare(db)
return fetch(statement, adapter: adapter)
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of values fetched from a fetch request.
@@ -233,35 +221,27 @@ extension DatabaseValueConvertible {
// MARK: Fetching From SQL
/// TODO
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a sequence of values fetched from an SQL query.
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = String.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String>
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String>
/// while let name = try name.next() { // String
/// ...
/// }
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let names = String.fetch(db, "SELECT name FROM ...")
/// Array(names) // Arthur, Barbara
/// execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A Database.
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence.
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
return fetch(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
@@ -297,22 +277,40 @@ extension DatabaseValueConvertible {
}
/// Swift's Optional comes with built-in methods that allow to fetch sequences
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
///
/// Optional<String>.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String?>
/// Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
/// Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String?>
/// Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// Optional<String>.fetch(statement, arguments:...) // DatabaseSequence<String?>
/// Optional<String>.fetchAll(statement, arguments:...) // [String?]
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// Optional<String>.fetchCursor(statement, arguments:...) // DatabaseCursor<String?>
/// Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public extension Optional where Wrapped: DatabaseValueConvertible {
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From SelectStatement
/// TODO
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try Optional<String>.fetchCursor(statement) // DatabaseCursor<String?>
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
let row = try Row(statement: statement).adaptedRow(adapter: adapter, statement: statement)
return try statement.fetchCursor(arguments: arguments) { () -> Wrapped? in
@@ -327,35 +325,9 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
}
}
/// Returns a sequence of optional values fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let names = Optional<String>.fetch(statement) // DatabaseSequence<String?>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = Optional<String>.fetch(statement)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence of optional values.
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Wrapped?> {
return DatabaseSequence { try fetchCursor(statement, arguments: arguments, adapter: adapter) }
}
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
@@ -373,32 +345,28 @@ extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From FetchRequest
/// TODO
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Wrapped?> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns a sequence of optional values fetched from a fetch request.
/// Returns a cursor over optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = Optional<String>.fetch(db, request) // DatabaseSequence<String?>
/// let names = try Optional<String>.fetchCursor(db, request) // DatabaseCursor<String?>
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let names = Optional<String>.fetch(db, request)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
/// The cursor must be iterated in a protected dispath queue.
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Wrapped?> {
let (statement, adapter) = try! request.prepare(db)
return fetch(statement, adapter: adapter)
/// - parameters:
/// - db: A database connection.
/// - requet: A fetch request.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Wrapped?> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of optional values fetched from a fetch request.
@@ -419,35 +387,27 @@ extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From SQL
/// TODO
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a sequence of optional values fetched from an SQL query.
/// Returns a cursor over optional values fetched from an SQL query.
///
/// let names = Optional<String>.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String?>
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String?>
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let names = Optional<String>.fetch(db, "SELECT name FROM ...")
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A Database.
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence of optional values.
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Wrapped?> {
return fetch(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
+53 -79
View File
@@ -65,11 +65,11 @@ public final class Row {
let impl: RowImpl
/// Unless we are producing a row array, we use a single row when iterating a
/// statement:
/// Unless we are producing a row array, we use a single row when iterating
/// a statement:
///
/// for row in Row.fetch(db, "SELECT ...") { ... }
/// for person in Person.fetch(db, "SELECT ...") { ... }
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let persons = Person.fetchAll(db, "SELECT ...")
///
/// This row keeps an unmanaged reference to the statement, and a handle to
/// the sqlite statement, so that we avoid many retain/release invocations.
@@ -502,54 +502,44 @@ extension Row {
// MARK: - Fetching From SelectStatement
/// TODO
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
// Metal rows can be reused. And reusing them yields better performance.
let row = try Row(statement: statement).adaptedRow(adapter: adapter, statement: statement)
return try statement.fetchCursor(arguments: arguments) { row }
}
/// Returns a sequence of rows fetched from a prepared statement.
/// Returns a cursor over rows fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT ...")
/// for row in Row.fetch(statement) {
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let rows = try Row.fetchCursor(statement) // DatabaseCursor<Row>
/// while let row = try rows.next() { // Row
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// }
///
/// Fetched rows are reused during the sequence iteration: don't wrap a row
/// sequence in an array with `Array(rows)` or `rows.filter { ... }` since
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
/// instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let rows = Row.fetch(statement)
/// for row in rows { ... } // 3 steps
/// db.execute("DELETE ...")
/// for row in rows { ... } // 2 steps
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements of the sequence are undefined.
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A Database.
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence of rows.
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Row> {
return DatabaseSequence { try fetchCursor(statement, arguments: arguments, adapter: adapter) }
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
// Metal rows can be reused. And reusing them yields better performance.
let row = try Row(statement: statement).adaptedRow(adapter: adapter, statement: statement)
return try statement.fetchCursor(arguments: arguments) { row }
}
/// Returns an array of rows fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT ...")
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let rows = Row.fetchAll(statement)
///
/// - parameters:
@@ -563,7 +553,7 @@ extension Row {
/// Returns a single row fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT ...")
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let row = Row.fetchOne(statement)
///
/// - parameters:
@@ -572,8 +562,8 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Row? {
let cursor = try! fetchCursor(statement, arguments: arguments, adapter: adapter)
return try! cursor.next().flatMap { $0.copy() }
let rows = try! fetchCursor(statement, arguments: arguments, adapter: adapter)
return try! rows.next().flatMap { $0.copy() }
}
}
@@ -582,44 +572,38 @@ extension Row {
// MARK: - Fetching From FetchRequest
/// TODO
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Row> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns a sequence of rows fetched from a fetch request.
/// Returns a cursor over rows fetched from a fetch request.
///
/// let idColumn = Column("id")
/// let nameColumn = Column("name")
/// let request = Person.select(idColumn, nameColumn)
/// for row in Row.fetch(db, request) {
/// let rows = try Row.fetchCursor(db) // DatabaseCursor<Row>
/// while let row = try rows.next() { // Row
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// }
///
/// Fetched rows are reused during the sequence iteration: don't wrap a row
/// sequence in an array with `Array(rows)` or `rows.filter { ... }` since
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
/// instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let rows = Row.fetch(statement)
/// for row in rows { ... } // 3 steps
/// db.execute("DELETE ...")
/// for row in rows { ... } // 2 steps
/// The cursor must be iterated in a protected dispath queue.
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements of the sequence are undefined.
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Row> {
let (statement, adapter) = try! request.prepare(db)
return fetch(statement, adapter: adapter)
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Row> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of rows fetched from a fetch request.
@@ -654,46 +638,36 @@ extension Row {
// MARK: - Fetching From SQL
/// TODO
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a sequence of rows fetched from an SQL query.
/// Returns a cursor over rows fetched from an SQL query.
///
/// for row in Row.fetch(db, "SELECT id, name FROM persons") {
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM persons") // DatabaseCursor<Row>
/// while let row = try rows.next() { // Row
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// }
///
/// Fetched rows are reused during the sequence iteration: don't wrap a row
/// sequence in an array with `Array(rows)` or `rows.filter { ... }` since
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
/// instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let rows = Row.fetch(db, "SELECT...")
/// for row in rows { ... } // 3 steps
/// db.execute("DELETE ...")
/// for row in rows { ... } // 2 steps
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements of the sequence are undefined.
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A Database.
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence of rows.
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Row> {
return fetch(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of rows fetched from an SQL query.
+9 -56
View File
@@ -203,7 +203,7 @@ public class Statement {
/// You create SelectStatement with the Database.makeSelectStatement() method:
///
/// dbQueue.inDatabase { db in
/// let statement = db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
/// let moreThanTwentyCount = Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])!
/// }
@@ -249,6 +249,7 @@ public final class SelectStatement : Statement {
SchedulingWatchdog.preconditionValidQueue(database, "Database was not used on the correct thread.")
// Force arguments validity. See UpdateStatement.execute(), and Database.execute()
// TODO: throws SQL_MISUSE?
try! prepare(withArguments: arguments)
try reset()
@@ -256,58 +257,26 @@ public final class SelectStatement : Statement {
}
}
/// A sequence of elements fetched from the database.
public struct DatabaseSequence<Element>: Sequence {
private let iterator: () -> DatabaseIterator<Element>
// Statement sequence
init(cursor: @escaping () throws -> DatabaseCursor<Element>) {
self.init(iterator: { try! DatabaseIterator(cursor: cursor()) })
}
// Empty sequence
static func makeEmptySequence(inDatabase database: Database) -> DatabaseSequence {
// Empty sequence is just as strict as statement sequence, and requires
// to be used on the database queue.
return DatabaseSequence(iterator: {
SchedulingWatchdog.preconditionValidQueue(database, "Database was not used on the correct thread.")
return DatabaseIterator(cursor: nil)
})
}
private init(iterator: @escaping () -> DatabaseIterator<Element>) {
self.iterator = iterator
}
/// Return a *iterator* over the elements of this *sequence*.
public func makeIterator() -> DatabaseIterator<Element> {
return iterator()
}
}
/// A cursor on a statement
public final class DatabaseCursor<Element> : Cursor {
fileprivate let statementRef: Unmanaged<SelectStatement>
fileprivate let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let element: () throws -> Element?
private var done = false
init(statement: SelectStatement, element: @escaping () throws -> Element?) {
self.statementRef = Unmanaged.passRetained(statement)
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
self.element = element
}
deinit {
statementRef.release()
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists. Once nil has been returned, all subsequent calls return nil.
///
/// let cursor = try Row.fetchCursor(db, "SELECT ...")
/// while let row = try cursor.next() {
/// print(row)
/// let rows = try Row.fetchCursor(db, "SELECT ...") // DatabaseCursor<Row>
/// while let row = try rows.next() { // Row
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// }
public func next() throws -> Element? {
if done {
@@ -321,27 +290,11 @@ public final class DatabaseCursor<Element> : Cursor {
case SQLITE_ROW:
return try element()
case let errorCode:
let statement = statementRef.takeUnretainedValue()
throw DatabaseError(code: errorCode, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
/// A iterator of elements fetched from the database.
public final class DatabaseIterator<Element>: IteratorProtocol {
let cursor: DatabaseCursor<Element>?
init(cursor: DatabaseCursor<Element>?) {
self.cursor = cursor
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists. Once nil has been returned, all subsequent calls return nil.
public func next() -> Element? {
return try! cursor?.next()
}
}
// MARK: - UpdateStatement
@@ -387,7 +340,7 @@ public final class UpdateStatement : Statement {
public func execute(arguments: StatementArguments? = nil) throws {
SchedulingWatchdog.preconditionValidQueue(database)
// Force arguments validity. See SelectStatement.fetchSequence(), and Database.execute()
// Force arguments validity. See SelectStatement.fetchCursor(), and Database.execute()
try! prepare(withArguments: arguments)
try! reset()
+50 -70
View File
@@ -52,7 +52,25 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
// MARK: Fetching From SelectStatement
/// TODO
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
/// while let name = try names.next() { // String
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
// We'll read from leftmost column at index 0, unless adapter mangles columns
let columnIndex: Int32
@@ -72,35 +90,9 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
}
}
/// Returns a sequence of values fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let names = String.fetch(statement) // DatabaseSequence<String>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = String.fetch(statement)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence of values.
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
return DatabaseSequence { try fetchCursor(statement, arguments: arguments, adapter: adapter) }
}
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -114,7 +106,7 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
/// Returns a single value fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let name = String.fetchOne(statement) // String?
///
/// - parameters:
@@ -148,32 +140,28 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From FetchRequest
/// TODO
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns a sequence of values fetched from a fetch request.
/// Returns a cursor over values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = String.fetch(db, request) // DatabaseSequence<String>
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
/// while let name = try names.next() { // String
/// ...
/// }
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let names = String.fetch(db, request)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
/// The cursor must be iterated in a protected dispath queue.
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Self> {
let (statement, adapter) = try! request.prepare(db)
return fetch(statement, adapter: adapter)
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of values fetched from a fetch request.
@@ -209,35 +197,27 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From SQL
/// TODO
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a sequence of values fetched from an SQL query.
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = String.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String>
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String>
/// while let name = try names.next() { // String
/// ...
/// }
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let names = String.fetch(db, "SELECT name FROM ...")
/// Array(names) // Arthur, Barbara
/// execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A Database.
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence of values.
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
return fetch(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
+30 -38
View File
@@ -30,30 +30,25 @@ extension QueryInterfaceRequest where T: RowConvertible {
// MARK: Fetching Record and RowConvertible
/// TODO
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<T> {
return try T.fetchCursor(db, self)
}
/// A sequence of fetched records.
/// A cursor over fetched records.
///
/// let nameColumn = Column("name")
/// let request = Person.order(nameColumn)
/// let persons = request.fetch(db) // DatabaseSequence<Person>
/// let persons = try request.fetchCursor(db) // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// ...
/// }
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let persons = request.fetch(db)
/// Array(persons).count // 3
/// db.execute("DELETE ...")
/// Array(persons).count // 2
/// The cursor must be iterated in a protected dispath queue.
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
public func fetch(_ db: Database) -> DatabaseSequence<T> {
return T.fetch(db, self)
/// - parameter db: A database connection.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<T> {
return try T.fetchCursor(db, self)
}
/// An array of fetched records.
@@ -488,30 +483,27 @@ extension RowConvertible where Self: TableMapping {
// MARK: Fetching All
/// TODO
/// A cursor over all records fetched from the database.
///
/// let persons = try Person.fetchCursor(db) // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// ...
/// }
///
/// Records are iterated in the natural ordering of the table.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameter db: A database connection.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database) throws -> DatabaseCursor<Self> {
return try all().fetchCursor(db)
}
/// A sequence of all records fetched from the database.
///
/// let persons = Person.fetch(db) // DatabaseSequence<Person>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let persons = Person.fetch(db)
/// Array(persons).count // 3
/// db.execute("DELETE ...")
/// Array(persons).count // 2
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
public static func fetch(_ db: Database) -> DatabaseSequence<Self> {
return all().fetch(db)
}
/// An array of all records fetched from the database.
///
/// let persons = Person.fetchAll(db) // [Person]
+58 -78
View File
@@ -3,17 +3,17 @@
/// let row = Row.fetchOne(db, "SELECT ...")!
/// let person = Person(row)
///
/// The protocol comes with built-in methods that allow to fetch sequences,
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single values:
///
/// Person.fetch(db, "SELECT ...", arguments:...) // DatabaseSequence<Person>
/// Person.fetchAll(db, "SELECT ...", arguments:...) // [Person]
/// Person.fetchOne(db, "SELECT ...", arguments:...) // Person?
/// Person.fetchCursor(db, "SELECT ...", arguments:...) // DatabaseCursor<Person>
/// Person.fetchAll(db, "SELECT ...", arguments:...) // [Person]
/// Person.fetchOne(db, "SELECT ...", arguments:...) // Person?
///
/// let statement = db.makeSelectStatement("SELECT ...")
/// Person.fetch(statement, arguments:...) // DatabaseSequence<Person>
/// Person.fetchAll(statement, arguments:...) // [Person]
/// Person.fetchOne(statement, arguments:...) // Person?
/// let statement = try db.makeSelectStatement("SELECT ...")
/// Person.fetchCursor(statement, arguments:...) // DatabaseCursor<Person>
/// Person.fetchAll(statement, arguments:...) // [Person]
/// Person.fetchOne(statement, arguments:...) // Person?
///
/// RowConvertible is adopted by Record.
public protocol RowConvertible {
@@ -44,7 +44,25 @@ extension RowConvertible {
// MARK: Fetching From SelectStatement
/// TODO
/// A cursor over records fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
/// let persons = try Person.fetchCursor(statement) // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
let row = try Row(statement: statement).adaptedRow(adapter: adapter, statement: statement)
return try statement.fetchCursor(arguments: arguments) {
@@ -54,35 +72,9 @@ extension RowConvertible {
}
}
/// Returns a sequence of records fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT * FROM persons")
/// let persons = Person.fetch(statement) // DatabaseSequence<Person>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let persons = Person.fetch(statement)
/// Array(persons).count // 3
/// db.execute("DELETE ...")
/// Array(persons).count // 2
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence of records.
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
return DatabaseSequence { try fetchCursor(statement, arguments: arguments, adapter: adapter) }
}
/// Returns an array of records fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT * FROM persons")
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
/// let persons = Person.fetchAll(statement) // [Person]
///
/// - parameters:
@@ -96,7 +88,7 @@ extension RowConvertible {
/// Returns a single record fetched from a prepared statement.
///
/// let statement = db.makeSelectStatement("SELECT * FROM persons")
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
/// let person = Person.fetchOne(statement) // Person?
///
/// - parameters:
@@ -114,32 +106,28 @@ extension RowConvertible {
// MARK: Fetching From FetchRequest
/// TODO
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns a sequence of records fetched from a fetch request.
/// Returns a cursor over records fetched from a fetch request.
///
/// let nameColumn = Column("firstName")
/// let request = Person.order(nameColumn)
/// let identities = Identity.fetch(db, request) // DatabaseSequence<Identity>
/// let identities = try Identity.fetchCursor(db, request) // DatabaseCursor<Identity>
/// while let identity = try identities.next() { // Identity
/// ...
/// }
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let identities = Identity.fetch(db, request)
/// Array(identities).count // 3
/// db.execute("DELETE ...")
/// Array(identities).count // 2
/// The cursor must be iterated in a protected dispath queue.
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Self> {
let (statement, adapter) = try! request.prepare(db)
return fetch(statement, adapter: adapter)
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of records fetched from a fetch request.
@@ -172,35 +160,27 @@ extension RowConvertible {
// MARK: Fetching From SQL
/// TODO
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a sequence of records fetched from an SQL query.
/// Returns a cursor over records fetched from an SQL query.
///
/// let persons = Person.fetch(db, "SELECT * FROM persons") // DatabaseSequence<Person>
/// let persons = try Person.fetchCursor(db, "SELECT * FROM persons") // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// ...
/// }
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// let persons = Person.fetch(db, "SELECT * FROM persons")
/// Array(persons).count // 3
/// db.execute("DELETE ...")
/// Array(persons).count // 2
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A Database.
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A sequence of records.
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
return fetch(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of records fetched from an SQL query.
+29 -37
View File
@@ -54,7 +54,20 @@ extension RowConvertible where Self: TableMapping {
// MARK: - Fetching by Single-Column Primary Key
/// TODO
/// Returns a cursor over records, given their primary keys.
///
/// let persons = try Person.fetchCursor(db, keys: [1, 2, 3]) // DatabaseCursor<Person>
/// while let person = try persons.next() {
/// ...
/// }
///
/// Records are iterated in unspecified order.
///
/// - parameters:
/// - db: A database connection.
/// - keys: A sequence of primary keys.
/// - 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 -> DatabaseCursor<Self>? where Sequence.Iterator.Element: DatabaseValueConvertible {
guard let statement = try makeFetchByPrimaryKeyStatement(db, keys: keys) else {
return nil
@@ -62,23 +75,6 @@ extension RowConvertible where Self: TableMapping {
return try fetchCursor(statement)
}
/// Returns a sequence of records, given their primary keys.
///
/// let persons = Person.fetch(db, keys: [1, 2, 3]) // DatabaseSequence<Person>
///
/// The order of records in the returned sequence is undefined.
///
/// - parameters:
/// - db: A Database.
/// - keys: A sequence of primary keys.
/// - returns: A sequence of records.
public static func fetch<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) -> DatabaseSequence<Self> where Sequence.Iterator.Element: DatabaseValueConvertible {
guard let statement = try! makeFetchByPrimaryKeyStatement(db, keys: keys) else {
return DatabaseSequence.makeEmptySequence(inDatabase: db)
}
return fetch(statement)
}
/// Returns an array of records, given their primary keys.
///
/// let persons = Person.fetchAll(db, keys: [1, 2, 3]) // [Person]
@@ -223,7 +219,21 @@ extension RowConvertible where Self: TableMapping {
// MARK: - Fetching by Key
/// TODO
/// Returns a cursor over records identified by the provided unique keys
/// (primary key or any key with a unique index on it).
///
/// let persons = try Person.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// ...
/// }
///
/// Records are iterated in unspecified order.
///
/// - parameters:
/// - db: A database connection.
/// - keys: An array of key dictionaries.
/// - 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 -> DatabaseCursor<Self>? {
guard let statement = try makeFetchByKeyStatement(db, keys: keys) else {
return nil
@@ -231,24 +241,6 @@ extension RowConvertible where Self: TableMapping {
return try fetchCursor(statement)
}
/// Returns a sequence of records identified by the provided unique keys
/// (primary key or any key with a unique index on it).
///
/// let persons = Person.fetch(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // DatabaseSequence<Person>
///
/// The order of records in the returned sequence is undefined.
///
/// - parameters:
/// - db: A Database.
/// - keys: An array of key dictionaries.
/// - returns: A sequence of records.
public static func fetch(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> DatabaseSequence<Self> {
guard let statement = try! makeFetchByKeyStatement(db, keys: keys) else {
return DatabaseSequence.makeEmptySequence(inDatabase: db)
}
return fetch(statement)
}
/// Returns an array of records identified by the provided unique keys
/// (primary key or any key with a unique index on it).
///
+69 -60
View File
@@ -82,7 +82,8 @@ try dbQueue.inDatabase { db in
```swift
dbQueue.inDatabase { db in
for row in Row.fetch(db, "SELECT * FROM pointOfInterests") {
let rows = try Row.fetchCursor(db, "SELECT * FROM pointOfInterests")
while let row = try rows.next() {
let title: String = row.value(named: "title")
let isFavorite: Bool = row.value(named: "favorite")
let coordinate = CLLocationCoordinate2DMake(
@@ -527,7 +528,8 @@ if let row = Row.fetchOne(db, "SELECT * FROM wines WHERE id = ?", arguments: [1]
**Values** are the Bool, Int, String, Date, Swift enums, etc. stored in row columns:
```swift
for url in URL.fetch(db, "SELECT url FROM wines") {
let urls = try URL.fetchCursor(db, "SELECT url FROM wines")
while let url = try urls.next() {
print(url)
}
```
@@ -547,32 +549,33 @@ let wines = Wine.fetchAll(db, "SELECT * FROM wines")
### Fetching Methods
**Throughout GRDB**, you can always fetch *sequences*, *arrays*, or *single values* of any fetchable type (database [row](#row-queries), simple [value](#value-queries), or custom [record](#records)):
**Throughout GRDB**, you can always fetch *cursors*, *arrays*, or *single values* of any fetchable type (database [row](#row-queries), simple [value](#value-queries), or custom [record](#records)):
```swift
Type.fetch(...) // DatabaseSequence<Type>
Type.fetchAll(...) // [Type]
Type.fetchOne(...) // Type?
Type.fetchCursor(...) // DatabaseCursor<Type>
Type.fetchAll(...) // [Type]
Type.fetchOne(...) // Type?
```
- `fetch` returns a **sequence** that is memory efficient, but must be consumed in a protected dispatch queue (you'll get a fatal error if you do otherwise).
- `fetchCursor` returns a **cursor** that is memory efficient, but must be consumed in a protected dispatch queue.
```swift
for row in Row.fetch(db, "SELECT ...") { // DatabaseSequence<Row>
let rows = try Row.fetchCursor(db, "SELECT ...") // DatabaseCursor<Row>
while let row = try rows.next() {
...
}
```
Don't modify the database during a sequence iteration:
Don't modify the database during a cursor iteration:
```swift
// Undefined behavior
for row in Row.fetch(db, "SELECT * FROM persons") {
while let row = try rows.next() {
try db.execute("DELETE FROM persons ...")
}
```
A sequence fetches a new set of results each time it is iterated.
Cursors share some traits with Swift sequences and iterators, and implement methods like enumerated, filter, map, etc.
- `fetchAll` returns an **array** that can be consumed on any thread. It contains copies of database values, and can take a lot of memory:
@@ -597,14 +600,15 @@ Type.fetchOne(...) // Type?
#### Fetching Rows
Fetch **sequences** of rows, **arrays**, or **single** rows (see [fetching methods](#fetching-methods)):
Fetch **cursors** of rows, **arrays**, or **single** rows (see [fetching methods](#fetching-methods)):
```swift
Row.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Row>
Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row]
Row.fetchOne(db, "SELECT ...", arguments: ...) // Row?
Row.fetchCursor(db, "SELECT ...", arguments: ...) // DatabaseCursor<Row>
Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row]
Row.fetchOne(db, "SELECT ...", arguments: ...) // Row?
for row in Row.fetch(db, "SELECT * FROM wines") {
let rows = try Row.fetchCursor(db, "SELECT * FROM wines")
while let row = try rows.next() {
let name: String = row.value(named: "name")
let color: Color = row.value(named: "color")
print(name, color)
@@ -625,11 +629,11 @@ let rows = Row.fetchAll(db,
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.).
Unlike row arrays that contain copies of the database rows, row sequences are close to the SQLite metal, and require a little care:
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
> :point_up: **Don't turn a row sequence into an array** with `Array(rowSequence)` or `rowSequence.filter { ... }`: you would not get the distinct rows you expect. To get an array, use `Row.fetchAll(...)`.
> :point_up: **Don't turn a row cursor into an array** with `Array(rowCursor)` or `rowCursor.filter { ... }`: you would not get the distinct rows you expect. To get an array, use `Row.fetchAll(...)`.
>
> :point_up: **Make sure you copy a row** whenever you extract it from a sequence for later use: `row.copy()`.
> :point_up: **Make sure you copy a row** whenever you extract it from a cursor for later use: `row.copy()`.
#### Column Values
@@ -724,7 +728,8 @@ Generally speaking, you can extract the type you need, *provided it can be conve
GRDB will sometimes let those conversions go through:
```swift
for row in Row.fetch(db, "SELECT '20 small cigars'") {
let rows = try Row.fetchCursor(db, "SELECT '20 small cigars'")
while let row = try rows.next() {
row.value(atIndex: 0) as Int // 20
}
```
@@ -817,16 +822,16 @@ for (columnName, databaseValue) in row { ... } // ("foo", 1), ("foo", 2)
### Value Queries
Instead of rows, you can directly fetch **[values](#values)**. Like rows, fetch them as **sequences**, **arrays**, or **single** values (see [fetching methods](#fetching-methods)). Values are extracted from the leftmost column of the SQL queries:
Instead of rows, you can directly fetch **[values](#values)**. Like rows, fetch them as **cursors**, **arrays**, or **single** values (see [fetching methods](#fetching-methods)). Values are extracted from the leftmost column of the SQL queries:
```swift
Int.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Int>
Int.fetchAll(db, "SELECT ...", arguments: ...) // [Int]
Int.fetchOne(db, "SELECT ...", arguments: ...) // Int?
Int.fetchCursor(db, "SELECT ...", arguments: ...) // DatabaseCursor<Int>
Int.fetchAll(db, "SELECT ...", arguments: ...) // [Int]
Int.fetchOne(db, "SELECT ...", arguments: ...) // Int?
// When database may contain NULL:
Optional<Int>.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Int?>
Optional<Int>.fetchAll(db, "SELECT ...", arguments: ...) // [Int?]
Optional<Int>.fetchCursor(db, "SELECT ...", arguments: ...) // DatabaseCursor<Int?>
Optional<Int>.fetchAll(db, "SELECT ...", arguments: ...) // [Int?]
```
`fetchOne` returns an optional value which is nil in two cases: either the SELECT statement yielded no row, or one row with a NULL value.
@@ -868,7 +873,8 @@ try db.execute(
Values can be [extracted from rows](#column-values):
```swift
for row in Row.fetch(db, "SELECT * FROM links") {
let rows = try Row.fetchCursor(db, "SELECT * FROM links")
while let row = try rows.next() {
let url: URL = row.value(named: "url")
let verified: Bool = row.value(named: "verified")
}
@@ -912,7 +918,8 @@ let link = Link.filter(urlColumn == url).fetchOne(db)
**Data** suits the BLOB SQLite columns. It can be stored and fetched from the database just like other [values](#values):
```swift
for row in Row.fetch(db, "SELECT data, ...") {
let rows = try Row.fetchCursor(db, "SELECT data, ...")
while let row = try rows.next() {
let data: Data = row.value(named: "data")
}
```
@@ -922,7 +929,7 @@ At each step of the request iteration, the `row.value` method creates *two copie
**You have the opportunity to save memory** by not copying the data fetched by SQLite:
```swift
for row in Row.fetch(db, "SELECT data, ...") {
while let row = try rows.next() {
let data = row.dataNoCopy(named: "data") // Data?
}
```
@@ -1077,7 +1084,8 @@ try db.execute(
arguments: [Grape.merlot, Color.red])
// Read
for rows in Row.fetch(db, "SELECT * FROM wines") {
let rows = try Row.fetchCursor(db, "SELECT * FROM wines")
while let row = try rows.next() {
let grape: Grape = row.value(named: "grape")
let color: Color = row.value(named: "color")
}
@@ -1256,7 +1264,7 @@ try updateStatement.execute()
Select statements can be used wherever a raw SQL query string would fit (see [fetch queries](#fetch-queries)):
```swift
for row in Row.fetch(selectStatement) { ... }
let rows = try Row.fetchCursor(selectStatement)
let persons = Person.fetchAll(selectStatement)
let person = Person.fetchOne(selectStatement)
```
@@ -1362,13 +1370,13 @@ try db.create(table: "persons") { t in
// <Row type:"table" name:"persons" tbl_name:"persons" rootpage:2
// sql:"CREATE TABLE persons(id INTEGER PRIMARY KEY, name TEXT)">
for row in Row.fetch(db, "SELECT * FROM sqlite_master") {
for row in Row.fetchAll(db, "SELECT * FROM sqlite_master") {
print(row)
}
// <Row cid:0 name:"id" type:"INTEGER" notnull:0 dflt_value:NULL pk:1>
// <Row cid:1 name:"name" type:"TEXT" notnull:0 dflt_value:NULL pk:0>
for row in Row.fetch(db, "PRAGMA table_info('persons')") {
for row in Row.fetchAll(db, "PRAGMA table_info('persons')") {
print(row)
}
```
@@ -1458,7 +1466,8 @@ let adapter = ScopeAdapter(["author": authorMapping])
Use the `Row.scoped(on:)` method to access the "author" scope:
```swift
for row in Row.fetch(db, sql, adapter: adapter) {
let rows = try Row.fetchCursor(db, sql, adapter: adapter)
while let row = try rows.next() {
// The fetched row, without adaptation:
row.value(named: "id") // 1
row.value(named: "title") // Moby-Dick
@@ -1476,7 +1485,8 @@ for row in Row.fetch(db, sql, adapter: adapter) {
> :bowtie: **Tip**: now that we have nice "id" and "name" columns, we can leverage [RowConvertible](#rowconvertible-protocol) types such as [Record](#record-class) subclasses. For example, assuming the Book type consumes the "author" scope in its row initializer and builds a Person from it, the same row can be consumed by both the Book and Person types:
>
> ```swift
> for book in Book.fetch(db, sql, adapter: adapter) {
> let books = try Book.fetchCursor(db, sql, adapter: adapter)
> while let book = try books.next() {
> book.title // Moby-Dick
> book.author?.name // Melville
> }
@@ -1502,7 +1512,8 @@ let mainAdapter = ColumnMapping(["id": "mainID", "name": "mainName"])
let bestFriendAdapter = ColumnMapping(["id": "friendID", "name": "friendName"])
let adapter = mainAdapter.addingScopes(["bestFriend": bestFriendAdapter])
for row in Row.fetch(db, sql, adapter: adapter) {
let rows = try Row.fetchCursor(db, sql, adapter: adapter)
while let row = try rows.next() {
// The fetched row, adapted with mainAdapter:
row.value(named: "id") // 1
row.value(named: "name") // Arthur
@@ -1515,7 +1526,8 @@ for row in Row.fetch(db, sql, adapter: adapter) {
}
// Assuming Person.init(row:) consumes the "bestFriend" scope:
for person in Person.fetch(db, sql, adapter: adapter) {
let persons = try Person.fetchCursor(db, sql, adapter: adapter)
while let person = try persons.next() {
person.name // Arthur
person.bestFriend?.name // Barbara
}
@@ -1797,12 +1809,12 @@ See [column values](#column-values) for more information about the `row.value()`
RowConvertible allows adopting types to be fetched from SQL queries:
```swift
PointOfInterest.fetch(db, "SELECT ...", arguments:...) // DatabaseSequence<PointOfInterest>
PointOfInterest.fetchAll(db, "SELECT ...", arguments:...) // [PointOfInterest]
PointOfInterest.fetchOne(db, "SELECT ...", arguments:...) // PointOfInterest?
PointOfInterest.fetchCursor(db, "SELECT ...", arguments:...) // DatabaseCursor<PointOfInterest>
PointOfInterest.fetchAll(db, "SELECT ...", arguments:...) // [PointOfInterest]
PointOfInterest.fetchOne(db, "SELECT ...", arguments:...) // PointOfInterest?
```
See [fetching methods](#fetching-methods) for information about the `fetch`, `fetchAll` and `fetchOne` methods. See [fetching rows](#fetching-rows) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [fetching rows](#fetching-rows) for more information about the query arguments.
### RowConvertible and Row Adapters
@@ -2400,7 +2412,7 @@ This is the list of record methods, along with their required protocols. The [Re
| **Counting Records** | | |
| `Type.fetchCount(db)` | [TableMapping](#tablemapping-protocol) | |
| `Type.filter(...).fetchCount(db)` | [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-2">²</a> |
| **Fetching Record Sequences** | | |
| **Fetching Record Cursors** | | |
| `Type.fetch(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | |
| `Type.fetch(db, keys: ...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-1">¹</a> |
| `Type.fetch(db, sql)` | [RowConvertible](#rowconvertible-protocol) | <a href="#list-of-record-methods-3">³</a> |
@@ -3008,12 +3020,12 @@ Once you have a request, you can fetch the records at the origin of the request:
let request = Person.filter(...)... // QueryInterfaceRequest<Person>
// Fetch persons:
request.fetch(db) // DatabaseSequence<Person>
request.fetchAll(db) // [Person]
request.fetchOne(db) // Person?
request.fetchCursor(db) // DatabaseCursor<Person>
request.fetchAll(db) // [Person]
request.fetchOne(db) // Person?
```
See [fetching methods](#fetching-methods) for information about the `fetch`, `fetchAll` and `fetchOne` methods.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods.
For example:
@@ -4614,9 +4626,9 @@ let sql = "SELECT ..."
// Some untrusted arguments for the query
let arguments: [String: Any] = ...
let rows = try Row.fetchCursor(db, sql, arguments: StatementArguments(arguments))
// Some untrusted iteration of database results:
for row in Row.fetch(db, sql, arguments: StatementArguments(arguments)) {
while let row = try rows.next() {
// Some untrusted database value:
let date: Date? = row.value(atIndex: 0)
}
@@ -4627,7 +4639,6 @@ It has several opportunities to throw fatal errors:
- **Untrusted SQL**: The sql string may contain invalid sql, or refer to non-existing tables or columns.
- **Untrusted arguments dictionary**: The dictionary may contain values that do not conform to the [DatabaseValueConvertible protocol](#values).
- **Untrusted arguments fitting**: The dictionary may miss values required by the statement.
- **Untrusted SQLite execution**: SQLite may throw an error at each step of the results iteration.
- **Untrusted database content**: The row may contain a non-null value that can't be turned into a date.
In such a situation where nothing can be trusted, you can still avoid fatal errors by exposing and handling each failure point, one level down in the GRDB API:
@@ -4643,9 +4654,8 @@ if let arguments = StatementArguments(arguments) {
try statement.validate(arguments: arguments)
statement.unsafeSetArguments(arguments)
// Untrusted SQLite execution
var iterator = Row.fetch(statement).makeIterator()
while let row = try iterator.step() {
var cursor = try Row.fetchCursor(statement)
while let row = try iterator.next() {
// Untrusted database content
let dbv: DatabaseValue = row.value(atIndex: 0)
if dbv.isNull {
@@ -4935,13 +4945,13 @@ let hallOfFame = Person.order(scoreColumn.desc).limit(5).fetchAll(db)
**Don't copy values unless necessary**
Particularly: the Array returned by the `fetchAll` method, and the sequence returned by `fetch` aren't the same:
Particularly: the Array returned by the `fetchAll` method, and the cursor returned by `fetchCursor` aren't the same:
`fetchAll` copies all values from the database into memory, when `fetch` iterates database results as they are generated by SQLite, taking profit from SQLite efficiency.
`fetchAll` copies all values from the database into memory, when `fetchCursor` iterates database results as they are generated by SQLite, taking profit from SQLite efficiency.
You should only load arrays if you need to keep them for later use (such as iterating their contents in the main thread). Otherwise, use `fetch`.
You should only load arrays if you need to keep them for later use (such as iterating their contents in the main thread). Otherwise, use `fetchCursor`.
See [fetching methods](#fetching-methods) for more information about `fetchAll` and `fetch`. See also the [Row.dataNoCopy](#data-and-memory-savings) method.
See [fetching methods](#fetching-methods) for more information about `fetchAll` and `fetchCursor`. See also the [Row.dataNoCopy](#data-and-memory-savings) method.
**Don't update rows unless necessary**
@@ -5031,14 +5041,13 @@ For example, when fetching values, prefer loading columns by index:
```swift
// Strings & dictionaries
for person in Person.fetch(db) {
...
}
let persons = Person.fetchAll(db)
// Column indexes
// SELECT id, name, email FROM persons
let request = Person.select(idColumn, nameColumn, emailColumn)
for row in Row.fetch(db, request) {
let rows = try Row.fetchCursor(db, request)
while let row = try rows.next() {
let id: Int64 = row.value(atIndex: 0)
let name: String = row.value(atIndex: 1)
let email: String = row.value(atIndex: 2)
@@ -44,8 +44,9 @@ class FetchNamedValuesTests: XCTestCase {
measure {
var count = 0
dbQueue.inDatabase { db in
for row in Row.fetch(db, "SELECT * FROM items") {
try! dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, "SELECT * FROM items")
while let row = try rows.next() {
_ = row.value(named: "i0") as Int
_ = row.value(named: "i1") as Int
_ = row.value(named: "i2") as Int
@@ -85,8 +85,9 @@ class FetchPositionalValuesTests: XCTestCase {
measure {
var count = 0
dbQueue.inDatabase { db in
for row in Row.fetch(db, "SELECT * FROM items") {
try! dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, "SELECT * FROM items")
while let row = try rows.next() {
_ = row.value(atIndex: 0) as Int
_ = row.value(atIndex: 1) as Int
_ = row.value(atIndex: 2) as Int
+2 -1
View File
@@ -37,7 +37,8 @@ class DataMemoryTests: GRDBTestCase {
let data = "foo".data(using: .utf8)
try db.execute("INSERT INTO datas (data) VALUES (?)", arguments: [data])
for row in Row.fetch(db, "SELECT * FROM datas") {
let rows = try Row.fetchCursor(db, "SELECT * FROM datas")
while let row = try rows.next() {
let sqliteStatement = row.sqliteStatement
let sqliteBytes = sqlite3_column_blob(sqliteStatement, 0)
@@ -91,24 +91,24 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
// end end releaseMemory
let block1 = { () in
dbPool.read { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(try cursor.next() != nil)
s3.signal()
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let block2 = { () in
_ = s1.wait(timeout: .distantFuture)
dbPool.read { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s2.signal()
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let block3 = { () in
@@ -246,13 +246,13 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
}
let block2 = { [weak dbPool] () in
weak var connection: Database? = nil
var iterator: DatabaseIterator<Int>? = nil
var cursor: DatabaseCursor<Int>? = nil
do {
if let dbPool = dbPool {
dbPool.write { db in
try! dbPool.write { db in
connection = db
iterator = Int.fetch(db, "SELECT id FROM items").makeIterator()
XCTAssertTrue(iterator!.next() != nil)
cursor = try Int.fetchCursor(db, "SELECT id FROM items")
XCTAssertTrue(try cursor!.next() != nil)
s1.signal()
}
} else {
@@ -262,9 +262,9 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
_ = s2.wait(timeout: .distantFuture)
do {
XCTAssertTrue(dbPool == nil)
XCTAssertTrue(iterator!.next() != nil)
XCTAssertTrue(iterator!.next() == nil)
iterator = nil
XCTAssertTrue(try! cursor!.next() != nil)
XCTAssertTrue(try! cursor!.next() == nil)
cursor = nil
XCTAssertTrue(connection == nil)
}
}
@@ -159,13 +159,13 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
}
let block2 = { [weak dbQueue] () in
weak var connection: Database? = nil
var iterator: DatabaseIterator<Int>? = nil
var cursor: DatabaseCursor<Int>? = nil
do {
if let dbQueue = dbQueue {
dbQueue.write { db in
try! dbQueue.write { db in
connection = db
iterator = Int.fetch(db, "SELECT id FROM items").makeIterator()
XCTAssertTrue(iterator!.next() != nil)
cursor = try Int.fetchCursor(db, "SELECT id FROM items")
XCTAssertTrue(try cursor!.next() != nil)
s1.signal()
}
} else {
@@ -175,9 +175,9 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
_ = s2.wait(timeout: .distantFuture)
do {
XCTAssertTrue(dbQueue == nil)
XCTAssertTrue(iterator!.next() != nil)
XCTAssertTrue(iterator!.next() == nil)
iterator = nil
XCTAssertTrue(try! cursor!.next() != nil)
XCTAssertTrue(try! cursor!.next() == nil)
cursor = nil
XCTAssertTrue(connection == nil)
}
}
+4 -48
View File
@@ -234,8 +234,8 @@ class DatabaseTests : GRDBTestCase {
var names: [String?] = []
var ages: [Int?] = []
let rows = Row.fetch(db, "SELECT * FROM persons ORDER BY name")
for row in rows {
let rows = try Row.fetchCursor(db, "SELECT * FROM persons ORDER BY name")
while let row = try rows.next() {
// The tested function:
let name: String? = row.value(atIndex: 0)
let age: Int? = row.value(atIndex: 1)
@@ -261,8 +261,8 @@ class DatabaseTests : GRDBTestCase {
var names: [String?] = []
var ages: [Int?] = []
let rows = Row.fetch(db, "SELECT * FROM persons ORDER BY name")
for row in rows {
let rows = try Row.fetchCursor(db, "SELECT * FROM persons ORDER BY name")
while let row = try rows.next() {
// The tested function:
let name: String? = row.value(named: "name")
let age: Int? = row.value(named: "age")
@@ -278,50 +278,6 @@ class DatabaseTests : GRDBTestCase {
}
}
func testRowSequenceCanBeIteratedTwice() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inTransaction { db in
try db.execute("CREATE TABLE persons (name TEXT)")
try db.execute("INSERT INTO persons (name) VALUES (:name)", arguments: ["name": "Arthur"])
try db.execute("INSERT INTO persons (name) VALUES (:name)", arguments: ["name": "Barbara"])
let rows = Row.fetch(db, "SELECT * FROM persons ORDER BY name")
var names1: [String?] = rows.map { $0.value(named: "name") as String? }
var names2: [String?] = rows.map { $0.value(named: "name") as String? }
XCTAssertEqual(names1[0]!, "Arthur")
XCTAssertEqual(names1[1]!, "Barbara")
XCTAssertEqual(names2[0]!, "Arthur")
XCTAssertEqual(names2[1]!, "Barbara")
return .commit
}
}
}
func testValueSequenceCanBeIteratedTwice() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inTransaction { db in
try db.execute("CREATE TABLE persons (name TEXT)")
try db.execute("INSERT INTO persons (name) VALUES (:name)", arguments: ["name": "Arthur"])
try db.execute("INSERT INTO persons (name) VALUES (:name)", arguments: ["name": "Barbara"])
let nameSequence = String.fetch(db, "SELECT name FROM persons ORDER BY name")
var names1 = Array(nameSequence)
var names2 = Array(nameSequence)
XCTAssertEqual(names1[0], "Arthur")
XCTAssertEqual(names1[1], "Barbara")
XCTAssertEqual(names2[0], "Arthur")
XCTAssertEqual(names2[1], "Barbara")
return .commit
}
}
}
func testDatabaseCanBeUsedOutsideOfDatabaseQueueBlockAsLongAsTheQueueIsCorrect() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -67,25 +67,25 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// COMMIT
let block1 = { () in
dbPool.read { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let block2 = { () in
dbPool.read { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
_ = s1.wait(timeout: .distantFuture)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(try cursor.next() != nil)
s2.signal()
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let blocks = [block1, block2]
@@ -119,13 +119,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// COMMIT
let block1 = { () in
dbPool.read { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let block2 = { () in
@@ -171,13 +171,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// COMMIT
let block1 = { () in
dbPool.read { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let block2 = { () in
@@ -331,13 +331,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// SELECT COUNT(*) FROM items -> 0
let block1 = { () in
dbPool.nonIsolatedRead { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.nonIsolatedRead { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
}
}
@@ -382,13 +382,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// end
let block1 = { () in
dbPool.nonIsolatedRead { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.nonIsolatedRead { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let block2 = { () in
@@ -47,25 +47,25 @@ class DatabasePoolReadOnlyTests: GRDBTestCase {
// end
let block1 = { () in
dbPool.read { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let block2 = { () in
dbPool.read { db in
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
_ = s1.wait(timeout: .distantFuture)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(try cursor.next() != nil)
s2.signal()
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
}
}
let blocks = [block1, block2]
@@ -61,7 +61,8 @@ class DatabaseSchedulerTests: GRDBTestCase {
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
try dbQueue2.inDatabase { db2 in
try db2.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
for row in Row.fetch(db1, "SELECT * FROM items") {
let rows = try Row.fetchCursor(db1, "SELECT * FROM items")
while let row = try rows.next() {
try db2.execute("INSERT INTO items (id) VALUES (?)", arguments: [row.value(named: "id")])
}
}
@@ -82,7 +83,8 @@ class DatabaseSchedulerTests: GRDBTestCase {
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
try dbQueue2.inDatabase { db2 in
try db2.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
for row in Row.fetch(db1, "SELECT * FROM items") {
let rows = try Row.fetchCursor(db1, "SELECT * FROM items")
while let row = try rows.next() {
try db2.execute("INSERT INTO items (id) VALUES (?)", arguments: [row.value(named: "id")])
}
}
@@ -103,7 +105,8 @@ class DatabaseSchedulerTests: GRDBTestCase {
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
try dbPool2.write { db2 in
try db2.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
for row in Row.fetch(db1, "SELECT * FROM items") {
let rows = try Row.fetchCursor(db1, "SELECT * FROM items")
while let row = try rows.next() {
try db2.execute("INSERT INTO items (id) VALUES (?)", arguments: [row.value(named: "id")])
}
}
@@ -124,7 +127,8 @@ class DatabaseSchedulerTests: GRDBTestCase {
try db1.execute("INSERT INTO items (id) VALUES (NULL)")
try dbPool2.write { db2 in
try db2.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
for row in Row.fetch(db1, "SELECT * FROM items") {
let rows = try Row.fetchCursor(db1, "SELECT * FROM items")
while let row = try rows.next() {
try db2.execute("INSERT INTO items (id) VALUES (?)", arguments: [row.value(named: "id")])
}
}
@@ -64,38 +64,6 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase {
}
}
func testFetchSequenceFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
let sequence = WrappedInt.fetch(statement)
XCTAssertEqual(sequence.map { $0.int }, [1,2])
}
}
}
func testFetchSequenceFromStatementWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
let sequence = WrappedInt.fetch(statement, adapter: SuffixRowAdapter(fromIndex: 1))
XCTAssertEqual(sequence.map { $0.int }, [-1,-2])
}
}
}
func testFetchAllFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -208,36 +176,6 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase {
}
}
func testFetchSequenceFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
let sequence = WrappedInt.fetch(db, "SELECT int, -int FROM ints ORDER BY int")
XCTAssertEqual(sequence.map { $0.int }, [1,2])
}
}
}
func testFetchSequenceFromSQLWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
let sequence = WrappedInt.fetch(db, "SELECT int, -int FROM ints ORDER BY int", adapter: SuffixRowAdapter(fromIndex: 1))
XCTAssertEqual(sequence.map { $0.int }, [-1,-2])
}
}
}
func testFetchAllFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -334,27 +272,6 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase {
}
}
func testFetchSequenceFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
struct Request : FetchRequest {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
return (statement, SuffixRowAdapter(fromIndex: 1))
}
}
let sequence = WrappedInt.fetch(db, Request())
XCTAssertEqual(sequence.map { $0.int }, [-1,-2])
}
}
}
func testFetchAllFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -441,44 +358,6 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase {
}
}
func testOptionalFetchSequenceFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
let sequence = Optional<WrappedInt>.fetch(statement)
let ints = sequence.map { $0?.int }
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!, 1)
}
}
}
func testOptionalFetchSequenceFromStatementWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
let sequence = Optional<WrappedInt>.fetch(statement, adapter: SuffixRowAdapter(fromIndex: 1))
let ints = sequence.map { $0?.int }
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!, -1)
}
}
}
func testOptionalFetchAllFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -553,42 +432,6 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase {
}
}
func testOptionalFetchSequenceFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let sequence = Optional<WrappedInt>.fetch(db, "SELECT int, -int FROM ints ORDER BY int")
let ints = sequence.map { $0?.int }
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!, 1)
}
}
}
func testOptionalFetchSequenceFromSQLWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let sequence = Optional<WrappedInt>.fetch(db, "SELECT int, -int FROM ints ORDER BY int", adapter: SuffixRowAdapter(fromIndex: 1))
let ints = sequence.map { $0?.int }
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!, -1)
}
}
}
func testOptionalFetchAllFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -649,30 +492,6 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase {
}
}
func testOptionalFetchSequenceFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
struct Request : FetchRequest {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
return (statement, SuffixRowAdapter(fromIndex: 1))
}
}
let sequence = Optional<WrappedInt>.fetch(db, Request())
let ints = sequence.map { $0?.int }
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!, -1)
}
}
}
func testOptionalFetchAllFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
+38 -32
View File
@@ -462,44 +462,50 @@ class AdapterRowTests : RowTestCase {
}
func testCopy() {
let dbQueue = DatabaseQueue()
dbQueue.inDatabase { db in
let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"])
.addingScopes(["sub": ColumnMapping(["a": "baseb"])])
var copiedRow: Row? = nil
for baseRow in Row.fetch(db, "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter) {
copiedRow = baseRow.copy()
}
if let copiedRow = copiedRow {
XCTAssertEqual(copiedRow.count, 3)
XCTAssertEqual(copiedRow.value(named: "a") as Int, 0)
XCTAssertEqual(copiedRow.value(named: "b") as Int, 1)
XCTAssertEqual(copiedRow.value(named: "c") as Int, 2)
if let scope = copiedRow.scoped(on: "sub") {
XCTAssertEqual(scope.count, 1)
XCTAssertEqual(scope.value(named: "a") as Int, 1)
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"])
.addingScopes(["sub": ColumnMapping(["a": "baseb"])])
var copiedRow: Row? = nil
let baseRows = try Row.fetchCursor(db, "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter)
while let baseRow = try baseRows.next() {
copiedRow = baseRow.copy()
}
if let copiedRow = copiedRow {
XCTAssertEqual(copiedRow.count, 3)
XCTAssertEqual(copiedRow.value(named: "a") as Int, 0)
XCTAssertEqual(copiedRow.value(named: "b") as Int, 1)
XCTAssertEqual(copiedRow.value(named: "c") as Int, 2)
if let scope = copiedRow.scoped(on: "sub") {
XCTAssertEqual(scope.count, 1)
XCTAssertEqual(scope.value(named: "a") as Int, 1)
}
} else {
XCTFail()
}
} else {
XCTFail()
}
}
}
func testEqualityWithCopy() {
let dbQueue = DatabaseQueue()
dbQueue.inDatabase { db in
let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"])
var row: Row? = nil
for baseRow in Row.fetch(db, "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter) {
row = baseRow.copy()
XCTAssertEqual(row, baseRow)
}
if let row = row {
let copiedRow = row.copy()
XCTAssertEqual(row, copiedRow)
} else {
XCTFail()
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"])
var row: Row? = nil
let baseRows = try Row.fetchCursor(db, "SELECT 0 AS basea, 'XXX' AS extra, 1 AS baseb, 2 as basec", adapter: adapter)
while let baseRow = try baseRows.next() {
row = baseRow.copy()
XCTAssertEqual(row, baseRow)
}
if let row = row {
let copiedRow = row.copy()
XCTAssertEqual(row, copiedRow)
} else {
XCTFail()
}
}
}
}
+55 -36
View File
@@ -22,7 +22,8 @@ class MetalRowTests : RowTestCase {
try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)")
try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)")
var rowFetched = false
for row in Row.fetch(db, "SELECT * FROM ints") {
let rows = try Row.fetchCursor(db, "SELECT * FROM ints")
while let row = try rows.next() {
rowFetched = true
var columnNames = [String]()
var ints = [Int]()
@@ -49,7 +50,8 @@ class MetalRowTests : RowTestCase {
try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)")
try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)")
var rowFetched = false
for row in Row.fetch(db, "SELECT * FROM ints") {
let rows = try Row.fetchCursor(db, "SELECT * FROM ints")
while let row = try rows.next() {
rowFetched = true
// Raw extraction
@@ -84,7 +86,8 @@ class MetalRowTests : RowTestCase {
try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)")
try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)")
var rowFetched = false
for row in Row.fetch(db, "SELECT * FROM ints") {
let rows = try Row.fetchCursor(db, "SELECT * FROM ints")
while let row = try rows.next() {
rowFetched = true
// Raw extraction
@@ -114,7 +117,8 @@ class MetalRowTests : RowTestCase {
try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)")
try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)")
var rowFetched = false
for row in Row.fetch(db, "SELECT * FROM ints") {
let rows = try Row.fetchCursor(db, "SELECT * FROM ints")
while let row = try rows.next() {
rowFetched = true
// Raw extraction
@@ -140,10 +144,11 @@ class MetalRowTests : RowTestCase {
func testDataNoCopy() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
try dbQueue.inDatabase { db in
let data = "foo".data(using: .utf8)!
var rowFetched = false
for row in Row.fetch(db, "SELECT ? AS a", arguments: [data]) {
let rows = try Row.fetchCursor(db, "SELECT ? AS a", arguments: [data])
while let row = try rows.next() {
rowFetched = true
XCTAssertEqual(row.dataNoCopy(atIndex: 0), data)
@@ -158,9 +163,10 @@ class MetalRowTests : RowTestCase {
func testRowDatabaseValueAtIndex() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
try dbQueue.inDatabase { db in
var rowFetched = false
for row in Row.fetch(db, "SELECT NULL, 1, 1.1, 'foo', x'53514C697465'") {
let rows = try Row.fetchCursor(db, "SELECT NULL, 1, 1.1, 'foo', x'53514C697465'")
while let row = try rows.next() {
rowFetched = true
guard case .null = (row.value(atIndex: 0) as DatabaseValue).storage else { XCTFail(); return }
guard case .int64(let int64) = (row.value(atIndex: 1) as DatabaseValue).storage, int64 == 1 else { XCTFail(); return }
@@ -176,9 +182,10 @@ class MetalRowTests : RowTestCase {
func testRowDatabaseValueNamed() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
try dbQueue.inDatabase { db in
var rowFetched = false
for row in Row.fetch(db, "SELECT NULL AS \"null\", 1 AS \"int64\", 1.1 AS \"double\", 'foo' AS \"string\", x'53514C697465' AS \"blob\"") {
let rows = try Row.fetchCursor(db, "SELECT NULL AS \"null\", 1 AS \"int64\", 1.1 AS \"double\", 'foo' AS \"string\", x'53514C697465' AS \"blob\"")
while let row = try rows.next() {
rowFetched = true
guard case .null = (row.value(named: "null") as DatabaseValue).storage else { XCTFail(); return }
guard case .int64(let int64) = (row.value(named: "int64") as DatabaseValue).storage, int64 == 1 else { XCTFail(); return }
@@ -198,7 +205,8 @@ class MetalRowTests : RowTestCase {
try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)")
try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)")
var rowFetched = false
for row in Row.fetch(db, "SELECT * FROM ints") {
let rows = try Row.fetchCursor(db, "SELECT * FROM ints")
while let row = try rows.next() {
rowFetched = true
XCTAssertEqual(row.count, 3)
}
@@ -214,7 +222,8 @@ class MetalRowTests : RowTestCase {
try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)")
try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)")
var rowFetched = false
for row in Row.fetch(db, "SELECT a, b, c FROM ints") {
let rows = try Row.fetchCursor(db, "SELECT a, b, c FROM ints")
while let row = try rows.next() {
rowFetched = true
XCTAssertEqual(Array(row.columnNames), ["a", "b", "c"])
}
@@ -230,7 +239,8 @@ class MetalRowTests : RowTestCase {
try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)")
try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)")
var rowFetched = false
for row in Row.fetch(db, "SELECT a, b, c FROM ints") {
let rows = try Row.fetchCursor(db, "SELECT a, b, c FROM ints")
while let row = try rows.next() {
rowFetched = true
XCTAssertEqual(Array(row.databaseValues), [0.databaseValue, 1.databaseValue, 2.databaseValue])
}
@@ -242,9 +252,10 @@ class MetalRowTests : RowTestCase {
func testRowIsCaseInsensitive() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
try dbQueue.inDatabase { db in
var rowFetched = false
for row in Row.fetch(db, "SELECT 'foo' AS nAmE") {
let rows = try Row.fetchCursor(db, "SELECT 'foo' AS nAmE")
while let row = try rows.next() {
rowFetched = true
XCTAssertEqual(row.value(named: "name") as DatabaseValue, "foo".databaseValue)
XCTAssertEqual(row.value(named: "NAME") as DatabaseValue, "foo".databaseValue)
@@ -261,9 +272,10 @@ class MetalRowTests : RowTestCase {
func testRowIsCaseInsensitiveAndReturnsLeftmostMatchingColumn() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
try dbQueue.inDatabase { db in
var rowFetched = false
for row in Row.fetch(db, "SELECT 1 AS name, 2 AS NAME") {
let rows = try Row.fetchCursor(db, "SELECT 1 AS name, 2 AS NAME")
while let row = try rows.next() {
rowFetched = true
XCTAssertEqual(row.value(named: "name") as DatabaseValue, 1.databaseValue)
XCTAssertEqual(row.value(named: "NAME") as DatabaseValue, 1.databaseValue)
@@ -280,9 +292,10 @@ class MetalRowTests : RowTestCase {
func testMissingColumn() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
try dbQueue.inDatabase { db in
var rowFetched = false
for row in Row.fetch(db, "SELECT 'foo' AS name") {
let rows = try Row.fetchCursor(db, "SELECT 'foo' AS name")
while let row = try rows.next() {
rowFetched = true
XCTAssertFalse(row.hasColumn("missing"))
XCTAssertTrue(row.value(named: "missing") as DatabaseValue? == nil)
@@ -296,9 +309,10 @@ class MetalRowTests : RowTestCase {
func testRowHasColumnIsCaseInsensitive() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
try dbQueue.inDatabase { db in
var rowFetched = false
for row in Row.fetch(db, "SELECT 'foo' AS nAmE, 1 AS foo") {
let rows = try Row.fetchCursor(db, "SELECT 'foo' AS nAmE, 1 AS foo")
while let row = try rows.next() {
rowFetched = true
XCTAssertTrue(row.hasColumn("name"))
XCTAssertTrue(row.hasColumn("NAME"))
@@ -314,25 +328,29 @@ class MetalRowTests : RowTestCase {
}
func testVariants() {
let dbQueue = DatabaseQueue()
dbQueue.inDatabase { db in
var rowFetched = false
for row in Row.fetch(db, "SELECT 'foo' AS nAmE, 1 AS foo") {
rowFetched = true
XCTAssertTrue(row.scoped(on: "missing") == nil)
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var rowFetched = false
let rows = try Row.fetchCursor(db, "SELECT 'foo' AS nAmE, 1 AS foo")
while let row = try rows.next() {
rowFetched = true
XCTAssertTrue(row.scoped(on: "missing") == nil)
}
XCTAssertTrue(rowFetched)
}
XCTAssertTrue(rowFetched)
}
}
func testCopy() {
assertNoError {
let dbQueue = DatabaseQueue()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)")
try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)")
var rowFetched = false
for row in Row.fetch(db, "SELECT * FROM ints") {
let rows = try Row.fetchCursor(db, "SELECT * FROM ints")
while let row = try rows.next() {
rowFetched = true
let copiedRow = row.copy()
XCTAssertEqual(copiedRow.count, 3)
@@ -347,12 +365,13 @@ class MetalRowTests : RowTestCase {
func testEqualityWithCopy() {
assertNoError {
let dbQueue = DatabaseQueue()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (a INTEGER, b INTEGER, c INTEGER)")
try db.execute("INSERT INTO ints (a,b,c) VALUES (0, 1, 2)")
var rowFetched = false
for row in Row.fetch(db, "SELECT * FROM ints") {
let rows = try Row.fetchCursor(db, "SELECT * FROM ints")
while let row = try rows.next() {
rowFetched = true
let copiedRow = row.copy()
XCTAssertEqual(row, copiedRow)
@@ -362,12 +381,12 @@ class MetalRowTests : RowTestCase {
}
}
func testDatabaseSequenceMap() {
func testDatabaseCursorMap() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let sequence: DatabaseSequence<Row> = Row.fetch(db, "SELECT 1 UNION SELECT 2 UNION SELECT 3")
let values = sequence.map { $0.value(atIndex: 0) as Int }
try dbQueue.inDatabase { db in
let cursor = try Row.fetchCursor(db, "SELECT 1 UNION SELECT 2 UNION SELECT 3")
let values = try cursor.map { $0.value(atIndex: 0) as Int }
XCTAssertEqual(values, [1, 2, 3])
}
}
@@ -100,42 +100,6 @@ class RowConvertibleTests: GRDBTestCase {
}
}
func testFetchSequenceFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO structs (firstName, lastName) VALUES (?, ?)", arguments: ["Arthur", "Martin"])
let statement = try db.makeSelectStatement("SELECT * FROM structs")
let ss = SimpleRowConvertible.fetch(statement)
let s = Array(ss).first!
XCTAssertEqual(s.firstName, "Arthur")
XCTAssertEqual(s.lastName, "Martin")
XCTAssertTrue(s.fetched)
}
}
}
func testFetchSequenceFromStatementWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let adapter = ColumnMapping(["firstName": "firstName1", "lastName": "lastName1"])
.addingScopes(["bestFriend": ColumnMapping(["firstName": "firstName2", "lastName": "lastName2"])])
let sql = "SELECT ? AS firstName1, ? AS lastName1, ? AS firstName2, ? AS lastName2"
let arguments = StatementArguments(["Stan", "Laurel", "Oliver", "Hardy"])
let statement = try db.makeSelectStatement(sql)
let ss = Person.fetch(statement, arguments: arguments, adapter: adapter)
let s = Array(ss).first!
XCTAssertEqual(s.firstName, "Stan")
XCTAssertEqual(s.lastName, "Laurel")
XCTAssertTrue(s.fetched)
XCTAssertEqual(s.bestFriend!.firstName, "Oliver")
XCTAssertEqual(s.bestFriend!.lastName, "Hardy")
XCTAssertTrue(s.bestFriend!.fetched)
}
}
}
func testFetchAllFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -243,40 +207,6 @@ class RowConvertibleTests: GRDBTestCase {
}
}
func testFetchSequenceFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO structs (firstName, lastName) VALUES (?, ?)", arguments: ["Arthur", "Martin"])
let ss = SimpleRowConvertible.fetch(db, "SELECT * FROM structs")
let s = Array(ss).first!
XCTAssertEqual(s.firstName, "Arthur")
XCTAssertEqual(s.lastName, "Martin")
XCTAssertTrue(s.fetched)
}
}
}
func testFetchSequenceFromSQLWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let adapter = ColumnMapping(["firstName": "firstName1", "lastName": "lastName1"])
.addingScopes(["bestFriend": ColumnMapping(["firstName": "firstName2", "lastName": "lastName2"])])
let sql = "SELECT ? AS firstName1, ? AS lastName1, ? AS firstName2, ? AS lastName2"
let arguments = StatementArguments(["Stan", "Laurel", "Oliver", "Hardy"])
let ss = Person.fetch(db, sql, arguments: arguments, adapter: adapter)
let s = Array(ss).first!
XCTAssertEqual(s.firstName, "Stan")
XCTAssertEqual(s.lastName, "Laurel")
XCTAssertTrue(s.fetched)
XCTAssertEqual(s.bestFriend!.firstName, "Oliver")
XCTAssertEqual(s.bestFriend!.lastName, "Hardy")
XCTAssertTrue(s.bestFriend!.fetched)
}
}
}
func testFetchAllFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -374,34 +304,6 @@ class RowConvertibleTests: GRDBTestCase {
}
}
func testFetchSequenceFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
struct Request : FetchRequest {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let adapter = ColumnMapping(["firstName": "firstName1", "lastName": "lastName1"])
.addingScopes(["bestFriend": ColumnMapping(["firstName": "firstName2", "lastName": "lastName2"])])
let sql = "SELECT ? AS firstName1, ? AS lastName1, ? AS firstName2, ? AS lastName2"
let arguments = StatementArguments(["Stan", "Laurel", "Oliver", "Hardy"])
let statement = try db.makeSelectStatement(sql)
statement.arguments = arguments
return (statement, adapter)
}
}
let ss = Person.fetch(db, Request())
let s = Array(ss).first!
XCTAssertEqual(s.firstName, "Stan")
XCTAssertEqual(s.lastName, "Laurel")
XCTAssertTrue(s.fetched)
XCTAssertEqual(s.bestFriend!.firstName, "Oliver")
XCTAssertEqual(s.bestFriend!.lastName, "Hardy")
XCTAssertTrue(s.bestFriend!.fetched)
}
}
}
func testFetchAllFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -87,80 +87,6 @@ class SelectStatementTests : GRDBTestCase {
}
}
func testRowSequenceCanBeFetchedTwice() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeSelectStatement("SELECT * FROM persons ORDER BY name")
var names1 = Row.fetch(statement).map { $0.value(named: "name") as String }
var names2 = Row.fetch(statement).map { $0.value(named: "name") as String }
XCTAssertEqual(names1[0], "Arthur")
XCTAssertEqual(names1[1], "Barbara")
XCTAssertEqual(names1[2], "Craig")
XCTAssertEqual(names2[0], "Arthur")
XCTAssertEqual(names2[1], "Barbara")
XCTAssertEqual(names2[2], "Craig")
}
}
}
func testRowSequenceCanBeIteratedTwice() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeSelectStatement("SELECT * FROM persons ORDER BY name")
let rows = Row.fetch(statement)
var names1 = rows.map { $0.value(named: "name") as String }
var names2 = rows.map { $0.value(named: "name") as String }
XCTAssertEqual(names1[0], "Arthur")
XCTAssertEqual(names1[1], "Barbara")
XCTAssertEqual(names1[2], "Craig")
XCTAssertEqual(names2[0], "Arthur")
XCTAssertEqual(names2[1], "Barbara")
XCTAssertEqual(names2[2], "Craig")
}
}
}
func testValueSequenceCanBeFetchedTwice() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeSelectStatement("SELECT name FROM persons ORDER BY name")
var names1 = Array(String.fetch(statement))
var names2 = Array(String.fetch(statement))
XCTAssertEqual(names1[0], "Arthur")
XCTAssertEqual(names1[1], "Barbara")
XCTAssertEqual(names1[2], "Craig")
XCTAssertEqual(names2[0], "Arthur")
XCTAssertEqual(names2[1], "Barbara")
XCTAssertEqual(names2[2], "Craig")
}
}
}
func testValueSequenceCanBeIteratedTwice() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeSelectStatement("SELECT name FROM persons ORDER BY name")
let nameSequence = String.fetch(statement)
var names1 = Array(nameSequence)
var names2 = Array(nameSequence)
XCTAssertEqual(names1[0], "Arthur")
XCTAssertEqual(names1[1], "Barbara")
XCTAssertEqual(names1[2], "Craig")
XCTAssertEqual(names2[0], "Arthur")
XCTAssertEqual(names2[1], "Barbara")
XCTAssertEqual(names2[2], "Craig")
}
}
}
func testDatabaseErrorThrownBySelectStatementContainSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -62,27 +62,32 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase {
func testRowExtraction() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
for row in Row.fetch(db, "SELECT NULL") {
try dbQueue.inDatabase { db in
var rows = try Row.fetchCursor(db, "SELECT NULL")
while let row = try rows.next() {
let one: FastWrappedInt? = row.value(atIndex: 0)
XCTAssertTrue(one == nil)
}
for row in Row.fetch(db, "SELECT 1") {
rows = try Row.fetchCursor(db, "SELECT 1")
while let row = try rows.next() {
let one: FastWrappedInt? = row.value(atIndex: 0)
XCTAssertEqual(one!.int, 1)
XCTAssertEqual(one!.fast, true)
}
for row in Row.fetch(db, "SELECT 1 AS int") {
rows = try Row.fetchCursor(db, "SELECT 1 AS int")
while let row = try rows.next() {
let one: FastWrappedInt? = row.value(named: "int")
XCTAssertEqual(one!.int, 1)
XCTAssertEqual(one!.fast, true)
}
for row in Row.fetch(db, "SELECT 1") {
rows = try Row.fetchCursor(db, "SELECT 1")
while let row = try rows.next() {
let one: FastWrappedInt = row.value(atIndex: 0)
XCTAssertEqual(one.int, 1)
XCTAssertEqual(one.fast, true)
}
for row in Row.fetch(db, "SELECT 1 AS int") {
rows = try Row.fetchCursor(db, "SELECT 1 AS int")
while let row = try rows.next() {
let one: FastWrappedInt = row.value(named: "int")
XCTAssertEqual(one.int, 1)
XCTAssertEqual(one.fast, true)
@@ -139,41 +144,6 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase {
}
}
func testFetchSequenceFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
let sequence = FastWrappedInt.fetch(statement)
XCTAssertEqual(Array(sequence).map { $0.int }, [1,2])
XCTAssertEqual(Array(sequence).map { $0.fast }, [true, true])
}
}
}
func testFetchSequenceFromStatementWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
let sequence = FastWrappedInt.fetch(statement, adapter: SuffixRowAdapter(fromIndex: 1))
XCTAssertEqual(Array(sequence).map { $0.int }, [-1,-2])
// NICE TO HAVE: make it fast, and the following test pass:
// XCTAssertEqual(Array(sequence).map { $0.fast }, [true, true])
}
}
}
func testFetchAllFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -302,39 +272,6 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase {
}
}
func testFetchSequenceFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
let sequence = FastWrappedInt.fetch(db, "SELECT int, -int FROM ints ORDER BY int")
XCTAssertEqual(Array(sequence).map { $0.int }, [1,2])
XCTAssertEqual(Array(sequence).map { $0.fast }, [true, true])
}
}
}
func testFetchSequenceFromSQLWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
let sequence = FastWrappedInt.fetch(db, "SELECT int, -int FROM ints ORDER BY int", adapter: SuffixRowAdapter(fromIndex: 1))
XCTAssertEqual(Array(sequence).map { $0.int }, [-1,-2])
// NICE TO HAVE: make it fast, and the following test pass:
// XCTAssertEqual(Array(sequence).map { $0.fast }, [true, true])
}
}
}
func testFetchAllFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -442,52 +379,6 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase {
}
}
func testFetchSequenceFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
struct Request : FetchRequest {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
return (statement, SuffixRowAdapter(fromIndex: 1))
}
}
let sequence = FastWrappedInt.fetch(db, Request())
XCTAssertEqual(Array(sequence).map { $0.int }, [-1,-2])
// NICE TO HAVE: make it fast, and the following test pass:
// XCTAssertEqual(Array(sequence).map { $0.fast }, [true, true])
}
}
}
func testFetchAllFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (2)")
struct Request : FetchRequest {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
return (statement, SuffixRowAdapter(fromIndex: 1))
}
}
let array = FastWrappedInt.fetchAll(db, Request())
XCTAssertEqual(array.map { $0.int }, [-1,-2])
// NICE TO HAVE: make it fast, and the following test pass:
// XCTAssertEqual(array.map { $0.fast }, [true, true])
}
}
}
func testFetchOneFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -565,48 +456,6 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase {
}
}
func testOptionalFetchSequenceFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
let sequence = Optional<FastWrappedInt>.fetch(statement)
let ints = Array(sequence)
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!.int, 1)
// TODO: uncomment when we have a workaround for rdar://22852669
// XCTAssertEqual(ints[1]!.fast, true)
}
}
}
func testOptionalFetchSequenceFromStatementWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
let sequence = Optional<FastWrappedInt>.fetch(statement, adapter: SuffixRowAdapter(fromIndex: 1))
let ints = Array(sequence)
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!.int, -1)
// TODO: uncomment when we have a workaround for rdar://22852669
// XCTAssertEqual(ints[1]!.fast, true)
}
}
}
func testOptionalFetchAllFromStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -693,46 +542,6 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase {
}
}
func testOptionalFetchSequenceFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let sequence = Optional<FastWrappedInt>.fetch(db, "SELECT int, -int FROM ints ORDER BY int")
let ints = Array(sequence)
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!.int, 1)
// TODO: uncomment when we have a workaround for rdar://22852669
// XCTAssertEqual(ints[1]!.fast, true)
}
}
}
func testOptionalFetchSequenceFromSQLWithAdapter() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let sequence = Optional<FastWrappedInt>.fetch(db, "SELECT int, -int FROM ints ORDER BY int", adapter: SuffixRowAdapter(fromIndex: 1))
let ints = Array(sequence)
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!.int, -1)
// TODO: uncomment when we have a workaround for rdar://22852669
// XCTAssertEqual(ints[1]!.fast, true)
}
}
}
func testOptionalFetchAllFromSQL() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -800,32 +609,6 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase {
}
}
func testOptionalFetchSequenceFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
struct Request : FetchRequest {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement = try db.makeSelectStatement("SELECT int, -int FROM ints ORDER BY int")
return (statement, SuffixRowAdapter(fromIndex: 1))
}
}
let sequence = Optional<FastWrappedInt>.fetch(db, Request())
let ints = Array(sequence)
XCTAssertEqual(ints.count, 2)
XCTAssertTrue(ints[0] == nil)
XCTAssertEqual(ints[1]!.int, -1)
// TODO: uncomment when we have a workaround for rdar://22852669
// XCTAssertEqual(ints[1]!.fast, true)
}
}
}
func testOptionalFetchAllFromFetchRequest() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
File diff suppressed because it is too large. Load diff
@@ -1,212 +0,0 @@
import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct CustomFetchRequest : FetchRequest {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try (db.makeSelectStatement("SELECT 1 AS 'produced'"), ColumnMapping(["consumed": "produced"]))
}
}
private struct CustomRecord: RowConvertible {
let consumed: Int
init(row: Row) {
consumed = row.value(named: "consumed")
}
}
private struct CustomStruct: DatabaseValueConvertible {
// CustomStruct that *only* conforms to DatabaseValueConvertible, *NOT* StatementColumnConvertible
fileprivate let number: Int64
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue {
return number.databaseValue
}
/// Returns a String initialized from *databaseValue*, if possible.
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> CustomStruct? {
guard let number = Int64.fromDatabaseValue(databaseValue) else {
return nil
}
return CustomStruct(number: number)
}
}
extension CustomStruct: Equatable {
static func ==(lhs: CustomStruct, rhs: CustomStruct) -> Bool {
return lhs.number == rhs.number
}
}
class FetchRequestTests: GRDBTestCase {
func testDatabaseValueConvertibleFetch() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
var fetchedValue: CustomStruct? = nil
for i in CustomStruct.fetch(db, CustomFetchRequest()) {
fetchedValue = i
}
XCTAssertEqual(fetchedValue!, CustomStruct(number: 1))
}
}
}
func testDatabaseValueConvertibleFetchAll() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let fetchedValues = CustomStruct.fetchAll(db, CustomFetchRequest())
XCTAssertEqual(fetchedValues, [CustomStruct(number: 1)])
}
}
}
func testDatabaseValueConvertibleFetchOne() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let fetchedValue = CustomStruct.fetchOne(db, CustomFetchRequest())!
XCTAssertEqual(fetchedValue, CustomStruct(number: 1))
}
}
}
func testDatabaseValueConvertibleOptionalFetch() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
var fetchedValue: CustomStruct? = nil
for i in Optional<CustomStruct>.fetch(db, CustomFetchRequest()) {
fetchedValue = i
}
XCTAssertEqual(fetchedValue!, CustomStruct(number: 1))
}
}
}
func testDatabaseValueConvertibleOptionalFetchAll() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let fetchedValues = Optional<CustomStruct>.fetchAll(db, CustomFetchRequest())
let expectedValue: CustomStruct? = CustomStruct(number: 1)
XCTAssertEqual(fetchedValues.count, 1)
XCTAssertEqual(fetchedValues[0], expectedValue)
}
}
}
func testDatabaseValueConvertibleFetchWhereStatementColumnConvertible() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
var fetchedInt: Int? = nil
for i in Int.fetch(db, CustomFetchRequest()) {
fetchedInt = i
}
XCTAssertEqual(fetchedInt!, 1)
}
}
}
func testDatabaseValueConvertibleFetchAllWhereStatementColumnConvertible() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let fetchedInts = Int.fetchAll(db, CustomFetchRequest())
XCTAssertEqual(fetchedInts, [1])
}
}
}
func testDatabaseValueConvertibleFetchOneWhereStatementColumnConvertible() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let fetchedInt = Int.fetchOne(db, CustomFetchRequest())!
XCTAssertEqual(fetchedInt, 1)
}
}
}
func testRowFetch() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
var fetched = false
for row in Row.fetch(db, CustomFetchRequest()) {
fetched = true
XCTAssertEqual(Array(row.columnNames), ["consumed"])
XCTAssertEqual(Array(row.databaseValues), [1.databaseValue])
}
XCTAssertTrue(fetched)
}
}
}
func testRowFetchAll() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let rows = Row.fetchAll(db, CustomFetchRequest())
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(Array(rows[0].columnNames), ["consumed"])
XCTAssertEqual(Array(rows[0].databaseValues), [1.databaseValue])
}
}
}
func testRowFetchOne() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let row = Row.fetchOne(db, CustomFetchRequest())!
XCTAssertEqual(Array(row.columnNames), ["consumed"])
XCTAssertEqual(Array(row.databaseValues), [1.databaseValue])
}
}
}
func testRowConvertibleFetch() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
var fetched = false
for record in CustomRecord.fetch(db, CustomFetchRequest()) {
fetched = true
XCTAssertEqual(record.consumed, 1)
}
XCTAssertTrue(fetched)
}
}
}
func testRowConvertibleFetchAll() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let records = CustomRecord.fetchAll(db, CustomFetchRequest())
XCTAssertEqual(records.count, 1)
XCTAssertEqual(records[0].consumed, 1)
}
}
}
func testRowConvertibleFetchOne() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let record = CustomRecord.fetchOne(db, CustomFetchRequest())!
XCTAssertEqual(record.consumed, 1)
}
}
}
}
@@ -73,7 +73,8 @@ class QueryInterfaceRequestTests: GRDBTestCase {
do {
var names: [String] = []
for row in Row.fetch(db, tableRequest) {
let rows = try Row.fetchCursor(db, tableRequest)
while let row = try rows.next() {
names.append(row.value(named: "name"))
}
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"")
@@ -89,12 +89,6 @@ class RecordQueryInterfaceRequestTests: GRDBTestCase {
XCTAssertEqual(reader.age, arthur.age)
}
do {
let names = request.fetch(db).map { $0.name }
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(names, [arthur.name, barbara.name])
}
do {
let cursor = try request.fetchCursor(db)
let names = try cursor.map { $0.name }
@@ -98,7 +98,7 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase {
}
do {
let names = request.fetch(db).map { $0.name }
let names = try request.fetchCursor(db).map { $0.name }
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(names, [arthur.name, barbara.name])
}
@@ -135,12 +135,6 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase {
XCTAssertEqual(reader.age, arthur.age)
}
do {
let names = Reader.fetch(db).map { $0.name }
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(names, [arthur.name, barbara.name])
}
do {
let cursor = try Reader.fetchCursor(db)
let names = try cursor.map { $0.name }
@@ -183,7 +177,7 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase {
}
do {
let names = AltReader.fetch(db, request).map { $0.name }
let names = try AltReader.fetchCursor(db, request).map { $0.name }
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(names, [arthur.name, barbara.name])
}
@@ -352,35 +352,6 @@ class MinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
func testFetchSequenceWithKeys() {
assertNoError {
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 = Array(MinimalRowID.fetch(db, keys: []))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = Array(MinimalRowID.fetch(db, keys: [["id": record1.id], ["id": record2.id]]))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
}
do {
let fetchedRecords = Array(MinimalRowID.fetch(db, keys: [["id": record1.id], ["id": nil]]))
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
}
}
}
}
func testFetchAllWithKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -453,31 +424,6 @@ class MinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
func testFetchSequenceWithPrimaryKeys() {
assertNoError {
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 = Array(MinimalRowID.fetch(db, keys: ids))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [record1.id!, record2.id!]
let fetchedRecords = Array(MinimalRowID.fetch(db, keys: ids))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
}
}
}
}
func testFetchAllWithPrimaryKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -348,37 +348,6 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
func testFetchSequenceWithKeys() {
assertNoError {
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 = Array(MinimalSingle.fetch(db, keys: []))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = Array(MinimalSingle.fetch(db, keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = Array(MinimalSingle.fetch(db, keys: [["UUID": record1.UUID], ["UUID": nil]]))
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
}
func testFetchAllWithKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -456,33 +425,6 @@ class MinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
func testFetchSequenceWithPrimaryKeys() {
assertNoError {
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 = Array(MinimalSingle.fetch(db, keys: UUIDs))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = Array(MinimalSingle.fetch(db, keys: UUIDs))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
}
func testFetchAllWithPrimaryKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -445,35 +445,6 @@ class PrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
func testFetchSequenceWithKeys() {
assertNoError {
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 = Array(Person.fetch(db, keys: []))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = Array(Person.fetch(db, keys: [["rowid": record1.id], ["rowid": record2.id]]))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
}
do {
let fetchedRecords = Array(Person.fetch(db, keys: [["rowid": record1.id], ["rowid": nil]]))
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
}
}
}
}
func testFetchAllWithKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -549,31 +520,6 @@ class PrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
func testFetchSequenceWithPrimaryKeys() {
assertNoError {
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 = Array(Person.fetch(db, keys: ids))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [record1.id!, record2.id!]
let fetchedRecords = Array(Person.fetch(db, keys: ids))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
}
}
}
}
func testFetchAllWithPrimaryKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -681,7 +627,8 @@ class PrimaryKeyHiddenRowIDTests : GRDBTestCase {
try record.insert(db)
}
for record in Person.fetch(db) {
let records = try Person.fetchCursor(db)
while let record = try records.next() {
XCTAssert(record.id != nil)
}
@@ -377,35 +377,6 @@ class PrimaryKeyMultipleTests: GRDBTestCase {
}
}
func testFetchSequenceWithKeys() {
assertNoError {
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 = Array(Citizenship.fetch(db, keys: []))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = Array(Citizenship.fetch(db, keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": record2.personName, "countryName": record2.countryName]]))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.personName }), Set([record1.personName, record2.personName]))
}
do {
let fetchedRecords = Array(Citizenship.fetch(db, keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": nil, "countryName": nil]]))
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.personName, record1.personName!)
}
}
}
}
func testFetchAllWithKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -140,33 +140,6 @@ class PrimaryKeyNoneTests: GRDBTestCase {
}
}
func testFetchSequenceWithPrimaryKeys() {
assertNoError {
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 = Array(Item.fetch(db, keys: ids))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [id1, id2]
let fetchedRecords = Array(Item.fetch(db, keys: ids))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.name! }), Set([record1, record2].map { $0.name! }))
}
}
}
}
func testFetchAllWithPrimaryKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -442,35 +442,6 @@ class PrimaryKeyRowIDTests: GRDBTestCase {
}
}
func testFetchSequenceWithKeys() {
assertNoError {
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 = Array(Person.fetch(db, keys: []))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = Array(Person.fetch(db, keys: [["id": record1.id], ["id": record2.id]]))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
}
do {
let fetchedRecords = Array(Person.fetch(db, keys: [["id": record1.id], ["id": nil]]))
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
}
}
}
}
func testFetchAllWithKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -546,31 +517,6 @@ class PrimaryKeyRowIDTests: GRDBTestCase {
}
}
func testFetchSequenceWithPrimaryKeys() {
assertNoError {
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 = Array(Person.fetch(db, keys: ids))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [record1.id!, record2.id!]
let fetchedRecords = Array(Person.fetch(db, keys: ids))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
}
}
}
}
func testFetchAllWithPrimaryKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -368,35 +368,6 @@ class PrimaryKeySingleTests: GRDBTestCase {
}
}
func testFetchSequenceWithKeys() {
assertNoError {
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 = Array(Pet.fetch(db, keys: []))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = Array(Pet.fetch(db, keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = Array(Pet.fetch(db, keys: [["UUID": record1.UUID], ["UUID": nil]]))
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
}
func testFetchAllWithKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -470,31 +441,6 @@ class PrimaryKeySingleTests: GRDBTestCase {
}
}
func testFetchSequenceWithPrimaryKeys() {
assertNoError {
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 = Array(Pet.fetch(db, keys: UUIDs))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = Array(Pet.fetch(db, keys: UUIDs))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
}
func testFetchAllWithPrimaryKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -359,37 +359,6 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
func testFetchSequenceWithKeys() {
assertNoError {
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 = Array(Email.fetch(db, keys: []))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = Array(Email.fetch(db, keys: [["email": record1.email], ["email": record2.email]]))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set([record1.email, record2.email]))
}
do {
let fetchedRecords = Array(Email.fetch(db, keys: [["email": record1.email], ["email": nil]]))
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.email, record1.email!)
}
}
}
}
func testFetchAllWithKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
@@ -467,33 +436,6 @@ class PrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
func testFetchSequenceWithPrimaryKeys() {
assertNoError {
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 = Array(Email.fetch(db, keys: emails))
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let emails = [record1.email!, record2.email!]
let fetchedRecords = Array(Email.fetch(db, keys: emails))
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set(emails))
}
}
}
}
func testFetchAllWithPrimaryKeys() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
-127
View File
@@ -1,127 +0,0 @@
import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private class Person : Record {
var id: Int64!
var name: String!
var age: Int?
init(id: Int64? = nil, name: String? = nil, age: Int? = nil) {
self.id = id
self.name = name
self.age = age
super.init()
}
static func setup(inDatabase db: Database) throws {
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
// Record
override class var databaseTableName: String {
return "persons"
}
required init(row: Row) {
id = row.value(named: "id")
age = row.value(named: "age")
name = row.value(named: "name")
super.init(row: row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return [
"id": id,
"name": name,
"age": age,
]
}
override func didInsert(with rowID: Int64, for column: String?) {
self.id = rowID
}
}
class RecordFetchTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPerson", migrate: Person.setup)
try migrator.migrate(dbWriter)
}
func testSelectStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inTransaction { db in
try Person(name: "Arthur", age: 41).insert(db)
try Person(name: "Barbara", age: 37).insert(db)
return .commit
}
try dbQueue.inDatabase { db in
let statement = try db.makeSelectStatement("SELECT * FROM persons WHERE name = ?")
for name in ["Arthur", "Barbara"] {
let person = Person.fetchOne(statement, arguments: [name])!
XCTAssertEqual(person.name!, name)
}
}
}
}
func testDatabaseRecordSequenceCanBeIteratedTwice() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inTransaction { db in
try Person(name: "Arthur", age: 41).insert(db)
try Person(name: "Barbara", age: 37).insert(db)
let personSequence = Person.fetch(db, "SELECT * FROM persons ORDER BY name")
var names1: [String?] = personSequence.map { $0.name }
var names2: [String?] = personSequence.map { $0.name }
XCTAssertEqual(names1[0]!, "Arthur")
XCTAssertEqual(names1[1]!, "Barbara")
XCTAssertEqual(names2[0]!, "Arthur")
XCTAssertEqual(names2[1]!, "Barbara")
return .commit
}
}
}
func testSelectStatementRecordSequenceCanBeIteratedTwice() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inTransaction { db in
try Person(name: "Arthur", age: 41).insert(db)
try Person(name: "Barbara", age: 37).insert(db)
let statement = try db.makeSelectStatement("SELECT * FROM persons ORDER BY name")
let personSequence = Person.fetch(statement)
var names1: [String?] = personSequence.map { $0.name }
var names2: [String?] = personSequence.map { $0.name }
XCTAssertEqual(names1[0]!, "Arthur")
XCTAssertEqual(names1[1]!, "Barbara")
XCTAssertEqual(names2[0]!, "Arthur")
XCTAssertEqual(names2[1]!, "Barbara")
return .commit
}
}
}
}