Compare commits

...
217 Commits
Author SHA1 Message Date
Gwendal Roué baeba0dea3 v2.9.0 2018-02-25 07:40:14 +01:00
Gwendal Roué 3dc31ad638 Typo 2018-02-25 00:00:25 +01:00
Gwendal Roué 4201e2a611 README 2018-02-24 21:24:18 +01:00
Gwendal Roué d9f6fa7de6 CHANGELOG 2018-02-24 21:12:53 +01:00
Gwendal Roué d0146762bc Differences between Database Queues and Pools 2018-02-24 21:06:07 +01:00
Gwendal Roué 7e8f2e2fbc Differences between Database Queues and Pools 2018-02-24 21:05:23 +01:00
Gwendal Roué 497f4b65ef Differences between Database Queues and Pools 2018-02-24 21:03:08 +01:00
Gwendal Roué 03c44778ba Differences between Database Queues and Pools 2018-02-24 20:57:27 +01:00
Gwendal Roué 0cc744ae16 Differences between Database Queues and Pools 2018-02-24 20:54:12 +01:00
Gwendal Roué fae3862547 Typo 2018-02-24 20:08:07 +01:00
Gwendal Roué 70a222f3c9 Typo 2018-02-24 20:07:21 +01:00
Gwendal Roué 5676adca99 TODO: Decode NSDecimalNumber from text database values
(Idea from @robertmryan at https://github.com/ccgus/fmdb/pull/647#issuecomment-368083101)
2018-02-24 18:18:41 +01:00
Gwendal Roué 3a77ca68c4 TODO 2018-02-24 17:58:02 +01:00
Gwendal Roué 248437d1d6 DatabaseSnapshot documentation 2018-02-24 17:55:34 +01:00
Gwendal Roué afcde4609e CHANGELOG 2018-02-24 17:49:39 +01:00
Gwendal Roué 2e98974373 Cursor doc 2018-02-24 17:46:01 +01:00
Gwendal Roué 086a33fd62 Cursor doc 2018-02-24 17:44:33 +01:00
Gwendal Roué 33359dd435 Markdown typo 2018-02-24 17:42:52 +01:00
Gwendal Roué 574d71b50c Cursor level 2018-02-24 17:41:29 +01:00
Gwendal Roué c806b706d4 Focus on Cursor specificities 2018-02-24 17:40:16 +01:00
Gwendal Roué c3b8c0f7e9 Explain why cursors are not sequences (addresses #303) 2018-02-24 17:37:00 +01:00
Gwendal Roué a1cd622892 Focus on Cursor specificities 2018-02-24 17:30:31 +01:00
Gwendal Roué dea3ee0b84 Focus on Cursor specificities 2018-02-24 17:29:29 +01:00
Gwendal Roué 5c64348ea8 Focus on Cursor specificities 2018-02-24 17:25:13 +01:00
Gwendal Roué 262ac2c476 Intra-doc links 2018-02-24 17:17:34 +01:00
Gwendal Roué dbfbe30749 DatabaseSnapshot RAII 2018-02-24 17:15:53 +01:00
Gwendal Roué 70437bd4cb Documentation typos 2018-02-24 17:14:30 +01:00
Gwendal Roué 2d30b5ea1c Documentation typos 2018-02-24 17:13:27 +01:00
Gwendal Roué 5414111bed Update changes tracking documentation, and changelog 2018-02-24 17:06:35 +01:00
Gwendal Roué 9168bac16e Deprecate RecordBox. Introduce changes API on MutablePersistable. Rename Record changes tracking methods. 2018-02-24 16:19:21 +01:00
Gwendal Roué 8760d36f6c Snapshot documentation 2018-02-24 07:59:44 +01:00
Gwendal Roué 141b870bc0 Typo 2018-02-24 07:55:15 +01:00
Gwendal Roué 5e4406e78c Improves documentation (addresses #306) 2018-02-24 07:54:42 +01:00
Gwendal Roué c5426bfcf7 CHANGELOG 2018-02-24 07:44:35 +01:00
Gwendal Roué 76561a567f Introduce DatabaseSnapshot 2018-02-24 07:37:26 +01:00
Gwendal Roué 8288f0c751 Add a real-life test for allowsUnsafeTransactions 2018-02-23 19:11:38 +01:00
Gwendal Roué 7dc008db8b Expose Database.beginTransaction(), commit(), rollback(). New Configuration.allowsUnsafeTransactions flag. New fatal error when a database access block ends with a transaction left opened. 2018-02-23 14:14:05 +01:00
Gwendal Roué 86bb4a27a4 CHANGELOG 2018-02-23 13:23:44 +01:00
Gwendal Roué f2d9f50930 CHANGELOG 2018-02-23 13:10:40 +01:00
Gwendal Roué b9af7e6a25 Update ColumnInfo.primaryKeyIndex documentation 2018-02-23 12:55:27 +01:00
Gwendal Roué 00825748ff Fix ColumnInfo test (it is different with SQLite < 3.7.16) 2018-02-23 12:53:41 +01:00
Gwendal Roué fe0edde4a9 TODO 2018-02-23 12:41:19 +01:00
Gwendal Roué edfea91920 TODO 2018-02-23 09:03:58 +01:00
Gwendal Roué 319e6bcdc8 Typo 2018-02-23 08:55:40 +01:00
Gwendal Roué 274f73e040 Cleanup 2018-02-23 08:55:03 +01:00
Gwendal Roué fab37838b2 Cleanup 2018-02-23 08:49:50 +01:00
Gwendal Roué a5a3610bf6 Cleanup 2018-02-23 08:49:27 +01:00
Gwendal Roué 07e600163c Splitting rows: documentation WIP 2018-02-23 08:35:32 +01:00
Gwendal Roué 14a5dc5489 Cleanup 2018-02-23 08:34:34 +01:00
Gwendal Roué 46c2b94425 Cleanup 2018-02-23 08:32:50 +01:00
Gwendal Roué 9a1dc7f292 Cleanup 2018-02-23 08:32:17 +01:00
Gwendal Roué c68fc37959 Cleanup 2018-02-23 08:17:15 +01:00
Gwendal Roué aa1f555e05 Drop init(leftJoinedRow:), and expose Row subscripts that return records 2018-02-23 08:08:00 +01:00
Gwendal Roué 699e64c610 Splitting rows: documentation WIP 2018-02-22 23:31:58 +01:00
Gwendal Roué e8c1392314 TODO 2018-02-22 23:30:48 +01:00
Gwendal Roué c1ae47d188 Splitting rows: documentation WIP 2018-02-22 23:26:37 +01:00
Gwendal Roué 13a9f1113a Splitting rows: documentation WIP 2018-02-22 23:07:19 +01:00
Gwendal Roué c4ad86863f Splitting rows: documentation WIP 2018-02-22 23:03:39 +01:00
Gwendal Roué 8300a618f8 Splitting rows: documentation WIP 2018-02-22 22:58:56 +01:00
Gwendal Roué 52f0038262 Splitting rows: documentation WIP 2018-02-22 22:58:05 +01:00
Gwendal Roué 31710ce91c Splitting rows: documentation WIP 2018-02-22 22:55:24 +01:00
Gwendal Roué a9c75652e1 Splitting rows: documentation WIP 2018-02-22 22:54:21 +01:00
Gwendal Roué 3e13e5be57 Splitting rows: documentation WIP 2018-02-22 22:48:52 +01:00
Gwendal Roué c27979a210 Splitting rows: documentation WIP 2018-02-22 22:37:42 +01:00
Gwendal Roué 37d7c84bc3 Splitting rows: documentation WIP 2018-02-22 22:30:13 +01:00
Gwendal Roué 62f5c8fc2f Splitting rows: documentation WIP 2018-02-22 22:18:12 +01:00
Gwendal Roué 289c449dff Splitting rows: documentation WIP 2018-02-22 22:13:29 +01:00
Gwendal Roué e7b7b603d2 Splitting rows: documentation WIP 2018-02-22 22:08:23 +01:00
Gwendal Roué e7e342600b Splitting rows: documentation WIP 2018-02-22 21:03:17 +01:00
Gwendal Roué db6e3b8371 Splitting rows: documentation WIP 2018-02-22 20:33:46 +01:00
Gwendal Roué 79ed15c38c Deprecate Database.columnCount(in:) in favor of Database.columns(in:). Update doc and changelog 2018-02-22 14:00:19 +01:00
Gwendal Roué 6f175dcafb Add ColumnInfoTests to GRDBCustom/GRDBCipher tests 2018-02-22 13:52:52 +01:00
Gwendal Roué ca70a10bd4 TODO 2018-02-22 13:37:49 +01:00
Gwendal Roué ae3319e9f9 Make ColumnInfo public (asked by @freak4pc) 2018-02-22 13:20:41 +01:00
Gwendal Roué 5112cb24f5 Expose EmptyRowAdapter, and ScopeAdapter(base:scopes:) 2018-02-22 12:38:03 +01:00
Gwendal Roué c6bbccc02e Have AdaptedRow go straight to SQLite when possible (avoid DatabaseValue initializer) 2018-02-22 12:23:19 +01:00
Gwendal Roué 93ec4d2515 Remove Row.hasNull(named:String) and Row.hasNull(Column) 2018-02-22 12:00:06 +01:00
Gwendal Roué 955dc6094b TODO 2018-02-22 09:24:30 +01:00
Gwendal Roué bd694cbc53 Cleanup 2018-02-22 08:50:35 +01:00
Gwendal Roué c115a035ec Row.hasNull(atIndex:) goes straight to sqlite3_column_type() when possible 2018-02-22 08:39:14 +01:00
Gwendal Roué 288144f347 splittingRowAdapters(columnCounts:), ScopeAdapter(nestedScopes:), RowConvertible?(leftJoinedRow:), TableMapping.numberOfSelectedColumns(_:), support for nested codable records 2018-02-21 23:15:13 +01:00
Gwendal Roué 3bdfdaa40a TableMapping.selectionSQL(_:) 2018-02-21 13:51:37 +01:00
Gwendal Roué 22949813af Row.hasNull(atIndex:), Row.hasNull(named:), Row.hasNull(_:), Row.hasNonNullValue 2018-02-20 14:43:06 +01:00
Gwendal Roué 5c98b01484 Update Record.updateChanges(_:) documentation 2018-02-20 13:20:50 +01:00
Gwendal Roué ea5e1cd0db CHANGELOG 2018-02-20 13:18:38 +01:00
Gwendal Roué b5d9955442 Tests: setup Database.logError only once (and avoid SQLite misuse) 2018-02-20 13:16:11 +01:00
Gwendal Roué feb5cb35b4 Record.updateChanges now returns whether the record had changes 2018-02-20 13:06:58 +01:00
Gwendal Roué 654c7083eb TODO 2018-02-17 17:44:03 +01:00
Gwendal Roué a0457928b3 TODO 2018-02-17 17:40:25 +01:00
Gwendal Roué 4df535a3a9 TODO 2018-02-17 17:32:15 +01:00
Gwendal Roué 0b251ec4e0 TODO 2018-01-31 19:54:37 +01:00
Gwendal Roué 7704a9ac41 v2.8.0 2018-01-29 08:12:29 +01:00
Gwendal Roué 59031893ff Merge pull request #297 from groue/MoreCursor
More sequence-like cursor methods
2018-01-29 07:19:58 +01:00
Gwendal Roué fcfa044320 Parts of Cursor implementation are derived from Swift.org 2018-01-28 18:56:40 +01:00
Gwendal Roué f95658e7ce Remove convenience cursor types from reference documentation
Those types bloat the documentation for no real value: DropFirstCursor, DropWhileCursor, EnumeratedCursor, FilterCursor, FlattenCursor, MapCursor, PrefixCursor, PrefixWhileCursor
2018-01-28 17:13:53 +01:00
Gwendal Roué 2c16fcaa99 Cursor cleanup 2018-01-28 17:13:52 +01:00
Gwendal Roué 4e638016e1 Cursor changelog 2018-01-28 17:13:52 +01:00
Gwendal Roué 5d811c0e68 Documentation for Cursor convenience methods 2018-01-28 17:13:52 +01:00
Gwendal Roué 9f1f51637a Tests for Cursor.joined(separator:String) 2018-01-28 17:13:52 +01:00
Gwendal Roué 7c16ffcdf8 Cursor.joined(separator:String) 2018-01-28 17:13:51 +01:00
Gwendal Roué 7ca582719b Tests for Cursor.reduce(into:_:) 2018-01-28 17:13:51 +01:00
Gwendal Roué e4b83baa53 Cursor.reduce(into:_:) 2018-01-28 17:13:51 +01:00
Gwendal Roué ac6b2933a8 Tests for Cursor.max(by:), max(), min(by:), min() 2018-01-28 17:13:50 +01:00
Gwendal Roué 92758fa51d Cursor.max(by:), max(), min(by:), min() 2018-01-28 17:13:50 +01:00
Gwendal Roué acd06a4f5a Tests for Cursor.dropLast() 2018-01-28 17:13:50 +01:00
Gwendal Roué eec6b17398 Cursor.dropLast() 2018-01-28 17:13:50 +01:00
Gwendal Roué 15fbf02647 Tests for Cursor.dropFirst() 2018-01-28 17:13:49 +01:00
Gwendal Roué c296be5057 Cursor.dropFirst() 2018-01-28 17:13:49 +01:00
Gwendal Roué 129e178ee0 Tests for Cursor.dropFirst(_:) 2018-01-28 17:13:49 +01:00
Gwendal Roué 1e5caa62a8 Tests for Cursor.prefix(while:) 2018-01-28 17:13:49 +01:00
Gwendal Roué 420ed0764b Tests for Cursor.drop(while:) 2018-01-28 17:13:49 +01:00
Gwendal Roué ce6bbb2885 Tests for Cursor.prefix(_:) 2018-01-28 17:13:48 +01:00
Gwendal Roué 87d6c5dd29 Cursor.prefix(_:) 2018-01-28 17:13:48 +01:00
Gwendal Roué dccd456497 Tests for Cursor.dropLast(_:) 2018-01-28 17:13:48 +01:00
Gwendal Roué 520bdd64e6 Tests for Cursor.dropFirst(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué 72608fd016 Cursor.dropLast(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué 69b51ffbd5 Tests for Cursor.dropFirst(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué c9044ea07b Cursor.dropFirst(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué 362c40326f Tests for Cursor.suffix(_:) 2018-01-28 17:13:47 +01:00
Gwendal Roué 28d0793688 Cursor.suffix(_:) 2018-01-28 17:13:46 +01:00
Gwendal Roué abdc2000c4 Tests for Cursor.prefix(while:) 2018-01-28 17:13:46 +01:00
Gwendal Roué 3d845b1e9f Cursor.prefix(while:) 2018-01-28 17:13:46 +01:00
Gwendal Roué bae8c97df4 Tests for Cursor.drop(while:) 2018-01-28 17:13:46 +01:00
Gwendal Roué 452c1d4b92 Cursor.drop(while:) 2018-01-28 17:13:46 +01:00
Gwendal Roué 9990e6e2a6 Less TODO 2018-01-28 17:13:16 +01:00
Gwendal Roué 8d0dc3eb78 Merge pull request #293 from groue/SQLite3.22.0
Upgrade SQLite version to 3.22.0
2018-01-27 09:33:54 +01:00
Gwendal Roué 0a2a3c75c1 Fix typo 2018-01-26 08:47:27 +01:00
Gwendal Roué 830e6acb4f Documentation and changelog 2018-01-26 08:44:18 +01:00
Gwendal Roué 1da85dff58 FTS5Pattern(matchingPrefixPhrase:) 2018-01-26 08:38:11 +01:00
Gwendal Roué dd40e3be5b Upgrade custom SQLite version in documentation 2018-01-26 08:00:50 +01:00
Gwendal Roué 224d6488a9 Upgrade swiftlyfalling/SQLiteLib to v3.22.0 2018-01-26 07:54:08 +01:00
Gwendal Roué cac31d3294 TODO: apply @hartbit's suggestion 2018-01-24 18:56:53 +01:00
Gwendal Roué 951d5fa58d TODO SQLite 3.22.0 2018-01-23 08:10:26 +01:00
Gwendal Roué 7a4f0778df Remove references to discarded GRDB Extension Guide 2018-01-21 17:31:45 +01:00
Gwendal Roué 5aff4d29fc CHANGELOG 2018-01-21 17:29:27 +01:00
Gwendal Roué 402b7001ee v2.7.0 2018-01-21 17:07:39 +01:00
Gwendal Roué f7d0979fb1 Remove ExtendingGRDB guide 2018-01-21 17:05:38 +01:00
Gwendal Roué 2289ed9d95 Cleanup Jazzy documentation from most redundant definitions and experimental APIs 2018-01-21 16:57:43 +01:00
Gwendal Roué dfcb44016f Enhance CHANGELOG 2018-01-21 15:19:55 +01:00
Gwendal Roué 37a434a615 Merge pull request #289 from groue/RecordBox
Bring changes tracking to any record type
2018-01-21 13:16:35 +01:00
Gwendal Roué 0ddcf1e401 RecordBox documentation 2018-01-21 13:14:14 +01:00
Gwendal Roué 0aa673f24e RecordBox consequence: more TODO 2018-01-21 12:05:41 +01:00
Gwendal Roué b3a24daa2f Documentation tweaks 2018-01-21 07:49:13 +01:00
Gwendal Roué 8c6954cd75 RecordBox documentation 2018-01-21 07:35:52 +01:00
Gwendal Roué 283f08de07 RecordBox changelog 2018-01-20 20:26:37 +01:00
Gwendal Roué d96543ddeb RecordBox documentation 2018-01-20 20:26:37 +01:00
Gwendal Roué 4b320f3cb5 RecordBox documentation 2018-01-20 20:26:37 +01:00
Gwendal Roué 69a6d3e3f3 RecordBox documentation 2018-01-20 20:26:36 +01:00
Gwendal Roué 93d4587732 RecordBox 2018-01-20 20:26:36 +01:00
Gwendal Roué 7481b9788a Run truncate optimization tests with and without transaction observer
This topic is sooo touchy...
2018-01-20 20:26:10 +01:00
Gwendal Roué acf3e0b397 TODO 2018-01-20 19:54:19 +01:00
Gwendal Roué 88ae0fa059 TODO 2018-01-20 17:59:54 +01:00
Gwendal Roué a1e63d9028 Fix management of current transaction observation broker (and discover a new SQLite oddity) 2018-01-20 16:11:05 +01:00
Gwendal Roué 2a1ad8d31c TODO 2018-01-20 09:09:32 +01:00
Gwendal Roué ba7cd2160f TODO 2018-01-20 06:09:44 +01:00
Gwendal Roué 8e50383371 v2.6.1 2018-01-19 16:24:09 +01:00
Gwendal Roué ffc5352840 Fix transaction observer crash 2018-01-19 16:17:38 +01:00
Gwendal Roué 53e849cbec v2.6.0 2018-01-18 13:05:07 +01:00
Gwendal Roué b71d57d7ec Merge pull request #288 from groue/TransactionObserverInvalidation
Enhance Database Observation
2018-01-18 13:04:41 +01:00
Gwendal Roué 4fe2b2542f Cleanup 2018-01-18 12:54:02 +01:00
Gwendal Roué 8c7895d8ab Have Makefile accept both Xcode9.0 and Xcode9.0.1 2018-01-18 12:47:29 +01:00
Gwendal Roué ad15f4dc59 Fix .travis.yml for Xcode9 2018-01-17 13:51:19 +01:00
Gwendal Roué c4ef161a83 Rename Statement.region and Request.region to fetchedRegion 2018-01-17 06:54:10 +01:00
Gwendal Roué bb48025947 Derived requests ought to preserve database region: fix failing tests 2018-01-16 20:39:19 +01:00
Gwendal Roué 389a7f28c4 Derived requests ought to preserve database region: failing tests 2018-01-16 20:39:13 +01:00
Gwendal Roué 714cc1c734 DatabaseRegion() is public 2018-01-16 19:57:30 +01:00
Gwendal Roué 8d0da7f870 DatabaseRegion documentation 2018-01-16 18:47:59 +01:00
Gwendal Roué e42e74103d DatabaseRegion documentation 2018-01-16 18:46:55 +01:00
Gwendal Roué 4bcdb91895 AnyRequest and all derived requests preserve database region, and counting method 2018-01-16 14:11:05 +01:00
Gwendal Roué 938977bbca Cleanup DatabaseRegion: no more public intersection, no more public way to specify rowids 2018-01-16 13:58:55 +01:00
Gwendal Roué 581c1c46e2 More TODO 2018-01-16 11:28:48 +01:00
Gwendal Roué 768b2ab620 More TODO 2018-01-16 09:30:12 +01:00
Gwendal Roué 4eff5ab357 More TODO 2018-01-16 09:06:53 +01:00
Gwendal Roué 888892b92f Cleanup 2018-01-16 09:04:06 +01:00
Gwendal Roué ba4f146c9c Cleanup 2018-01-16 08:55:48 +01:00
Gwendal Roué 8359dd2ae2 Cleanup 2018-01-16 08:54:12 +01:00
Gwendal Roué 0be80db8f9 Cleanup 2018-01-16 08:51:42 +01:00
Gwendal Roué 72de142519 Cleanup 2018-01-16 08:50:49 +01:00
Gwendal Roué 0a7468f56d Cleanup 2018-01-16 08:34:54 +01:00
Gwendal Roué 33b5c6c616 Rename DatabaseSelectionInfo to DatabaseRegion 2018-01-16 08:23:08 +01:00
Gwendal Roué 4003d7600d DatabaseSelectionInfo documentation WIP 2018-01-15 23:41:49 +01:00
Gwendal Roué a7122ba8bb Unit tests for DatabaseSelectionInfo.isModified methods 2018-01-15 23:09:52 +01:00
Gwendal Roué dc8c85d3db Odd failing tests for DatabaseSelectionInfo and the rowid column. Consequences not cleared out yet. 2018-01-15 22:44:09 +01:00
Gwendal Roué fc1b4a6f35 Complete refactoring of SelectStatement.SelectionInfo into DatabaseSelectionInfo 2018-01-15 22:28:43 +01:00
Gwendal Roué af42623654 Fix SPM tests 2018-01-15 07:22:01 +01:00
Gwendal Roué ab1a672336 Disable test that fails on iOS 8.1 (SQLite 3.7.13) 2018-01-14 23:31:19 +01:00
Gwendal Roué 4501d7dcde TransactionObserver: provide default implementation for rarely used and stabilized databaseWillChange() and databaseWillCommit() methods 2018-01-14 22:58:12 +01:00
Gwendal Roué 5d463d6bff Goal achieved! FetchedRecordsController uses ignoreDatabaseChangesUntilNextTransaction, and checks changed rowIds in order to avoid useless fetch requests 2018-01-14 22:41:27 +01:00
Gwendal Roué 9c8a9fbe32 SelectionInfo.rowIds contains the rowIds fetched by a request 2018-01-14 22:05:18 +01:00
Gwendal Roué 1a89b2eae5 Test that sqlite authorizer uses "ROWID" as the name of the rowid column 2018-01-14 20:15:55 +01:00
Gwendal Roué fd65e72bbb CHANGELOG 2018-01-14 19:41:05 +01:00
Gwendal Roué 33e8d0875d Remove update hook when no observer is active. Allow truncate optimization when deletions are not observed. 2018-01-14 19:34:11 +01:00
Gwendal Roué 19e75576a8 Documentation for TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 17:36:51 +01:00
Gwendal Roué 980860b2e9 Documentation for TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 17:35:17 +01:00
Gwendal Roué eee3e36238 Test TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 17:08:53 +01:00
Gwendal Roué eaadd37e87 TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() is public 2018-01-14 17:08:42 +01:00
Gwendal Roué a1e508b1df TransactionObserver.ignoreDatabaseChangesUntilNextTransaction() 2018-01-14 16:45:36 +01:00
Gwendal Roué 2c8f9dffdd TODO GRDB3 2018-01-12 10:06:26 +01:00
Gwendal Roué 92fd3bf8ae TODO: TransactionObserver.stopObservingUntilNextTransaction() 2018-01-12 09:48:57 +01:00
Gwendal Roué c940675bf3 Fix typo 2018-01-12 09:12:35 +01:00
Gwendal Roué 2a147d5029 Travis: test Xcode 9.2 and Xcode 9.0 2018-01-12 08:19:02 +01:00
Gwendal Roué 0d236ae32c Row adopts RandomAccessCollection 2018-01-12 08:18:50 +01:00
Gwendal Roué cf4654108e More doc for filter(key:) and filter(keys:) 2018-01-12 07:19:26 +01:00
Gwendal Roué 7e9eed9374 v2.5.0 2018-01-11 21:16:54 +01:00
Gwendal Roué 383581938a Cleanup 2018-01-11 20:14:01 +01:00
Gwendal Roué df50da9024 Cleanup 2018-01-11 20:12:02 +01:00
Gwendal Roué d3a65303a1 Cleanup 2018-01-11 20:06:59 +01:00
Gwendal Roué 9a2bf923d2 Update CHANGELOG and README for new key-filtering requests 2018-01-11 20:04:49 +01:00
Gwendal Roué 9b27c0c651 WIP TableMapping.filter(key: [:]) and TableMapping.filter(keys: [[:], ]) 2018-01-11 19:34:28 +01:00
Gwendal Roué 2af85e7347 WIP TableMapping.filter(key:1) and TableMapping.filter(keys: [1, 2, 3]) 2018-01-11 18:09:01 +01:00
Gwendal Roué 071f0f4443 Cleanup 2018-01-10 08:50:45 +01:00
Gwendal Roué 903e8c96aa '^foo' is no longer an invalid FTS5 pattern in upcoming SQLite 3.22.0 2018-01-10 07:40:02 +01:00
Gwendal Roué 79a5fb9c15 Cleanup 2018-01-08 08:44:42 +01:00
Gwendal Roué 46ef4b27bb Fix failing test 2018-01-07 15:29:24 +01:00
Gwendal Roué 1838797d38 CHANGELOG 2018-01-07 14:25:36 +01:00
Gwendal Roué c7d500b8ba Optimize database event notifications for simple statements without side effect 2018-01-07 14:25:29 +01:00
Gwendal Roué 95a09cb644 Only notify observed events to transaction observers 2018-01-07 13:33:35 +01:00
107 changed files with 9091 additions and 2000 deletions

No files matched your search

+104 -46
View File
@@ -15,140 +15,198 @@ jobs:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 9.1)
# Test GRDBOSX (Xcode 9.2)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBOSX (Xcode 9.1, macOS)
- TID=GRDBOSX (Xcode 9.2, macOS)
script: make test_framework_GRDBOSX
# Test GRDBWatchOS (Xcode 9.1)
# Test GRDBWatchOS (Xcode 9.2)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBWatchOS (Xcode 9.1, watchOS)
- TID=GRDBWatchOS (Xcode 9.2, watchOS)
script: make test_framework_GRDBWatchOS
# Test GRDBiOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
# Test GRDBiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBiOS (Xcode 9.1, iOS <MAX>)
- TID=GRDBiOS (Xcode 9.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
# Test GRDBiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
# Test GRDBiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBiOS (Xcode 9.1, iOS <MIN>)
- TID=GRDBiOS (Xcode 9.2, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 9.1, macOS)
# Test GRDB [SPM] (Xcode 9.2, macOS)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDB [SPM] (Xcode 9.1, macOS)
- TID=GRDB [SPM] (Xcode 9.2, macOS)
script: make test_SPM
# Test GRDBOSX (Xcode 9.0)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBOSX (Xcode 9.0, macOS)
script: make test_framework_GRDBOSX
# Test GRDBiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBiOS (Xcode 9.0, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
###########################################
## Test GRDB (Custom SQLite)
# Test GRDBCustomSQLiteOSX (Xcode 9.1)
# Test GRDBCustomSQLiteOSX (Xcode 9.2)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCustomSQLiteOSX (Xcode 9.1, macOS)
- TID=GRDBCustomSQLiteOSX (Xcode 9.2, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAX>)
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MIN>)
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
# Test GRDBCustomSQLiteOSX (Xcode 9.0)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteOSX (Xcode 9.0, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
###########################################
## Test GRDB (SQLCipher)
# Test GRDBCipherOSX (Xcode 9.1)
# Test GRDBCipherOSX (Xcode 9.2)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCipherOSX (Xcode 9.1, macOS)
- TID=GRDBCipherOSX (Xcode 9.2, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
# Test GRDBCipheriOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MAX>)
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9.1, iOS <MINIMUM VERSION>))
# Test GRDBCipheriOS (Xcode 9.2, iOS <MINIMUM VERSION>))
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MIN>)
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MIN>)
script: make test_framework_GRDBCipheriOS_minTarget
# Test GRDBCipherOSX (Xcode 9.0)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCipherOSX (Xcode 9.0, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCipheriOS (Xcode 9.0, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
###########################################
## Test Installation Methods
# Manual Install
# Manual Install (Xcode 9.2)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=Manual Install
- TID=Manual Install (Xcode 9.2)
script: make test_install_manual
# Manual Install (GRDBCipher)
# Manual Install (GRDBCipher, Xcode 9.2)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.1
osx_image: xcode9.2
env:
- TID=Manual Install (GRDBCipher)
- TID=Manual Install (GRDBCipher, Xcode 9.2)
script: make test_install_GRDBCipher
# Cocoapods Lint
# Cocoapods Lint (Xcode 9.2)
- stage: Test Installation
osx_image: xcode9.1
osx_image: xcode9.2
install:
- gem install cocoapods # Since Travis is not always on latest version
env:
- TID=Cocoapods
- TID=Cocoapods (Xcode 9.2)
script: make test_CocoaPodsLint
# SPM Install
# Cocoapods Lint (Xcode 9.0)
- stage: Test Installation
osx_image: xcode9.1
osx_image: xcode9
install:
- gem install cocoapods # Since Travis is not always on latest version
env:
- TID=SPM
- TID=Cocoapods (Xcode 9.0)
script: make test_CocoaPodsLint
# SPM Install (Xcode 9.2)
- stage: Test Installation
osx_image: xcode9.2
env:
- TID=SPM (Xcode 9.2)
script: make test_install_SPM
## Carthage Build
## Commented out until `make test_CarthageBuild` performs *reliably*.
## See https://github.com/groue/GRDB.swift/pull/262
# - stage: Test Installation
# osx_image: xcode9.1
# osx_image: xcode9.2
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
+313 -2
View File
@@ -1,6 +1,317 @@
Release Notes
=============
## 2.9.0
Released February 25, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.8.0...v2.9.0)
### New
- **Changes tracking overhaul**: changes tracking, a feature previously restricted to the `Record` class and its subclasses, is now available for all records. And it has a better looking API ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking)).
- **Database snapshots**: Database pools can now take database snapshots. A snapshot sees an unchanging database content, as it existed at the moment the snapshot was created ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#database-snapshots)).
- **Improved support for joined queries**: more than a set on new APIs, we provide a set of guidelines that will help you deal with your wildest joined queries. Check the new [Joined Queries Support](https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support) documentation chapter.
- `Database.columns(in:)` returns information about the columns of a table.
- `Request.adapted(_:)` is no longer experimental.
- `Configuration.allowsUnsafeTransactions` lets you leave transactions opened between two database accesses (see below).
- Support for explicit transaction management, via the new `Database.beginTransaction`, `commit`, and `rollback` methods.
### Fixed
- It is now a programmer error to leave a transaction opened at the end of a database access block:
```swift
// Fatal error: A transaction has been left opened at the end of a database access
try dbQueue.inDatabase { db in
try db.beginTransaction()
}
```
One can still opt-in for the unsafe behavior by setting the new `allowsUnsafeTransactions` configuration flag:
```swift
var config = Configuration()
config.allowsUnsafeTransactions = true
let dbQueue = DatabaseQueue(configuration: config)
// OK
try dbQueue.inDatabase { db in
try db.beginTransaction()
}
```
### Deprecated
- `Database.columnCount(in:)` is deprecated. Use `db.columns(in:).count` instead.
- `RecordBox`, introduced in [2.7.0](#270), was ill-advised. It has been deprecated. Use [changes tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking) methods on the Persistable protocol instead.
- `Record.hasPersistentChangedValues` has been deprecated, renamed `hasDatabaseChanges`.
- `Record.persistentChangedValues` has been deprecated, renamed `databaseChanges`.
### Documentation Diff
- The [Changes Tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking) chapter has been updated for the new universal support for record changes.
- A new [Database Snapshots](https://github.com/groue/GRDB.swift/blob/master/README.md#database-snapshots) chapter has been added.
- The [Concurrency](https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency) chapter has been updated for database snapshots.
- A new [Differences between Database Queues and Pools](https://github.com/groue/GRDB.swift/blob/master/README.md#differences-between-database-queues-and-pools) chapter has been added, that attempts at visually show how much database pools are different from database queues.
- A new [Joined Queries Support](https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support) chapter has been added.
- The [Row Adapters](https://github.com/groue/GRDB.swift/blob/master/README.md#row-adapters) chapter has been made consistent with the new chapter on joined queries.
- The [Codable Records](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) chapter has been made consistent with the new chapter on joined queries.
- The [Database Schema Introspection](https://github.com/groue/GRDB.swift/blob/master/README.md#database-schema-introspection) has been updated for `Database.columns(in:)`
### API diff
```diff
+struct ColumnInfo {
+ let name: String
+ let type: String
+ let isNotNull: Bool
+ let defaultValueSQL: String?
+ let primaryKeyIndex: Int
+}
struct Configuration {
+ var allowsUnsafeTransactions: Bool
}
class Database {
+ @available(*, deprecated, message: "Use db.columns(in: tableName).count instead")
func columnCount(in tableName: String) throws -> Int
+ func columns(in tableName: String) throws -> [ColumnInfo]
+ func beginTransaction(_ kind: TransactionKind? = nil) throws
+ func rollback() throws
+ func commit() throws
}
class DatabasePool {
+ func makeSnapshot() throws -> DatabaseSnapshot
}
+class DatabaseSnapshot: DatabaseReader { }
extension MutablePersistable {
+ @discardableResult
+ func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool
+ func databaseEqual(_ record: Self) -> Bool
+ func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue]
}
class Record {
- final func updateChanges(_ db: Database) throws
+ @discardableResult
+ final func updateChanges(_ db: Database) throws -> Bool
}
+@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
class RecordBox: Record { }
class Row {
+ var unscoped: Row
+ var containsNonNullValue: Bool
+ func hasNull(atIndex index: Int) -> Bool
+ subscript<Record: RowConvertible>(_ scope: String) -> Record
+ subscript<Record: RowConvertible>(_ scope: String) -> Record?
}
extension TableMapping {
+ static func selectionSQL(alias: String? = nil) -> String
+ static func numberOfSelectedColumns(_ db: Database) throws -> Int
}
+struct EmptyRowAdapter: RowAdapter { }
struct ScopeAdapter {
+ init(base: RowAdapter, scopes: [String: RowAdapter])
}
+func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter]
```
## 2.8.0
Released January 29, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.7.0...v2.8.0)
**New**
- Upgrade custom SQLite builds to [v3.22.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- The FTS5 full-text search engine has been enhanced with [initial token queries](https://sqlite.org/fts5.html#carrotq), and FTS5Pattern has gained a new initializer: `FTS5Pattern(matchingPrefixPhrase:)`
- The `Cursor` protocol is extended with more methods inspired by the standard Sequence protocol: `drop(while:)`, `dropFirst()`, `dropFirst(_:)`, `dropLast()`, `dropLast(_:)`, `joined(separator:)`, `prefix(_:)`, `max()`, `max(by:)`, `min()`, `min(by:)`, `prefix(while:)`, `reduce(into:_:)`, `suffix(_:)`,
## 2.7.0
Released January 21, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.6.1...v2.7.0)
**New**
- The new RecordBox class brings changes tracking to any record type ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#recordbox-class)):
```swift
// A regular record struct
struct Player: RowConvertible, MutablePersistable { ... }
try dbQueue.inDatabase { db in
// Fetch a boxed player
if let boxedPlayer = try RecordBox<Player>.fetchOne(db, key: 1) {
// boxedPlayer.value is Player
boxedPlayer.value.score = 300
if boxedPlayer.hasPersistentChangedValues {
print("player has been modified")
}
// Does nothing if player has not been modified:
try boxedPlayer.updateChanges(db)
}
}
```
## 2.6.1
Released January 19, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.6.0...v2.6.1)
**Fixed**
- Fixed a crash that could happen when a transaction observer uses the `stopObservingDatabaseChangesUntilNextTransaction()` method.
## 2.6.0
Released January 18, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.5.0...v2.6.0)
### New
- Database observation has been enhanced:
- `TransactionObserver.stopObservingDatabaseChangesUntilNextTransaction()` allows transaction observers to stop observing the database for the remaining extent of a transaction.
- GRDB no longer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt) when no transaction observers are interested in deleted rows.
- FetchedRecordsController now avoids checking for changes in untracked rowIds.
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](http://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
- `TransactionObserver` protocol provides default implementations for rarely used callbacks.
- `Row` adopts RandomAccessCollection
### API diff
```diff
extension TransactionObserver {
+ func stopObservingDatabaseChangesUntilNextTransaction()
+
+ // Default implementation
+ func databaseWillCommit() throws
+
+ #if SQLITE_ENABLE_PREUPDATE_HOOK
+ // Default implementation
+ func databaseWillChange(with event: DatabasePreUpdateEvent)
+ #endif
}
+struct DatabaseRegion: Equatable {
+ var isEmpty: Bool
+
+ init()
+
+ func union(_ other: DatabaseRegion) -> DatabaseRegion
+ mutating func formUnion(_ other: DatabaseRegion)
+
+ func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool
+ func isModified(by event: DatabaseEvent) -> Bool
+}
class SelectStatement {
+ var fetchedRegion: DatabaseRegion
+
+ @available(*, deprecated, renamed:"DatabaseRegion")
+ typealias SelectionInfo = DatabaseRegion
+
+ @available(*, deprecated, renamed:"fetchedRegion")
+ var selectionInfo: DatabaseRegion
}
enum DatabaseEventKind {
- func impacts(_ selectionInfo: SelectStatement.SelectionInfo) -> Bool
+ @available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
+ func impacts(_ region: DatabaseRegion) -> Bool
}
protocol Request {
+ // Default implementation
+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion
}
+extension Row: RandomAccessCollection {
+}
+extension RowIndex: Strideable {
}
```
## 2.5.0
Released January 11, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.4.2...v2.5.0)
### Fixed
- [Transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) used to be notified of some database changes they were not interested into, in case of complex statements with side effects (foreign key cascades or sql triggers). This has been fixed.
### New
- The query interface has learned to build requests from any key (primary keys and unique keys) ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#fetching-by-key)):
```swift
// SELECT * FROM players WHERE id = 1
let request = Player.filter(key: 1)
let player = try request.fetchOne(db) // Player?
// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
let request = Country.filter(keys: ["FR", "US"])
let countries = try request.fetchAll(db) // [Country]
// SELECT * FROM players WHERE email = 'arthur@example.com'
let request = Player.filter(key: ["email": "arthur@example.com"])
let player = try request.fetchOne(db) // Player?
```
This feature has been introduced in order to ease the use of [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
```swift
// New
Player.filter(key: 1).rx
.fetchOne(in: dbQueue)
.subscribe(onNext: { player: Player? in
print("Player 1 has changed")
})
```
### API diff
```diff
extension TableMapping {
+ static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self>
+ static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible
+ static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self>
+ static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self>
}
extension QueryInterfaceRequest where T: TableMapping {
+ func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T>
+ func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible
+ func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T>
+ func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T>
}
extension RowConvertible where Self: TableMapping {
- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self?
+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self?
}
```
## 2.4.2
Released January 6, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v2.4.1...v2.4.2)
@@ -125,14 +436,14 @@ Released October 24, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/comp
### API diff
```diff
extension Request {
extension Request {
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
}
struct SQLRequest {
+ let sql: String
+ let arguments: StatementArguments?
+ let adapter: RowAdapter?
}
}
```
+2 -2
View File
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.21.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.22.0](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v2.4.2
git checkout v2.9.0
git submodule update --init SQLiteCustom/src
````
-591
View File
@@ -1,591 +0,0 @@
GRDB Extension Guide
====================
**Some parts of GRDB are extensible, so that you can make it better fit your needs.**
This guide is a step-by-step tour of GRDB extensibility, around a few topics:
- **[Add a value type](#add-a-value-type)**
You'll learn how to turn UIColor into a value type that you can store, fetch, and use in your records:
```swift
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
while let row = try rows.next() {
let name: String = row["name"]
let color: UIColor = row["color"] // <-- New! UIColor as value
}
```
- **[Add an SQLite function or operator](#add-an-sqlite-function-or-operator)**
You'll learn how to add support for the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator:
```swift
Books.select(strftime("%Y", Column("publishedDate"))) // <-- New! strftime function
Books.filter(Column("body").glob("*Moby-Dick*")) // <-- New! glob method
```
- **[Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression)**
You'll learn how to add support for [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr):
```swift
let jsonString = Column("jsonString")
let request = Books.select(cast(jsonString, as: .blob)) // <-- New! cast function
let rows = try Row.fetchCursor(db, request)
while let row = try rows.next() {
let data = row.dataNoCopy(atIndex: 0)
}
```
- **Extend the query interface requests**
You may need to extend the [query interface requests](../../../#requests) so that their SELECT queries could embed recursive clauses, table joins, etc.
Pull requests are welcome. Open issues if you have questions.
Meanwhile, you can build your own [custom requests](../../../#custom-requests).
- **[Add a custom FTS5 full-text tokenizer](FTS5Tokenizers.md)**
Custom tokenizers can leverage extra full-text features such as synonyms or stop words.
- **Support a new kind of SQL query**
For example, you may need to generate SQL triggers, or create specific kinds of virtual tables.
Pull requests are welcome. Open issues if you have questions.
## Add a Value Type
**All value types adopt the [DatabaseValueConvertible protocol](../../../#custom-value-types).**
```swift
protocol DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from databaseValue, if possible.
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self?
}
```
The `databaseValue` property returns [DatabaseValue](../../../#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail.
The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
**What does the DatabaseValueConvertible protocol bring to a type like UIColor?**
Well, you will be able to use UIColor like all other [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
- Use UIColor as [statement arguments](../../../#executing-updates):
```swift
try db.execute(
"INSERT INTO clothes (name, color) VALUES (?, ?)",
arguments: ["Shirt", UIColor.red])
```
- UIColor can be [extracted from rows](../../../#column-values):
```swift
let rows = try Row.fetchCursor(db, "SELECT * FROM clothes")
while let row = try rows.next() {
let name: String = row["name"]
let color: UIColor = row["color"]
}
```
- UIColor can be [directly fetched](../../../#value-queries):
```swift
let colors = try UIColor.fetchAll(db, "SELECT DISTINCT color FROM clothes") // [UIColor]
```
- Use UIColor in [Records](../../../#records):
```swift
class ClothingItem : Record {
var name: String
var color: UIColor
required init(row: Row) {
name = row["name"]
color = row["color"]
super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
container["name"] = name
container["color"] = color
}
}
```
- Use UIColor in the [query interface](../../../#the-query-interface):
```swift
let redClothes = try ClothingItem.filter(colorColumn == UIColor.red).fetchAll(db)
```
**Let's have UIColor adopt DatabaseValueConvertible**
In order to preserve as most information as possible, we'll archive UIColor as a data blob using the NSCoding protocol. But YMMV.
```swift
extension UIColor : DatabaseValueConvertible {
/// Encode UIColor as a data blob
var databaseValue: DatabaseValue {
// Use NSKeyedArchiver to build Data
let data = NSKeyedArchiver.archivedData(withRootObject: self)
// Data is already DatabaseValueConvertible
return data.databaseValue
}
/// Returns a UIColor if databaseValue contains suitable data, and
/// nil otherwise.
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
// Only Data blobs can contain a UIColor
guard let data = Data.fromDatabaseValue(databaseValue) else {
return nil
}
// We're looking for an archived object
guard let color = NSKeyedUnarchiver.unarchiveObject(with: data) else {
return nil
}
// The cast function will return nil if the unarchived object doesn't
// have the correct type
return cast(color) // Converts Any to Self?
}
}
```
Use the `cast` utility function when you want *non-final classes* to implement DatabaseValueConvertible. It avoids compiler errors that are not easy to deal with. Note that final classes and value types won't need it.
```swift
// Workaround Swift inconvenience around factories methods of non-final classes
func cast<T, U>(_ value: T) -> U? {
return value as? U
}
```
## Add an SQLite Function or Operator
**When an SQLite [function](https://www.sqlite.org/lang_corefunc.html) or [operator](https://www.sqlite.org/lang_expr.html) is missing from GRDB**, this usually means that there hasn't been a [feature request](http://github.com/groue/GRDB.swift/issues) yet.
But you don't have to wait: you can extend GRDB and the query interface to add support for the missing syntax element (and eventually submit a pull request later).
Let's remind our goal: we'll add the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator.
Their SQL usage is the following:
```sql
-- Publication years of books
SELECT STRFTIME('%Y', publishedOn) FROM books;
-- Books that talk about Moby Dick
SELECT * FROM books WHERE body GLOB '*Moby-Dick*';
```
Translated in the query interface, this gives:
```swift
Books.select(strftime("%Y", Column("publishedDate")))
Books.filter(Column("body").glob("*Moby-Dick*"))
```
`strftime` is a top-level Swift function because this is how GRDB usually imports SQLite functions which do not have matching standard Swift counterpart, like AVG, LEGNTH, SUM. It helps the Swift code looking like SQL when it is relevant.
In the same fashion, we expose the GLOB SQL operator as the `glob` Swift method, just because `value.glob(pattern)` reads like `value GLOB pattern`.
Whenever you import a SQL feature to Swift, you'll have to decide: should you preserve the SQL look and feel, or adopt a well-established swiftism? It's really up to you.
### STRFTIME
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
The [STRFTIME](https://www.sqlite.org/lang_datefunc.html) SQL function accepts many arguments. We'll simplify it to `strftime(format, date)`, so that we can write:
```sql
// Publication years of books
// SELECT STRFTIME('%Y', publishedOn) FROM books
Books.select(strftime("%Y", Column("publishedDate")))
```
The signature of the Swift `strftime` function is:
```swift
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression
```
SQLSpecificExpressible and SQLExpression are types of the [query interface](../../../#the-query-interface) that you do not usually see. We have moved down one floor, closer to the SQL guts of GRDB. We'll see more new types and protocols below.
The return value is SQLExpression. All GRDB functions and operators that build [query interface expressions](../../../#expressions) return values of this type. It represents actual [SQLite expressions](https://www.sqlite.org/lang_expr.html).
SQLExpression is a protocol, so that you can build your own [custom expressions](#add-a-new-kind-of-sqlite-expression). But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, and here we'll use SQLExpressionFunction that is dedicated to function calls:
```swift
struct SQLExpressionFunction : SQLExpression {
/// Creates an SQL function call
///
/// // ABS(-1)
/// SQLExpressionFunction(.abs, arguments: -1)
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
}
```
So here is the code that defines our `strftime` function:
```swift
// Add a SQLFunctionName just like we add NSNotification.Name since
// the release of Swift 3.
extension SQLFunctionName {
/// The `STRFTIME` SQL function
static let strftime = SQLFunctionName("STRFTIME")
}
/// Returns an expression that evaluates the `STRFTIME` SQL function.
///
/// // STRFTIME('%Y', date)
/// strftime("%Y", Column("date"))
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionFunction(.strftime, arguments: format, date)
}
```
The `strftime` function is now complete, ready to be used. We haven't yet described the SQLSpecificExpressible type of the `date` argument:
SQLSpecificExpressible is the protocol for all types that can be turned into a SQL expression, but types like Int, Date, or UIColor that exist outside of GRDB and the query interface. Having `strftime` accept a SQLSpecificExpressible date prevents it from polluting the global space. It is *specific* to GRDB:
```swift
strftime("%Y", Date()) // Compiler error
strftime("%Y", Column("date")) // SQLExpression: STRFTIME('%Y', date)
```
You may want to compare it to another protocol, SQLExpressible, which will be described [below](#add-a-new-kind-of-sqlite-expression), when we add support for CAST SQL expressions.
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `strftime` function, it is the SQLSpecificExpressible protocol.
### GLOB
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
For the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator, we want to define the glob Swift method:
```swift
// Books that talk about Moby Dick
// SELECT * FROM books WHERE body GLOB '*Moby-Dick*'
Books.filter(Column("body").glob("*Moby-Dick*"))
```
This time we can't use the SQLExpressionFunction type, because it can't generate the SQL for a binary operator. Instead, we'll use another [built-in expression](#built-in-expressions), SQLExpressionBinary:
```swift
struct SQLExpressionBinary : SQLExpression {
/// Creates an expression made of two expressions joined with a binary operator.
///
/// // length * width
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
}
```
Now we have to find the signature of our Swift method. The GLOB operator accepts any value on both sides. However, what kind of Swift code should we accept?
```swift
// 1) body GLOB '*Moby-Dick*' -- Yes, of course
Column("body").glob("*Moby-Dick*")
// 2) body GLOB pattern -- Sure, why not?
Column("body").glob(Column("pattern"))
// 3) 'Some Swift String' GLOB pattern - Not sure, but OK
"Some Swift String".glob(Column("pattern"))
// 4) 'Some Swift String' GLOB 'Another Swift String' -- NO
"Some Swift String".glob("Another Swift String")
```
We don't want the form 4, because this is an unacceptable pollution of the Swift global namespace. A good GRDB extension limits its scope to database-related code.
We thus have two overloaded definitions of the `glob` method:
```swift
extension SQLSpecificExpressible {
func glob(_ pattern: SQLExpressible) -> SQLExpression
}
extension SQLExpressible {
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression
}
```
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all expressions, and all [value types](../../../#values) (including String).
SQLSpecificExpressible is a sub protocol of SQLExpressible protocol, restricted to all types that can be turned into a SQL expression, but types like Int, Date, or String that exist outside of GRDB and the query interface.
By extending both, we can define the GLOB operators for any pair that contains at least one type that is specific to GRDB - and leave the global Swift space clean.
The final implementation follows:
```swift
// Add a SQLBinaryOperator just like we add NSNotification.Name since
// the release of Swift 3.
extension SQLBinaryOperator {
/// The `GLOB` binary operator
static let glob = SQLBinaryOperator("GLOB")
}
extension SQLSpecificExpressible {
/// Returns an SQL `GLOB` expression.
///
/// // body GLOB '*Moby-Dick*'
/// Column("body").glob("*Moby-Dick*")
func glob(_ pattern: SQLExpressible) -> SQLExpression {
return SQLExpressionBinary(.glob, self, pattern)
}
}
extension SQLExpressible {
/// Returns an SQL `GLOB` expression.
///
/// // 'Some Swift String' GLOB pattern
/// "Some Swift String".glob(Column("pattern"))
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.glob, self, pattern)
}
}
```
### Built-in Expressions
When you extend GRDB with a new function, method, or operator that generates an [SQL expression](https://www.sqlite.org/lang_expr.html), you have to return a value the adopts the SQLExpression protocol.
We have already seen in our [previous](#strftime) [examples](#glob) two concrete types that generate SQL function calls and binary operators: SQLExpressionFunction and SQLExpressionBinary.
This section of the documentation lists all built-in expressions. Adding a custom SQLExpression type will be documented [below](#add-a-new-kind-of-sqlite-expression).
#### Column and DatabaseValue
The [Column](../../../#the-query-interface) type from the query interface, and [DatabaseValue](../../../#databasevalue), the type that wraps the five values supported by SQLite (NULL, Int64, Double, String and Data) are expressions. They are rather trivial, and it is unlikely that you use them in your GRDB extensions.
#### SQLExpressionLiteral
Use SQLExpressionLiteral when you need to go fast:
```swift
struct SQLExpressionLiteral : SQLExpression {
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral("1 + 2")
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
init(_ sql: String, arguments: StatementArguments? = nil)
}
```
For an example of use, see the [Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression) chapter.
#### SQLExpressionUnary
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionUnary builds an expression by prefixing another expression with an unary operator:
```swift
struct SQLExpressionUnary : SQLExpression {
/// Creates an expression made of an unary operator and
/// an operand expression.
///
/// // NOT favorite
/// SQLExpressionUnary(.not, Column("favorite"))
init(_ op: SQLUnaryOperator, _ value: SQLExpressible)
}
```
You add missing SQLite unary operators by extending SQLUnaryOperator:
```swift
extension SQLUnaryOperator {
/// The `+` unary operator
static let plus = SQLUnaryOperator("+", needsRightSpace: false)
}
```
#### SQLExpressionBinary
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionBinary builds an expression by joining two expressions with a binary operator:
```swift
struct SQLExpressionBinary : SQLExpression {
/// Creates an expression made of two expressions joined with a binary operator.
///
/// // length * width
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
}
```
You add missing SQLite binary operators by extending SQLBinaryOperator:
```swift
extension SQLBinaryOperator {
/// The `GLOB` binary operator
static let glob = SQLBinaryOperator("GLOB")
}
```
#### SQLExpressionFunction
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionFunction builds an SQL function call:
```swift
struct SQLExpressionFunction : SQLExpression {
/// Creates an SQL function call
///
/// // ABS(-1)
/// SQLExpressionFunction(.abs, arguments: -1)
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
}
```
You add missing SQLite function names by extending SQLFunctionName:
```swift
extension SQLFunctionName {
/// The `STRFTIME` SQL function
static let strftime = SQLFunctionName("STRFTIME")
}
```
#### The IN Operator
Build a `value IN (...)` expression from any sequence of [values](../../../#values):
```swift
// SQLExpression: id IN (1, 2, 3)
[1,2,3].contains(Column("id"))
// SQLExpression: id NOT IN (1, 2, 3)
![1,2,3].contains(Column("id"))
```
#### The BETWEEN Operator
Build a `value BETWEEN min AND max` expression from Swift ranges:
```swift
// SQLExpression: id BETWEEN 1 AND 10
1...10.contains(Column("id")
```
#### The COUNT Function
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.4/Functions.html) functions:
```swift
// SQLExpression: COUNT(email)
count(Column("email"))
// SQLExpression: COUNT(DISTINCT email)
count(distinct: Column("email"))
```
#### The COLLATE Operator
Build a `expression COLLATE collation` expression with the `collating` method:
```swift
// SQLExpression: name = 'Arthur' COLLATE NOCASE
Column("name").collating(.nocase) == "Arthur"
```
## Add a New Kind of SQLite Expression
GRDB does not have built-in support for the full range of the SQLite [expression grammar](https://www.sqlite.org/lang_expr.html).
For example, [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) are not ready-made. They can be useful, though: a CAST expression can efficiently convert json strings to UTF-8 data blobs for you:
```sql
SELECT CAST(jsonString AS BLOB) FROM books
```
We'll add below a Swift `cast` function:
```swift
let request = Books.select(cast(Column("jsonString"), as: .blob))
let jsonDatas = try Data.fetchAll(db, request) // [Data]
```
`cast` is a top-level Swift function because this is how GRDB usually imports SQLite features which do not have matching standard Swift counterpart. It helps the Swift code looking like SQL when it is relevant. But YMMV.
The signature of the `cast` function is:
```swift
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression
```
Database.ColumnType is a String-based enumeration of all database column types (.integer, .text, .blob, etc.) You have already used if you have [created tables](../../../#create-tables) using the query interface.
The return type SQLExpression is the type returned by all GRDB functions and operators that build [query interface expressions](../../../#expressions).
SQLExpression is a protocol. But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, so that you generally don't have to write your custom expression type. Here we need something new. So we'll use the most versatile of all, SQLExpressionLiteral:
```swift
struct SQLExpressionLiteral : SQLExpression {
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral("1 + 2")
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
init(_ sql: String, arguments: StatementArguments? = nil)
}
```
Here is the code that defines our `cast` function:
```swift
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression {
// Turn the value into a literal expression
let literal: SQLExpressionLiteral = value.sqlExpression.literal
// Build our "CAST(value AS type)" sql snippet
let sql = "CAST(\(literal.sql) AS \(type.rawValue))"
// And return a new literal expression, preserving input arguments
return SQLExpressionLiteral(sql, arguments: literal.arguments)
}
```
We haven't yet described the SQLExpressible type of the `value` argument:
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
```swift
cast("foo", as: .blob) // SQLExpression: CAST('foo' AS BLOB)
cast(Column("name"), as: .blob) // SQLExpression: CAST(name AS BLOB)
```
You may want to compare it to another protocol, SQLSpecificExpressible, which has been described [above](#strftime), when we were adding support for the STRFTIME SQL function.
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.4/Protocols/SQLExpression.html) protocol.
Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

-1
View File
@@ -16,7 +16,6 @@ To release a new GRDB version:
- Makefile
- CHANGELOG.md
- Documentation/CustomSQLiteBuilds.md
- Documentation/ExtendingGRDB.md
- GRDB.swift.podspec
- GRDBCipher.podspec
- README.md
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '2.4.2'
s.version = '2.9.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+86 -8
View File
@@ -24,7 +24,7 @@
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */; };
5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
5605F1881C69111300235C62 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; };
5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; };
5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; };
@@ -140,6 +140,8 @@
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
@@ -230,6 +232,15 @@
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
5665F85D203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */; };
5665F85E203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */; };
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
566A8425204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */; };
566A8426204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */; };
566A84402041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */; };
566A84412041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */; };
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
566AD8CA1D531BEC002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; };
@@ -281,6 +292,9 @@
5674A7231F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; };
5674A72A1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; };
5674A72D1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; };
567517C820131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; };
567517C920131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; };
567517CA20131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; };
567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF1F1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
@@ -289,6 +303,8 @@
567DAF391EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
56805210201320E600E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520F201320E600E87861 /* RecordBoxTests.swift */; };
56805211201320E600E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520F201320E600E87861 /* RecordBoxTests.swift */; };
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568735A21CEDE16C009B9116 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; };
@@ -349,6 +365,9 @@
5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; };
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
569EF0E4200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; };
56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; };
56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */; };
@@ -428,6 +447,14 @@
56BF6D401DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF6D2E1DEF47DA006039A3 /* Fixits-Swift2.swift */; };
56BF6D431DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF6D2E1DEF47DA006039A3 /* Fixits-Swift2.swift */; };
56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; };
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
56CC9244201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; };
56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; };
56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; };
56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; };
56CEB4F11EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; };
56CEB4F41EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; };
56CEB4F71EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; };
@@ -533,7 +560,7 @@
56D496B31D8133E3008276D7 /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; };
56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
56D496B61D813434008276D7 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
56D496B71D81344B008276D7 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; };
56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
56D496B91D81346F008276D7 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; };
@@ -724,7 +751,7 @@
5605F1521C672E4000235C62 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+RawRepresentable.swift"; sourceTree = "<group>"; };
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementSelectionInfoTests.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = "<group>"; };
5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
@@ -771,6 +798,7 @@
56439B501F4CA1DC0066043F /* GRDBOSXPerformanceComparisonTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceComparisonTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
565490A01D5A4798005622CB /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -798,6 +826,10 @@
566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSpecificExpressible+QueryInterface.swift"; sourceTree = "<group>"; };
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableChangesTests.swift; sourceTree = "<group>"; };
566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = "<group>"; };
566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = "<group>"; };
566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = "<group>"; };
@@ -821,10 +853,12 @@
5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = "<group>"; };
5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = "<group>"; };
5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowConvertibleDecodableTests.swift; sourceTree = "<group>"; };
567517C720131B220094BF41 /* RecordBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = "<group>"; };
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
5680520F201320E600E87861 /* RecordBoxTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordBoxTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = "<group>"; };
@@ -862,6 +896,7 @@
5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = "<group>"; };
5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = "<group>"; };
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = "<group>"; };
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryTests.swift; sourceTree = "<group>"; };
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = "<group>"; };
@@ -939,6 +974,10 @@
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = SQLite.xcodeproj; path = SQLite.swift/SQLite.xcodeproj; sourceTree = "<group>"; };
56CA22211BB41565009A04C5 /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceTests.swift; sourceTree = "<group>"; };
56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
56CC9245201E058000CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = "<group>"; };
56CC9250201E093E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = "<group>"; };
56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = "<group>"; };
56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = "<group>"; };
@@ -1132,9 +1171,10 @@
560B3FA41C19DFF800C58EC7 /* Persistable */ = {
isa = PBXGroup;
children = (
566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */,
56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */,
5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */,
56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */,
56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableTests.swift */,
563363AA1C933FF8000BE133 /* PersistableTests.swift */,
);
@@ -1352,11 +1392,11 @@
569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */,
563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */,
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */,
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */,
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */,
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */,
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */,
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */,
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */,
);
name = Private;
sourceTree = "<group>";
@@ -1364,6 +1404,7 @@
56A238111B9C74A90082EB20 /* Core */ = {
isa = PBXGroup;
children = (
5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */,
56DAA2C41DE99D8D006E10C8 /* Cursor */,
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */,
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */,
@@ -1375,6 +1416,7 @@
563363BB1C93FD32000BE133 /* DatabaseQueue */,
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
@@ -1382,8 +1424,8 @@
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */,
56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */,
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */,
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */,
565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */,
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */,
56741EA71E66A8B3003E422D /* RequestTests.swift */,
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */,
56A2381D1B9C74A90082EB20 /* Row */,
@@ -1445,8 +1487,10 @@
isa = PBXGroup;
children = (
56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */,
564E73DE203D50B9000C443C /* JoinSupportTests.swift */,
560B3FA41C19DFF800C58EC7 /* Persistable */,
56176C9E1EACEDF9000F3F2B /* Record */,
5680520F201320E600E87861 /* RecordBoxTests.swift */,
5674A7251F30A8EF0095F066 /* RowConvertible */,
56176C9C1EACEA8C000F3F2B /* TableMapping */,
);
@@ -1467,7 +1511,9 @@
560A37A31C8F625000949E71 /* DatabasePool.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
@@ -1501,6 +1547,7 @@
560D92441C672C4B00F4F92B /* Persistable.swift */,
5674A6F31F307F600095F066 /* Persistable+Encodable.swift */,
56A238A11B9C753B0082EB20 /* Record.swift */,
567517C720131B220094BF41 /* RecordBox.swift */,
56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */,
5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */,
56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */,
@@ -1589,11 +1636,15 @@
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */,
5623935F1DEE06D300A6B01F /* CursorTests.swift */,
56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */,
56CC9245201E058000CB597E /* DropFirstCursorTests.swift */,
56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */,
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */,
562393561DEE013C00A6B01F /* FilterCursorTests.swift */,
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */,
562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */,
562393711DEE104400A6B01F /* MapCursorTests.swift */,
56CC9250201E093E00CB597E /* PrefixCursorTests.swift */,
56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */,
);
name = Cursor;
sourceTree = "<group>";
@@ -2139,6 +2190,7 @@
565490D91D5AE252005622CB /* Migration.swift in Sources */,
56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */,
56F3E7691E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */,
@@ -2175,6 +2227,7 @@
5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */,
567517CA20131B220094BF41 /* RecordBox.swift in Sources */,
5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
565490C61D5AE236005622CB /* Statement.swift in Sources */,
56CEB5071EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
@@ -2189,6 +2242,7 @@
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
565490C81D5AE252005622CB /* CGFloat.swift in Sources */,
56F5ABDC1D814330001F60CB /* URL.swift in Sources */,
569EF0E4200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
565490D31D5AE252005622CB /* (null) in Sources */,
566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
566B910F1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
@@ -2254,6 +2308,7 @@
56F3E7661E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */,
56B964B41DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5605F16A1C672E4000235C62 /* NSString.swift in Sources */,
@@ -2266,6 +2321,7 @@
5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
56D51D031EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */,
560D924C1C672C4B00F4F92B /* TableMapping.swift in Sources */,
567517C920131B220094BF41 /* RecordBox.swift in Sources */,
5657AB121D10899D006283EF /* URL.swift in Sources */,
5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */,
56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */,
@@ -2290,6 +2346,7 @@
5659F4A31EA8D997004A4992 /* Result.swift in Sources */,
56B964BC1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
5605F1661C672E4000235C62 /* NSNull.swift in Sources */,
569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */,
@@ -2332,6 +2389,7 @@
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56A238461B9C74A90082EB20 /* RowFromDictionaryTests.swift in Sources */,
569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */,
56805211201320E600E87861 /* RecordBoxTests.swift in Sources */,
562EA82A1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */,
56E8CE111BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift in Sources */,
@@ -2340,6 +2398,7 @@
56176C6E1EACCCC9000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
56A2384C1B9C74A90082EB20 /* UpdateStatementTests.swift in Sources */,
56A2384E1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */,
56CC9244201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
5657AB4A1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
562393491DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */,
569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */,
@@ -2365,8 +2424,10 @@
5698AC4D1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */,
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */,
563363B01C933FF8000BE133 /* MutablePersistableTests.swift in Sources */,
5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */,
56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56300B621C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
@@ -2383,8 +2444,10 @@
56176C6C1EACCCC9000F3F2B /* FTS5PatternTests.swift in Sources */,
563363B21C933FF8000BE133 /* PersistableTests.swift in Sources */,
56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */,
564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */,
5674A7121F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
5657AB521D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
5665F85E203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */,
56A238441B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */,
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */,
@@ -2394,6 +2457,7 @@
567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */,
5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
5674A72D1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */,
566A84412041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */,
56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
56FEE7FF1F47253700D930EA /* TableMappingTests.swift in Sources */,
56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */,
@@ -2408,6 +2472,7 @@
5698AC9A1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
562393521DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */,
56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
@@ -2447,10 +2512,11 @@
56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */,
56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */,
5605F1881C69111300235C62 /* StatementSelectionInfoTests.swift in Sources */,
5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */,
56176C6D1EACCCC9000F3F2B /* FTS5RecordTests.swift in Sources */,
569178491CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */,
562393761DEE104400A6B01F /* MapCursorTests.swift in Sources */,
566A8426204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */,
56E5D8181B4D435D00430942 /* GRDBTestCase.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -2471,6 +2537,7 @@
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56D496811D813131008276D7 /* TransactionObserverSavepointsTests.swift in Sources */,
56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */,
56805210201320E600E87861 /* RecordBoxTests.swift in Sources */,
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */,
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
@@ -2479,6 +2546,7 @@
56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */,
56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */,
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */,
56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */,
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
@@ -2504,8 +2572,10 @@
56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */,
56D4965F1D81304E008276D7 /* FoundationNSURLTests.swift in Sources */,
562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */,
56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */,
5698AC891DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */,
56D5075E1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
@@ -2522,8 +2592,10 @@
56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */,
56D496581D81304E008276D7 /* FoundationDateTests.swift in Sources */,
562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */,
5674A70F1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
56D496711D81309E008276D7 /* RecordPrimaryKeySingleTests.swift in Sources */,
5665F85D203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */,
5698AC031D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */,
56D496611D81304E008276D7 /* Row+FoundationTests.swift in Sources */,
56D496C41D813767008276D7 /* DatabaseQueueTests.swift in Sources */,
@@ -2533,6 +2605,7 @@
56D496961D81317B008276D7 /* PersistableTests.swift in Sources */,
5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
5674A72A1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */,
566A84402041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */,
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
56FEE7FB1F47253700D930EA /* TableMappingTests.swift in Sources */,
56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */,
@@ -2547,10 +2620,11 @@
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */,
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
56D496B61D813434008276D7 /* StatementSelectionInfoTests.swift in Sources */,
56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */,
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */,
56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */,
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */,
@@ -2590,6 +2664,7 @@
56176C5B1EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */,
56D496B91D81346F008276D7 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
56D496901D81316E008276D7 /* RowAdapterTests.swift in Sources */,
566A8425204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */,
56D496721D81309E008276D7 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -2606,6 +2681,8 @@
566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
56CEB4F11EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */,
@@ -2679,6 +2756,7 @@
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
56A238871B9C75030082EB20 /* Row.swift in Sources */,
5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */,
567517C820131B220094BF41 /* RecordBox.swift in Sources */,
560D92471C672C4B00F4F92B /* Persistable.swift in Sources */,
566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
+32
View File
@@ -43,6 +43,38 @@ public struct Configuration {
/// Default: deferred
public var defaultTransactionKind: Database.TransactionKind = .deferred
/// If false, it is a programmer error to leave a transaction opened at the
/// end of a database access block.
///
/// For example:
///
/// let dbQueue = DatabaseQueue()
///
/// // fatal error: A transaction has been left opened at the end of a database access
/// try dbQueue.inDatabase { db in
/// try db.beginTransaction()
/// }
///
/// If true, one can leave opened transaction at the end of database access
/// blocks:
///
/// var config = Configuration()
/// config.allowsUnsafeTransactions = true
/// let dbQueue = DatabaseQueue(configuration: config)
///
/// try dbQueue.inDatabase { db in
/// try db.beginTransaction()
/// }
///
/// try dbQueue.inDatabase { db in
/// try db.commit()
/// }
///
/// This configuration flag has no effect on DatabasePool readers: those
/// never allow leaving a transaction opened at the end of a read access.
///
/// Default: false
public var allowsUnsafeTransactions: Bool = false
// MARK: - Concurrency
+486 -70
View File
@@ -1,3 +1,16 @@
//===----------------------------------------------------------------------===//
//
// Parts of this file are derived from the Swift.org open source project:
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: - Array, Sequence, Set extensions
extension Array {
/// Creates an array containing the elements of a cursor.
///
@@ -11,6 +24,15 @@ extension Array {
}
}
extension Sequence {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Iterator>, SegmentOfResult>> {
return IteratorCursor(self).flatMap(transform)
}
}
extension Set {
/// Creates a set containing the elements of a cursor.
///
@@ -24,6 +46,8 @@ extension Set {
}
}
// MARK: - Cursor
/// A type that supplies the values of some external resource, one at a time.
///
/// ## Overview
@@ -46,19 +70,11 @@ extension Set {
/// - A cursor can not be repeated.
///
/// The protocol comes with default implementations for many operations similar
/// to those defined by Swift's LazySequenceProtocol:
///
/// - `func contains(Self.Element)`
/// - `func contains(where: (Self.Element) throws -> Bool)`
/// - `func enumerated()`
/// - `func filter((Self.Element) throws -> Bool)`
/// - `func first(where: (Self.Element) throws -> Bool)`
/// - `func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?)`
/// - `func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult)`
/// - `func forEach((Self.Element) throws -> Void)`
/// - `func joined()`
/// - `func map<T>((Self.Element) throws -> T)`
/// - `func reduce<Result>(Result, (Result, Self.Element) throws -> Result)`
/// to those defined by Swift's Sequence protocol: `contains`, `dropFirst`,
/// `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`,
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
/// `suffix`.
public protocol Cursor : class {
/// The type of element traversed by the cursor.
associatedtype Element
@@ -68,32 +84,6 @@ public protocol Cursor : class {
func next() throws -> Element?
}
/// A type-erased cursor of Element.
///
/// This cursor forwards its next() method to an arbitrary underlying cursor
/// having the same Element type, hiding the specifics of the underlying
/// cursor.
public class AnyCursor<Element> : Cursor {
/// Creates a cursor that wraps a base cursor but whose type depends only on
/// the base cursor’s element type
public init<C: Cursor>(_ base: C) where C.Element == Element {
element = base.next
}
/// Creates a cursor that wraps the given closure in its next() method
public init(_ body: @escaping () throws -> Element?) {
element = body
}
/// Advances to the next element and returns it, or nil if no next
/// element exists.
public func next() throws -> Element? {
return try element()
}
private let element: () throws -> Element?
}
extension Cursor {
/// Returns a Boolean value indicating whether the cursor contains an
/// element that satisfies the given predicate.
@@ -148,6 +138,102 @@ extension Cursor {
return map(transform).filter { $0 != nil }.map { $0! }
}
/// Returns a cursor that skips any initial elements that satisfy
/// `predicate`.
///
/// - Parameter predicate: A closure that takes an element of the cursir as
/// its argument and returns `true` if the element should be skipped or
/// `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor<Self> {
return DropWhileCursor(self, predicate: predicate)
}
/// Returns a cursor containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the cursor, the result is an empty cursor.
///
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// try print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the cursor. `n` must be greater than or equal to zero.
/// - Returns: A cursor starting after the specified number of
/// elements.
public func dropFirst(_ n: Int) -> DropFirstCursor<Self> {
return DropFirstCursor(self, limit: n)
}
/// Returns a cursor containing all but the first element of the cursor.
///
/// The following example drops the first element from a cursor of integers.
///
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst())
/// // Prints "[2, 3, 4, 5]"
///
/// If the cursor has no elements, the result is an empty cursor.
///
/// - Returns: A cursor starting after the first element of the cursor.
public func dropFirst() -> DropFirstCursor<Self> {
return dropFirst(1)
}
/// Returns an array containing all but the given number of final
/// elements.
///
/// The cursor must be finite. If the number of elements to drop exceeds
/// the number of elements in the cursor, the result is an empty array.
///
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// try print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// cursor. `n` must be greater than or equal to zero.
/// - Returns: An array leaving off the specified number of elements.
public func dropLast(_ n: Int) throws -> [Element] {
GRDBPrecondition(n >= 0, "Can't drop a negative number of elements from a cursor")
if n == 0 { return try Array(self) }
var result: [Element] = []
var ringBuffer: [Element] = []
var i = ringBuffer.startIndex
while let element = try next() {
if ringBuffer.count < n {
ringBuffer.append(element)
} else {
result.append(ringBuffer[i])
ringBuffer[i] = element
i = ringBuffer.index(after: i) % n
}
}
return result
}
/// Returns an array containing all but the last element of the cursor.
///
/// The following example drops the last element from a cursor of integers.
///
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast())
/// // Prints "[1, 2, 3, 4]"
///
/// If the cursor has no elements, the result is an empty cursor.
///
/// - Returns: An array leaving off the last element of the cursor.
public func dropLast() throws -> [Element] {
return try dropLast(1)
}
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> {
@@ -173,17 +259,152 @@ extension Cursor {
return MapCursor(self, transform)
}
/// Returns the result of calling the given combining closure with each
/// element of this sequence and an accumulating value.
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result {
var result = initialResult
while let element = try next() {
result = try nextPartialResult(result, element)
/// Returns the maximum element in the cursor, using the given predicate as
/// the comparison between elements.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's maximum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
guard var result = try next() else {
return nil
}
while let e = try next() {
if try areInIncreasingOrder(result, e) {
result = e
}
}
return result
}
/// Returns the minimum element in the cursor, using the given predicate as
/// the comparison between elements.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's minimum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
public func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
guard var result = try next() else {
return nil
}
while let e = try next() {
if try areInIncreasingOrder(e, result) {
result = e
}
}
return result
}
/// Returns a cursor, up to the specified maximum length, containing the
/// initial elements of the cursor.
///
/// If the maximum length exceeds the number of elements in the cursor,
/// the result contains all the elements in the cursor.
///
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
/// try print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// try print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A cursor starting at the beginning of this cursor
/// with at most `maxLength` elements.
public func prefix(_ maxLength: Int) -> PrefixCursor<Self> {
return PrefixCursor(self, maxLength: maxLength)
}
/// Returns a cursor of the initial consecutive elements that satisfy
/// `predicate`.
///
/// - Parameter predicate: A closure that takes an element of the cursor as
/// its argument and returns `true` if the element should be included or
/// `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor<Self> {
return PrefixWhileCursor(self, predicate: predicate)
}
/// Returns the result of calling the given combining closure with each
/// element of this cursor and an accumulating value.
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Element) throws -> Result)
throws -> Result
{
var accumulator = initialResult
while let element = try next() {
accumulator = try nextPartialResult(accumulator, element)
}
return accumulator
}
/// Returns the result of calling the given combining closure with each
/// element of this cursor and an accumulating value.
public func reduce<Result>(
into initialResult: Result,
_ updateAccumulatingResult: (inout Result, Element) throws -> Void)
throws -> Result
{
var accumulator = initialResult
while let element = try next() {
try updateAccumulatingResult(&accumulator, element)
}
return accumulator
}
/// Returns an array, up to the given maximum length, containing the
/// final elements of the cursor.
///
/// The cursor must be finite. If the maximum length exceeds the number of
/// elements in the cursor, the result contains all the elements in the
/// cursor.
///
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
/// try print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// try print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
public func suffix(_ maxLength: Int) throws -> [Element] {
GRDBPrecondition(maxLength >= 0, "Can't take a suffix of negative length from a cursor")
if maxLength == 0 {
return []
}
var ringBuffer: [Element] = []
ringBuffer.reserveCapacity(maxLength)
var i = ringBuffer.startIndex
while let element = try next() {
if ringBuffer.count < maxLength {
ringBuffer.append(element)
} else {
ringBuffer[i] = element
i += 1
i %= maxLength
}
}
if i != ringBuffer.startIndex {
let s0 = ringBuffer[i..<ringBuffer.endIndex]
let s1 = ringBuffer[0..<i]
return Array([s0, s1].joined())
}
return ringBuffer
}
}
// MARK: Equatable elements
extension Cursor where Element: Equatable {
/// Returns a Boolean value indicating whether the cursor contains the
/// given element.
@@ -197,6 +418,36 @@ extension Cursor where Element: Equatable {
}
}
// MARK: Comparable elements
extension Cursor where Element: Comparable {
/// Returns the maximum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's maximum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
public func max() throws -> Element? {
return try max(by: <)
}
/// Returns the minimum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's minimum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
public func min() throws -> Element? {
return try min(by: <)
}
}
// MARK: Cursor elements
extension Cursor where Element: Cursor {
/// Returns the elements of this cursor of cursors, concatenated.
public func joined() -> FlattenCursor<Self> {
@@ -204,13 +455,122 @@ extension Cursor where Element: Cursor {
}
}
// MARK: Sequence elements
extension Cursor where Element: Sequence {
/// Returns the elements of this cursor of sequences, concatenated.
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Self.Element.Iterator>>> {
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Element.Iterator>>> {
return flatMap { $0 }
}
}
// MARK: String elements
extension Cursor where Element: StringProtocol {
/// Returns the elements of this cursor of sequences, concatenated.
public func joined(separator: String = "") throws -> String {
if separator.isEmpty {
var result = ""
while let x = try next() {
result.append(String(x))
}
return result
} else {
var result = ""
if let first = try next() {
result.append(String(first))
while let next = try next() {
result.append(separator)
result.append(String(next))
}
}
return result
}
}
}
// MARK: Specialized Cursors
/// A type-erased cursor of Element.
///
/// This cursor forwards its next() method to an arbitrary underlying cursor
/// having the same Element type, hiding the specifics of the underlying
/// cursor.
public class AnyCursor<Element> : Cursor {
private let element: () throws -> Element?
/// Creates a cursor that wraps a base cursor but whose type depends only on
/// the base cursor’s element type
public init<C: Cursor>(_ base: C) where C.Element == Element {
element = base.next
}
/// Creates a cursor that wraps the given closure in its next() method
public init(_ body: @escaping () throws -> Element?) {
element = body
}
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Element? {
return try element()
}
}
/// :nodoc:
public final class DropFirstCursor<Base: Cursor> : Cursor {
private let base: Base
private let limit: Int
private var dropped: Int = 0
init(_ base: Base, limit: Int) {
GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor")
self.base = base
self.limit = limit
}
public func next() throws -> Base.Element? {
while dropped < limit {
if try base.next() == nil {
dropped = limit
return nil
}
dropped += 1
}
return try base.next()
}
}
/// A cursor whose elements consist of the elements that follow the initial
/// consecutive elements of some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class DropWhileCursor<Base: Cursor> : Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
self.base = base
self.predicate = predicate
}
public func next() throws -> Base.Element? {
if predicateHasFailed {
return try base.next()
}
while let nextElement = try base.next() {
if try !predicate(nextElement) {
predicateHasFailed = true
return nextElement
}
}
return nil
}
}
/// An enumeration of the elements of a cursor.
///
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
@@ -223,27 +583,35 @@ extension Cursor where Element: Sequence {
/// }
/// // Prints: "0: foo"
/// // Prints: "1: bar"
///
/// :nodoc:
public final class EnumeratedCursor<Base: Cursor> : Cursor {
private let base: Base
private var index: Int
init(_ base: Base) {
self.index = 0
self.base = base
self.index = 0
}
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> (Int, Base.Element)? {
guard let element = try base.next() else { return nil }
defer { index += 1 }
return (index, element)
}
private var index: Int
private var base: Base
}
/// A cursor whose elements consist of the elements of some base cursor that
/// also satisfy a given predicate.
///
/// :nodoc:
public final class FilterCursor<Base: Cursor> : Cursor {
private let base: Base
private let isIncluded: (Base.Element) throws -> Bool
init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) {
self.base = base
self.isIncluded = isIncluded
@@ -251,6 +619,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Base.Element? {
while let element = try base.next() {
if try isIncluded(element) {
@@ -259,22 +628,25 @@ public final class FilterCursor<Base: Cursor> : Cursor {
}
return nil
}
private let base: Base
private let isIncluded: (Base.Element) throws -> Bool
}
/// A cursor consisting of all the elements contained in each segment contained
/// in some Base cursor.
///
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
///
/// :nodoc:
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
private let base: Base
private var inner: Base.Element?
init(_ base: Base) {
self.base = base
}
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Base.Element.Element? {
while true {
if let element = try inner?.next() {
@@ -286,16 +658,18 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
self.inner = inner
}
}
private var inner: Base.Element?
private let base: Base
}
/// A Cursor whose elements consist of those in a Base Cursor passed through a
/// transform function returning Element.
///
/// See Cursor.map(_:)
///
/// :nodoc:
public final class MapCursor<Base: Cursor, Element> : Cursor {
private let base: Base
private let transform: (Base.Element) throws -> Element
init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) {
self.base = base
self.transform = transform
@@ -303,18 +677,70 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() throws -> Element? {
guard let element = try base.next() else { return nil }
return try transform(element)
}
}
/// A cursor that only consumes up to `n` elements from an underlying
/// `Base` cursor.
///
/// :nodoc:
public final class PrefixCursor<Base: Cursor> : Cursor {
private let base: Base
private let transform: (Base.Element) throws -> Element
private let maxLength: Int
private var taken = 0
init(_ base: Base, maxLength: Int) {
self.base = base
self.maxLength = maxLength
}
public func next() throws -> Base.Element? {
if taken >= maxLength { return nil }
taken += 1
if let next = try base.next() {
return next
}
taken = maxLength
return nil
}
}
/// A cursor whose elements consist of the initial consecutive elements of
/// some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class PrefixWhileCursor<Base: Cursor> : Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
self.base = base
self.predicate = predicate
}
public func next() throws -> Base.Element? {
if !predicateHasFailed, let nextElement = try base.next() {
if try predicate(nextElement) {
return nextElement
} else {
predicateHasFailed = true
}
}
return nil
}
}
/// A Cursor whose elements are those of a sequence iterator.
public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
private var base: Base
/// Creates a cursor from a sequence iterator.
public init(_ base: Base) {
self.base = base
@@ -327,18 +753,8 @@ public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
/// Advances to the next element and returns it, or nil if no next
/// element exists.
/// :nodoc:
public func next() -> Base.Element? {
return base.next()
}
private var base: Base
}
extension Sequence {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Self.Iterator>, SegmentOfResult>> {
return IteratorCursor(self).flatMap(transform)
}
}
+98 -24
View File
@@ -132,6 +132,7 @@ extension Database {
/// The number of columns in the table named `tableName`.
///
/// - throws: A DatabaseError if table does not exist.
@available(*, deprecated, message: "Use db.columns(in: tableName).count instead")
public func columnCount(in tableName: String) throws -> Int {
return try columns(in: tableName).count
}
@@ -215,14 +216,35 @@ extension Database {
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
return foreignKeys
}
/// Returns the actual name of the database table
func canonicalName(table: String) throws -> String {
if let canonicalName = schemaCache.canonicalName(table: table) {
return canonicalName
}
guard let canonicalName = try String.fetchOne(self, """
SELECT name FROM (
SELECT name, type FROM sqlite_master
UNION
SELECT name, type FROM sqlite_temp_master)
WHERE type = 'table' AND LOWER(name) = ?
""", arguments: [table.lowercased()])
else {
throw DatabaseError(message: "no such table: \(table)")
}
schemaCache.set(canonicalName: canonicalName, forTable: table)
return canonicalName
}
}
extension Database {
/// The columns in the table named `tableName`.
/// The columns in the table named `tableName`
///
/// - throws: A DatabaseError if table does not exist.
func columns(in tableName: String) throws -> [ColumnInfo] {
public func columns(in tableName: String) throws -> [ColumnInfo] {
if let columns = schemaCache.columns(in: tableName) {
return columns
}
@@ -258,7 +280,9 @@ extension Database {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
let columns = try ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
let columns = try ColumnInfo
.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.sorted(by: { $0.cid < $1.cid })
guard columns.count > 0 else {
throw DatabaseError(message: "no such table: \(tableName)")
}
@@ -284,30 +308,80 @@ extension Database {
}
}
/// A column of a table
struct ColumnInfo : RowConvertible {
// CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
//
// PRAGMA table_info("players")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
let name: String
let type: String
let notNull: Bool
let defaultDatabaseValue: DatabaseValue
let primaryKeyIndex: Int
/// A column of a database table.
///
/// This type closely matches the information returned by the
/// `table_info` pragma.
///
/// > CREATE TABLE players (
/// id INTEGER PRIMARY KEY,
/// firstName TEXT,
/// lastName TEXT)
/// > PRAGMA table_info("players")
/// cid name type notnull dflt_value pk
/// ---- ----- ------- -------- ---------- ---
/// 0 id INTEGER 0 NULL 1
/// 1 name TEXT 0 NULL 0
/// 2 score INTEGER 0 NULL 0
///
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
public struct ColumnInfo : RowConvertible {
let cid: Int
init(row: Row) {
/// The column name
public let name: String
/// The column data type
public let type: String
/// True if and only if the column is constrained to be not null.
public let isNotNull: Bool
/// The SQL snippet that defines the default value, if any.
///
/// When nil, the column has no default value.
///
/// When not nil, it contains an SQL string that defines an expression. That
/// expression may be a literal, as `1`, or `'foo'`. It may also contain a
/// non-constant expression such as `CURRENT_TIMESTAMP`.
///
/// For example:
///
/// try db.execute("""
/// CREATE TABLE players(
/// id INTEGER PRIMARY KEY,
/// name TEXT DEFAULT 'Anonymous',
/// score INT DEFAULT 0,
/// creationDate DATE DEFAULT CURRENT_TIMESTAMP
/// )
/// """)
/// let columnInfos = try db.columns(in: "players")
/// columnInfos[0].defaultValueSQL // nil
/// columnInfos[1].defaultValueSQL // "'Anoynymous'"
/// columnInfos[2].defaultValueSQL // "0"
/// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
public let defaultValueSQL: String?
/// Zero for columns that are not part of the primary key.
///
/// Before SQLite 3.7.16, it is 1 for columns that are part of the
/// primary key.
///
/// Starting from SQLite 3.7.16, it is the one-based index of the column in
/// the primary key for columns that are part of the primary key.
///
/// References:
/// - https://sqlite.org/releaselog/3_7_16.html
/// - http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html
public let primaryKeyIndex: Int
/// :nodoc:
public init(row: Row) {
cid = row["cid"]
name = row["name"]
type = row["type"]
notNull = row["notnull"]
defaultDatabaseValue = row["dflt_value"]
isNotNull = row["notnull"]
defaultValueSQL = row["dflt_value"]
primaryKeyIndex = row["pk"]
}
}
+23 -5
View File
@@ -98,6 +98,8 @@ public final class Database {
/// True if the database connection is currently in a transaction.
public var isInsideTransaction: Bool {
if isClosed { return false }
// https://sqlite.org/c3ref/get_autocommit.html
//
// > The sqlite3_get_autocommit() interface returns non-zero or zero if
@@ -270,7 +272,7 @@ extension Database {
setupBusyMode()
setupDefaultFunctions()
setupDefaultCollations()
observationBroker.setup()
observationBroker.installCommitAndRollbackHooks()
}
private func setupTrace() {
@@ -549,7 +551,7 @@ extension Database {
/// - throws: The error thrown by the block.
public func inTransaction(_ kind: TransactionKind? = nil, _ block: () throws -> TransactionCompletion) throws {
// Begin transaction
try beginTransaction(kind ?? configuration.defaultTransactionKind)
try beginTransaction(kind)
// Now that transaction has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
@@ -669,11 +671,20 @@ extension Database {
}
}
func beginTransaction(_ kind: TransactionKind) throws {
/// Begins a database transaction.
///
/// - parameter kind: The transaction type (default nil). If nil, the
/// transaction type is configuration.defaultTransactionKind, which itself
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - throws: The error thrown by the block.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
let kind = kind ?? configuration.defaultTransactionKind
try execute("BEGIN \(kind.rawValue) TRANSACTION")
}
private func rollback() throws {
/// Rollbacks a database transaction.
public func rollback() throws {
// The SQLite documentation contains two related but distinct techniques
// to handle rollbacks and errors:
//
@@ -718,7 +729,8 @@ extension Database {
}
}
func commit() throws {
/// Commits a database transaction.
public func commit() throws {
try execute("COMMIT TRANSACTION")
}
}
@@ -817,8 +829,10 @@ extension Database {
///
/// See https://www.sqlite.org/datatype3.html#collation
public struct CollationName : RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
/// :nodoc:
public init(rawValue: String) {
self.rawValue = rawValue
}
@@ -828,6 +842,7 @@ extension Database {
}
/// The hash value
/// :nodoc:
public var hashValue: Int {
return rawValue.hashValue
}
@@ -851,8 +866,10 @@ extension Database {
///
/// See https://www.sqlite.org/datatype3.html
public struct ColumnType : RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
/// :nodoc:
public init(rawValue: String) {
self.rawValue = rawValue
}
@@ -862,6 +879,7 @@ extension Database {
}
/// The hash value
/// :nodoc:
public var hashValue: Int {
return rawValue.hashValue
}
+2
View File
@@ -33,6 +33,7 @@ public final class DatabaseCollation {
}
extension DatabaseCollation : Hashable {
/// :nodoc:
public var hashValue: Int {
// Collation equality is based on the sqlite3_strnicmp SQLite function.
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
@@ -44,6 +45,7 @@ extension DatabaseCollation : Hashable {
}
/// Two collations are equal if they share the same name (case insensitive)
/// :nodoc:
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
// See https://www.sqlite.org/c3ref/create_collation.html
return sqlite3_stricmp(lhs.name, lhs.name) == 0
+16 -6
View File
@@ -5,7 +5,7 @@ import Foundation
import SQLite3
#endif
public struct ResultCode : RawRepresentable {
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -139,13 +139,17 @@ public struct ResultCode : RawRepresentable {
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
}
extension ResultCode : Equatable {
// Equatable
extension ResultCode {
/// :nodoc:
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension ResultCode : CustomStringConvertible {
// CustomStringConvertible
extension ResultCode {
/// :nodoc:
public var description: String {
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
@@ -162,7 +166,7 @@ extension ResultCode : CustomStringConvertible {
}
/// DatabaseError wraps an SQLite error.
public struct DatabaseError : Error {
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
/// The SQLite error code (see
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
@@ -223,7 +227,9 @@ public struct DatabaseError : Error {
let arguments: StatementArguments?
}
extension DatabaseError: CustomStringConvertible {
// CustomStringConvertible
extension DatabaseError {
/// :nodoc:
public var description: String {
var description = "SQLite error \(resultCode.rawValue)"
if let sql = sql {
@@ -239,19 +245,23 @@ extension DatabaseError: CustomStringConvertible {
}
}
extension DatabaseError : CustomNSError {
// CustomNSError
extension DatabaseError {
/// NSError bridging: the domain of the error.
/// :nodoc:
public static var errorDomain: String {
return "GRDB.DatabaseError"
}
/// NSError bridging: the error code within the given domain.
/// :nodoc:
public var errorCode: Int {
return Int(extendedResultCode.rawValue)
}
/// NSError bridging: the user-info dictionary.
/// :nodoc:
public var errorUserInfo: [String : Any] {
return [NSLocalizedDescriptionKey: description]
}
+2
View File
@@ -311,11 +311,13 @@ public final class DatabaseFunction {
extension DatabaseFunction : Hashable {
/// The hash value
/// :nodoc:
public var hashValue: Int {
return name.hashValue ^ nArg.hashValue
}
/// Two functions are equal if they share the same name and arity.
/// :nodoc:
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
}
+51 -11
View File
@@ -39,7 +39,6 @@ public final class DatabasePool {
/// - parameters:
/// - path: The path to the database file.
/// - configuration: A configuration.
/// - maximumReaderCount: The maximum number of readers. Default is 5.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public init(path: String, configuration: Configuration = Configuration()) throws {
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
@@ -77,21 +76,13 @@ public final class DatabasePool {
readerConfig = configuration
readerConfig.readonly = true
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction.
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
let reader = try SerializedDatabase(
path: path,
configuration: self.readerConfig,
schemaCache: SimpleDatabaseSchemaCache())
reader.sync { db in
for function in self.functions {
db.add(function: function)
}
for collation in self.collations {
db.add(collation: collation)
}
}
reader.sync { self.setupDatabase($0) }
return reader
})
}
@@ -105,6 +96,15 @@ public final class DatabasePool {
NotificationCenter.default.removeObserver(self)
}
#endif
private func setupDatabase(_ db: Database) {
for function in self.functions {
db.add(function: function)
}
for collation in self.collations {
db.add(collation: collation)
}
}
}
extension DatabasePool {
@@ -616,3 +616,43 @@ extension DatabasePool : DatabaseWriter {
}
}
}
extension DatabasePool {
// MARK: - Snapshots
/// Creates a database snapshot.
//:
/// The snapshot sees an unchanging database content, as it existed at the
/// moment it was created.
///
/// When you want to control the latest committed changes seen by a
/// snapshot, create it from the pool's writer protected dispatch queue:
///
/// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
/// try Player.deleteAll()
/// return dbPool.makeSnapshot()
/// }
/// // <- Other threads may modify the database here
/// let snapshot2 = try dbPool.makeSnapshot()
///
/// try snapshot1.read { db in
/// // Guaranteed to be zero
/// try Player.fetchCount(db)
/// }
///
/// try snapshot2.read { db in
/// // Could be anything
/// try Player.fetchCount(db)
/// }
///
/// You can create as many snapshots as you need, regardless of the maximum
/// number of reader connections in the pool.
///
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
public func makeSnapshot() throws -> DatabaseSnapshot {
let snapshot = try DatabaseSnapshot(path: path, configuration: writer.configuration)
snapshot.read { setupDatabase($0) }
return snapshot
}
}
+12 -4
View File
@@ -188,8 +188,8 @@ extension DatabaseQueue {
extension DatabaseQueue : DatabaseReader {
// MARK: - DatabaseReader Protocol Adoption
// MARK: - Reading from Database
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
@@ -220,6 +220,8 @@ extension DatabaseQueue : DatabaseReader {
}
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
///
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
@@ -233,6 +235,8 @@ extension DatabaseQueue : DatabaseReader {
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
///
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try serializedDatabase.reentrantSync(block)
}
@@ -282,10 +286,10 @@ extension DatabaseQueue : DatabaseReader {
}
extension DatabaseQueue : DatabaseWriter {
// MARK: - DatabaseWriter Protocol Adoption
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
///
/// :nodoc:
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
@@ -300,6 +304,8 @@ extension DatabaseQueue : DatabaseWriter {
/// outside of a transaction. You'll get a fatal error otherwise.
///
/// See `DatabaseWriter.readFromCurrentState`.
///
/// :nodoc:
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
// Check that we're on the correct queue...
serializedDatabase.execute { db in
@@ -320,6 +326,8 @@ extension DatabaseQueue : DatabaseWriter {
}
}
// MARK: - Unsafe Database Access
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
+7
View File
@@ -223,34 +223,41 @@ public final class AnyDatabaseReader : DatabaseReader {
// MARK: - Reading from Database
/// :nodoc:
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
// MARK: - Functions
/// :nodoc:
public func add(function: DatabaseFunction) {
base.add(function: function)
}
/// :nodoc:
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
// MARK: - Collations
/// :nodoc:
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
/// :nodoc:
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
+303
View File
@@ -0,0 +1,303 @@
/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
/// to help transaction observers recognize impactful database changes in their
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
///
/// A database region is the union of any number of "table regions", which can
/// cover a full table, or the combination of columns and rows (identified by
/// their rowids):
///
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
/// |-------| |-------| |-------| |-------| |-------|
/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | |
/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | |
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
///
/// You don't create a database region directly. Instead, you use one of
/// those methods:
///
/// - `SelectStatement.fetchedRegion`:
///
/// let statement = db.makeSelectStatement("SELECT name, score FROM players")
/// print(statement.fetchedRegion)
/// // prints "players(name,score)"
///
/// - `Request.fetchedRegion(_:)`
///
/// let request = Player.filter(key: 1)
/// try print(request.fetchedRegion(db))
/// // prints "players(*)[1]"
///
/// Database regions returned by requests can be more precise than regions
/// returned by select statements. Especially, regions returned by statements
/// don't know about rowids:
///
/// // A plain statement
/// let statement = db.makeSelectStatement("SELECT * FROM players WHERE id = 1")
/// statement.fetchedRegion // "players(*)"
///
/// // A query interface request that executes the same statement:
/// let request = Player.filter(key: 1)
/// try request.fetchedRegion(db) // "players(*)[1]"
public struct DatabaseRegion: CustomStringConvertible, Equatable {
private let tableRegions: [String: TableRegion]?
private init(tableRegions: [String: TableRegion]?) {
self.tableRegions = tableRegions
}
/// Returns whether the region is empty.
public var isEmpty: Bool {
guard let tableRegions = tableRegions else { return false }
return tableRegions.isEmpty
}
/// The full database: (All columns in all tables) × (all rows)
static let fullDatabase = DatabaseRegion(tableRegions: nil)
/// The empty database region
public init() {
self.init(tableRegions: [:])
}
/// A full table: (all columns in the table) × (all rows)
init(table: String) {
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
}
/// Full columns in a table: (some columns in a table) × (all rows)
init(table: String, columns: Set<String>) {
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
}
/// Full rows in a table: (all columns in a table) × (some rows)
init(table: String, rowIds: Set<Int64>) {
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
}
/// Returns the intersection of this region and the given one.
///
/// This method is not public because there is no known public use case for
/// this intersection. It is currently only used as support for
/// the isModified(byEventsOfKind:) method.
func intersection(_ other: DatabaseRegion) -> DatabaseRegion {
guard let tableRegions = tableRegions else { return other }
guard let otherTableRegions = other.tableRegions else { return self }
var tableRegionsIntersection: [String: TableRegion] = [:]
for (table, tableRegion) in tableRegions {
guard let otherTableRegion = otherTableRegions
.first(where: { (otherTable, _) in otherTable == table })?
.value else { continue }
let tableRegionIntersection = tableRegion.intersection(otherTableRegion)
guard !tableRegionIntersection.isEmpty else { continue }
tableRegionsIntersection[table] = tableRegionIntersection
}
return DatabaseRegion(tableRegions: tableRegionsIntersection)
}
/// Only keeps those rowIds in the given table
func tableIntersection(_ table: String, rowIds: Set<Int64>) -> DatabaseRegion {
guard var tableRegions = tableRegions else {
return DatabaseRegion(table: table, rowIds: rowIds)
}
guard let tableRegion = tableRegions[table] else {
return self
}
let intersection = tableRegion.intersection(TableRegion(columns: nil, rowIds: rowIds))
if intersection.isEmpty {
tableRegions.removeValue(forKey: table)
} else {
tableRegions[table] = intersection
}
return DatabaseRegion(tableRegions: tableRegions)
}
/// Returns the union of this region and the given one.
public func union(_ other: DatabaseRegion) -> DatabaseRegion {
guard let tableRegions = tableRegions else { return .fullDatabase }
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
var tableRegionsUnion: [String: TableRegion] = [:]
let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key }))
for table in tableNames {
let tableRegion = tableRegions[table]
let otherTableRegion = otherTableRegions[table]
let tableRegionUnion: TableRegion
switch (tableRegion, otherTableRegion) {
case (nil, nil):
preconditionFailure()
case (nil, let tableRegion?), (let tableRegion?, nil):
tableRegionUnion = tableRegion
case (let tableRegion?, let otherTableRegion?):
tableRegionUnion = tableRegion.union(otherTableRegion)
}
tableRegionsUnion[table] = tableRegionUnion
}
return DatabaseRegion(tableRegions: tableRegionsUnion)
}
/// Inserts the given region into this region
public mutating func formUnion(_ other: DatabaseRegion) {
self = union(other)
}
}
extension DatabaseRegion {
// MARK: - Database Events
/// Returns whether the content in the region would be impacted if the
/// database were modified by an event of this kind.
public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool {
return !intersection(eventKind.modifiedRegion).isEmpty
}
/// Returns whether the content in the region is impacted by this event.
///
/// - precondition: event has been filtered by the same region
/// in the TransactionObserver.observes(eventsOfKind:) method, by calling
/// region.isModified(byEventsOfKind:)
public func isModified(by event: DatabaseEvent) -> Bool {
guard let tableRegions = tableRegions else {
return true
}
switch tableRegions.count {
case 1:
// The precondition applies here:
//
// The region contains a single table. Due to the
// filtering of events performed in observes(eventsOfKind:), the
// event argument is guaranteed to be about the fetched table.
// We thus only have to check for rowIds.
assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check
guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else {
return true
}
return rowIds.contains(event.rowID)
default:
guard let tableRegion = tableRegions[event.tableName] else {
// Shouldn't happen if the precondition is met.
fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)")
}
guard let rowIds = tableRegion.rowIds else {
return true
}
return rowIds.contains(event.rowID)
}
}
}
// Equatable
extension DatabaseRegion {
/// :nodoc:
public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool {
switch (lhs.tableRegions, rhs.tableRegions) {
case (nil, nil):
return true
case (let ltableRegions?, let rtableRegions?):
let ltableNames = Set(ltableRegions.map { $0.key })
let rtableNames = Set(rtableRegions.map { $0.key })
guard ltableNames == rtableNames else {
return false
}
for tableName in ltableNames {
if ltableRegions[tableName]! != rtableRegions[tableName]! {
return false
}
}
return true
default:
return false
}
}
}
// CustomStringConvertible
extension DatabaseRegion {
/// :nodoc:
public var description: String {
guard let tableRegions = tableRegions else {
return "full database"
}
if tableRegions.isEmpty {
return "empty"
}
return tableRegions
.sorted(by: { (l, r) in l.key < r.key })
.map { (table, tableRegion) in
var desc = table
if let columns = tableRegion.columns {
desc += "(" + columns.sorted().joined(separator: ",") + ")"
} else {
desc += "(*)"
}
if let rowIds = tableRegion.rowIds {
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
}
return desc
}
.joined(separator: ",")
}
}
private struct TableRegion: Equatable {
var columns: Set<String>? // nil means "all columns"
var rowIds: Set<Int64>? // nil means "all rowids"
var isEmpty: Bool {
if let columns = columns, columns.isEmpty { return true }
if let rowIds = rowIds, rowIds.isEmpty { return true }
return false
}
static func == (lhs: TableRegion, rhs: TableRegion) -> Bool {
if lhs.columns != rhs.columns { return false }
if lhs.rowIds != rhs.rowIds { return false }
return true
}
func intersection(_ other: TableRegion) -> TableRegion {
let columnsIntersection: Set<String>?
switch (self.columns, other.columns) {
case (nil, let columns), (let columns, nil):
columnsIntersection = columns
case (let columns?, let other?):
columnsIntersection = columns.intersection(other)
}
let rowIdsIntersection: Set<Int64>?
switch (self.rowIds, other.rowIds) {
case (nil, let rowIds), (let rowIds, nil):
rowIdsIntersection = rowIds
case (let rowIds?, let other?):
rowIdsIntersection = rowIds.intersection(other)
}
return TableRegion(columns: columnsIntersection, rowIds: rowIdsIntersection)
}
func union(_ other: TableRegion) -> TableRegion {
let columnsUnion: Set<String>?
switch (self.columns, other.columns) {
case (nil, _), (_, nil):
columnsUnion = nil
case (let columns?, let other?):
columnsUnion = columns.union(other)
}
let rowIdsUnion: Set<Int64>?
switch (self.rowIds, other.rowIds) {
case (nil, _), (_, nil):
rowIdsUnion = nil
case (let rowIds?, let other?):
rowIdsUnion = rowIds.union(other)
}
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
}
}
+20 -4
View File
@@ -2,6 +2,9 @@
protocol DatabaseSchemaCache {
mutating func clear()
func canonicalName(table: String) -> String?
mutating func set(canonicalName: String, forTable table: String)
func primaryKey(_ table: String) -> PrimaryKeyInfo?
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
@@ -17,18 +20,28 @@ protocol DatabaseSchemaCache {
/// A thread-unsafe database schema cache
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
private var canonicalNames: [String: String] = [:]
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
private var columns: [String: [ColumnInfo]] = [:]
private var indexes: [String: [IndexInfo]] = [:]
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
mutating func clear() {
canonicalNames = [:]
primaryKeys = [:]
columns = [:]
indexes = [:]
foreignKeys = [:]
}
func canonicalName(table: String) -> String? {
return canonicalNames[table]
}
mutating func set(canonicalName: String, forTable table: String) {
canonicalNames[table] = table
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return primaryKeys[table]
}
@@ -66,15 +79,18 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
func clear() { }
func canonicalName(table: String) -> String? { return nil }
func set(canonicalName: String, forTable table: String) { }
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
func columns(in table: String) -> [ColumnInfo]? { return nil }
mutating func set(columns: [ColumnInfo], forTable table: String) { }
func set(columns: [ColumnInfo], forTable table: String) { }
func indexes(on table: String) -> [IndexInfo]? { return nil }
mutating func set(indexes: [IndexInfo], forTable table: String) { }
func set(indexes: [IndexInfo], forTable table: String) { }
func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil }
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
}
+124
View File
@@ -0,0 +1,124 @@
/// A DatabaseSnapshot sees an unchanging database content, as it existed at the
/// moment it was created.
///
/// See DatabasePool.makeSnapshot()
///
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
public class DatabaseSnapshot : DatabaseReader {
private var serializedDatabase: SerializedDatabase
/// The database configuration
var configuration: Configuration {
return serializedDatabase.configuration
}
init(path: String, configuration: Configuration = Configuration()) throws {
var configuration = configuration
configuration.readonly = true
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
serializedDatabase = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache())
try serializedDatabase.sync { db in
// Assert WAL mode
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode")
guard journalMode == "wal" else {
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
}
// Establish snapshot isolation (see deinit)
try db.beginTransaction(.deferred)
// Take snapshot
// See DatabasePool.readFromCurrentState for a complete discussion
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
}
}
deinit {
// Leave snapshot isolation
serializedDatabase.sync { db in
try? db.commit()
}
}
}
// DatabaseReader
extension DatabaseSnapshot {
// MARK: - Reading from Database
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
///
/// let players = try snapshot.read { db in
/// try Player.fetchAll(...)
/// }
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
}
/// Alias for `read`. See `DatabaseReader.unsafeRead`.
///
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
}
/// Alias for `read`. See `DatabaseReader.unsafeReentrantRead`.
///
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try serializedDatabase.sync(block)
}
// MARK: - Functions
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
/// }
/// snapshot.add(function: fn)
/// try snapshot.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
serializedDatabase.sync { $0.add(function: function) }
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
serializedDatabase.sync { $0.remove(function: function) }
}
// MARK: - Collations
/// Add or redefine a collation.
///
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// snapshot.add(collation: collation)
/// let files = try snapshot.read { db in
/// try File.fetchAll(db, "SELECT * FROM files ORDER BY name COLLATE localized_standard")
/// }
public func add(collation: DatabaseCollation) {
serializedDatabase.sync { $0.add(collation: collation) }
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
serializedDatabase.sync { $0.remove(collation: collation) }
}
}
+27 -6
View File
@@ -10,7 +10,7 @@ import Foundation
/// DatabaseValue is the intermediate type between SQLite and your values.
///
/// See https://www.sqlite.org/datatype3.html
public struct DatabaseValue {
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpressible, SQLExpression {
/// The SQLite storage
public let storage: Storage
@@ -146,9 +146,11 @@ public struct DatabaseValue {
// MARK: - Hashable & Equatable
extension DatabaseValue : Hashable {
// Hashable
extension DatabaseValue {
/// The hash value
/// :nodoc:
public var hashValue: Int {
switch storage {
case .null:
@@ -202,6 +204,17 @@ extension DatabaseValue : Hashable {
}
}
// MARK: - SQLSelectable
extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func qualified(by qualifier: SQLTableQualifier) -> DatabaseValue {
return self
}
}
// MARK: - Lossless conversions
extension DatabaseValue {
@@ -280,7 +293,8 @@ extension DatabaseValue {
}
}
extension DatabaseValue : DatabaseValueConvertible {
// DatabaseValueConvertible
extension DatabaseValue {
/// Returns self
public var databaseValue: DatabaseValue {
return self
@@ -292,15 +306,19 @@ extension DatabaseValue : DatabaseValueConvertible {
}
}
extension DatabaseValue : SQLExpressible {
// SQLExpressible
extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var sqlExpression: SQLExpression {
return self
}
}
extension DatabaseValue : SQLExpression {
// SQLExpression
extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
// fast path for NULL
if isNull {
@@ -318,6 +336,7 @@ extension DatabaseValue : SQLExpression {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var negated: SQLExpression {
switch storage {
case .null:
@@ -343,7 +362,9 @@ extension DatabaseValue : SQLExpression {
}
}
extension DatabaseValue : CustomStringConvertible {
// CustomStringConvertible
extension DatabaseValue {
/// :nodoc:
public var description: String {
switch storage {
case .null:
+3
View File
@@ -32,6 +32,7 @@ public protocol DatabaseValueConvertible : SQLExpressible {
extension DatabaseValueConvertible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var sqlExpression: SQLExpression {
return databaseValue
}
@@ -60,6 +61,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Value? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
@@ -99,6 +101,7 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Value?? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
+10
View File
@@ -96,48 +96,58 @@ public final class AnyDatabaseWriter : DatabaseWriter {
// MARK: - Reading from Database
/// :nodoc:
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
/// :nodoc:
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
try base.readFromCurrentState(block)
}
// MARK: - Writing in Database
/// :nodoc:
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.write(block)
}
/// :nodoc:
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.unsafeReentrantWrite(block)
}
// MARK: - Functions
/// :nodoc:
public func add(function: DatabaseFunction) {
base.add(function: function)
}
/// :nodoc:
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
// MARK: - Collations
/// :nodoc:
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
/// :nodoc:
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
+80 -41
View File
@@ -22,6 +22,13 @@ public protocol Request {
///
/// - parameter db: A database connection.
func fetchCount(_ db: Database) throws -> Int
/// The database region that the request looks into.
///
/// This method has a default implementation.
///
/// - parameter db: A database connection.
func fetchedRegion(_ db: Database) throws -> DatabaseRegion
}
extension Request {
@@ -48,6 +55,14 @@ extension Request {
let (statement, adapter) = try prepare(db)
return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
}
/// The database region that the request looks into.
///
/// - parameter db: A database connection.
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
let (statement, _) = try prepare(db)
return statement.fetchedRegion
}
}
extension Request {
@@ -65,11 +80,9 @@ extension Request {
/// - parameter type: The fetched type T
/// - returns: A typed request bound to type T.
public func asRequest<T>(of type: T.Type) -> AnyTypedRequest<T> {
return AnyTypedRequest { try self.prepare($0) }
return AnyTypedRequest(self)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an adapted request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self> {
return AdaptedRequest(self, adapter)
@@ -78,6 +91,9 @@ extension Request {
/// An adapted request.
public struct AdaptedRequest<Base: Request> : Request {
private let base: Base
private let adapter: (Database) throws -> RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
@@ -85,10 +101,7 @@ public struct AdaptedRequest<Base: Request> : Request {
self.adapter = adapter
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let (statement, baseAdapter) = try base.prepare(db)
if let baseAdapter = baseAdapter {
@@ -98,15 +111,15 @@ public struct AdaptedRequest<Base: Request> : Request {
}
}
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
private let base: Base
private let adapter: (Database) throws -> RowAdapter
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
/// A type-erased Request.
@@ -114,26 +127,39 @@ public struct AdaptedRequest<Base: Request> : Request {
/// An instance of AnyRequest forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyRequest : Request {
private let base: Request
/// Creates a new request that wraps and forwards operations to `request`.
public init(_ request: Request) {
self._prepare = { try request.prepare($0) }
base = request
}
/// Creates a new request whose `prepare()` method wraps and forwards
/// operations the argument closure.
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
_prepare = prepare
struct PrepareRequest: Request {
let base: (Database) throws -> (SelectStatement, RowAdapter?)
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try base(db)
}
}
base = PrepareRequest(base: prepare)
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
return try base.prepare(db)
}
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
/// A Request built from raw SQL.
@@ -183,7 +209,9 @@ public struct SQLRequest : Request {
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
///
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement
switch cache {
case .none:
@@ -239,32 +267,31 @@ extension TypedRequest {
/// An adapted typed request.
public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
/// The type that can convert raw database rows to fetched values
public typealias RowDecoder = Base.RowDecoder
private let base: AdaptedRequest<Base>
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
adaptedRequest = AdaptedRequest(base, adapter)
self.base = AdaptedRequest(base, adapter)
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try adaptedRequest.prepare(db)
return try base.prepare(db)
}
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try adaptedRequest.fetchCount(db)
return try base.fetchCount(db)
}
private let adaptedRequest: AdaptedRequest<Base>
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
/// A type-erased TypedRequest.
@@ -274,27 +301,39 @@ public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
public struct AnyTypedRequest<T> : TypedRequest {
/// The type that can convert raw database rows to fetched values
public typealias RowDecoder = T
private let base: Request
/// Support for Request.asRequest(of:)
/// Not public because not type-safe.
fileprivate init(_ request: Request) {
base = request
}
/// Creates a new request that wraps and forwards operations to `request`.
public init<Request>(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder {
self._prepare = { try request.prepare($0) }
base = request
}
/// Creates a new request whose `prepare()` method wraps and forwards
/// operations the argument closure.
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
_prepare = prepare
base = AnyRequest(prepare)
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
return try base.prepare(db)
}
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try base.fetchedRegion(db)
}
}
extension TypedRequest where RowDecoder: RowConvertible {
+165 -59
View File
@@ -6,7 +6,7 @@ import Foundation
#endif
/// A database row.
public final class Row {
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible {
let impl: RowImpl
/// Unless we are producing a row array, we use a single row when iterating
@@ -131,6 +131,42 @@ extension Row {
// MARK: - Extracting Values
/// Returns true if and only if one column contains a non-null value, or if
/// the row was fetched with a row adapter that defines a scoped row that
/// contains a non-null value.
///
/// For example:
///
/// let row = try Row.fetchOne(db, "SELECT 'foo', 1")!
/// row.containsNonNullValue // true
///
/// let row = try Row.fetchOne(db, "SELECT NULL, NULL")!
/// row.containsNonNullValue // false
public var containsNonNullValue: Bool {
for i in (0..<count) {
if !hasNull(atIndex: i) { return true }
}
for name in scopeNames where scoped(on: name)!.containsNonNullValue {
return true
}
return false
}
/// Returns true if the row contains null at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// This method is equivalent to `row[index] == nil`, but may be preferred
/// in performance-critical code because it can avoid decoding database
/// values.
public func hasNull(atIndex index: Int) -> Bool {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.hasNull(atUncheckedIndex: index)
}
/// Returns Int64, Double, String, Data or nil, depending on the value
/// stored at the given index.
///
@@ -151,7 +187,7 @@ extension Row {
/// fail, a fatal error is raised.
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
return impl.value(atUncheckedIndex: index)
}
/// Returns the value at given index, converted to the requested type.
@@ -169,9 +205,9 @@ extension Row {
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
return impl.fastValue(atUncheckedIndex: index)
}
/// Returns the value at given index, converted to the requested type.
@@ -183,7 +219,7 @@ extension Row {
/// SQLite value can not be converted to `Value`.
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
return impl.value(atUncheckedIndex: index)
}
/// Returns the value at given index, converted to the requested type.
@@ -200,9 +236,9 @@ extension Row {
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
return impl.fastValue(atUncheckedIndex: index)
}
/// Returns Int64, Double, String, Data or nil, depending on the value
@@ -238,7 +274,7 @@ extension Row {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
return impl.value(atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
@@ -258,9 +294,9 @@ extension Row {
return nil
}
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
return impl.fastValue(atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
@@ -277,7 +313,7 @@ extension Row {
// Programmer error
fatalError("no such column: \(columnName)")
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
return impl.value(atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
@@ -295,13 +331,13 @@ extension Row {
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
guard let index = impl.index(ofColumn: columnName) else {
// Programmer error
// Programmer error
fatalError("no such column: \(columnName)")
}
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
return impl.fastValue(atUncheckedIndex: index)
}
/// Returns Int64, Double, String, NSData or nil, depending on the value
@@ -437,22 +473,36 @@ extension Row {
extension Row {
// MARK: - Helpers
@inline(__always)
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int32, in sqliteStatement: SQLiteStatement) -> Value? {
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
// MARK: - Extracting Records
/// Returns the record encoded in the given scope.
///
/// A fatal error is raised in the row was not fetched with a row adapter
/// that defines this scope.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
/// for more information.
public subscript<Record: RowConvertible>(_ scope: String) -> Record {
guard let scopedRow = scoped(on: scope) else {
// Programmer error
fatalError("no such scope: \(scope)")
}
return Record(row: scopedRow)
}
/// Returns the record encoded in the given scope, if and only if the scope
/// has been defined by a row adapter, and the scoped row contains a
/// non-null value. Otherwise, return nil.
///
/// This subscript is designed to handle left joined records.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
/// for more information.
public subscript<Record: RowConvertible>(_ scope: String) -> Record? {
guard let scopedRow = scoped(on: scope), scopedRow.containsNonNullValue else {
return nil
}
return Value.init(sqliteStatement: sqliteStatement, index: index)
}
@inline(__always)
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int32, in sqliteStatement: SQLiteStatement) -> Value {
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
// Programmer error
fatalError("could not convert database value NULL to \(Value.self)")
}
return Value.init(sqliteStatement: sqliteStatement, index: index)
return Record(row: scopedRow)
}
}
@@ -460,8 +510,12 @@ extension Row {
// MARK: - Scopes
/// Returns a scoped row, if the row was fetched along with a row adapter
/// that defines this scope.
var scopeNames: Set<String> {
return impl.scopeNames
}
/// Returns a scoped row, if the row was fetched with a row adapter that
/// defines this scope.
///
/// // Two adapters
/// let fooAdapter = ColumnMapping(["value": "foo"])
@@ -486,6 +540,12 @@ extension Row {
public func scoped(on name: String) -> Row? {
return impl.scoped(on: name)
}
/// Returns a copy of the row, without any scoped row (if the row was fetched
/// with a row adapter that defines scopes).
public var unscoped: Row {
return Row(impl: ArrayRowImpl(columns: map { ($0, $1) }))
}
}
/// A cursor of database rows. For example:
@@ -506,6 +566,7 @@ public final class RowCursor : Cursor {
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Row? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
@@ -725,7 +786,8 @@ extension Row {
}
}
extension Row : ExpressibleByDictionaryLiteral {
// ExpressibleByDictionaryLiteral
extension Row {
/// Creates a row initialized with elements. Column order is preserved, and
/// duplicated columns names are allowed.
@@ -738,17 +800,20 @@ extension Row : ExpressibleByDictionaryLiteral {
}
}
extension Row : Collection {
// RandomAccessCollection
extension Row {
// MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs
/// The index of the first (ColumnName, DatabaseValue) pair.
/// :nodoc:
public var startIndex: RowIndex {
return Index(0)
}
/// The "past-the-end" index, successor of the index of the last
/// (ColumnName, DatabaseValue) pair.
/// :nodoc:
public var endIndex: RowIndex {
return Index(count)
}
@@ -761,25 +826,14 @@ extension Row : Collection {
impl.columnName(atUncheckedIndex: index),
impl.databaseValue(atUncheckedIndex: index))
}
/// Returns the position immediately after `i`.
///
/// - Precondition: `(startIndex..<endIndex).contains(i)`
public func index(after i: RowIndex) -> RowIndex {
return RowIndex(i.index + 1)
}
/// Replaces `i` with its successor.
public func formIndex(after i: inout RowIndex) {
i = RowIndex(i.index + 1)
}
}
/// Row adopts Equatable.
extension Row : Equatable {
// Equatable
extension Row {
/// Returns true if and only if both rows have the same columns and values,
/// in the same order. Columns are compared in a case-sensitive way.
/// :nodoc:
public static func == (lhs: Row, rhs: Row) -> Bool {
if lhs === rhs {
return true
@@ -789,10 +843,7 @@ extension Row : Equatable {
return false
}
var liter = lhs.makeIterator()
var riter = rhs.makeIterator()
while let (lcol, lval) = liter.next(), let (rcol, rval) = riter.next() {
for ((lcol, lval), (rcol, rval)) in zip(lhs, rhs) {
guard lcol == rcol else {
return false
}
@@ -819,17 +870,19 @@ extension Row : Equatable {
}
}
/// Row adopts Hashable.
extension Row : Hashable {
// Hashable
extension Row {
/// The hash value
/// :nodoc:
public var hashValue: Int {
return columnNames.reduce(0) { (acc, column) in acc ^ column.hashValue } ^
databaseValues.reduce(0) { (acc, dbValue) in acc ^ dbValue.hashValue }
}
}
/// Row adopts CustomStringConvertible.
extension Row: CustomStringConvertible {
// CustomStringConvertible
extension Row {
/// :nodoc:
public var description: String {
return "<Row"
+ map { (column, dbValue) in
@@ -842,22 +895,38 @@ extension Row: CustomStringConvertible {
// MARK: - RowIndex
/// Indexes to (columnName, dbValue) pairs in a database row.
public struct RowIndex : Comparable {
/// Indexes to (ColumnName, DatabaseValue) pairs in a database row.
public struct RowIndex : Comparable, Strideable {
let index: Int
init(_ index: Int) { self.index = index }
/// Equality operator
}
// Comparable
extension RowIndex {
/// :nodoc:
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index == rhs.index
}
// Comparison operator
/// :nodoc:
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index < rhs.index
}
}
// Strideable: support for Row: RandomAccessCollection
extension RowIndex {
/// :nodoc:
public func distance(to other: RowIndex) -> Int {
return other.index - index
}
/// :nodoc:
public func advanced(by n: Int) -> RowIndex {
return RowIndex(index + n)
}
}
// MARK: - RowImpl
@@ -866,6 +935,9 @@ protocol RowImpl {
var count: Int { get }
var isFetched: Bool { get }
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value?
func hasNull(atUncheckedIndex index:Int) -> Bool
func dataNoCopy(atUncheckedIndex index:Int) -> Data?
func columnName(atUncheckedIndex index: Int) -> String
@@ -880,6 +952,27 @@ protocol RowImpl {
func copy(_ row: Row) -> Row
}
extension RowImpl {
func hasNull(atUncheckedIndex index:Int) -> Bool {
return databaseValue(atUncheckedIndex: index).isNull
}
func value<Value: DatabaseValueConvertible>(atUncheckedIndex index: Int) -> Value {
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func value<Value: DatabaseValueConvertible>(atUncheckedIndex index: Int) -> Value? {
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
}
/// See Row.init(dictionary:)
private struct ArrayRowImpl : RowImpl {
@@ -1008,6 +1101,11 @@ private struct StatementRowImpl : RowImpl {
return true
}
func hasNull(atUncheckedIndex index:Int) -> Bool {
// Avoid extracting values, because this modifies the statement.
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
return nil
@@ -1023,6 +1121,14 @@ private struct StatementRowImpl : RowImpl {
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
}
func columnName(atUncheckedIndex index: Int) -> String {
return statementRef.takeUnretainedValue().columnNames[index]
}
+129 -12
View File
@@ -1,8 +1,50 @@
import Foundation
/// Returns an array of row adapters that split a row according to the input
/// number of columns.
///
/// For example:
///
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
/// // <.><. . .><. .><. .>
/// let adapters = splittingRowAdapters([1, 3, 2])
/// let adapter = ScopeAdapter([
/// "a": adapters[0],
/// "b": adapters[1],
/// "c": adapters[2],
/// "d": adapters[3]])
/// let row = try Row.fetchOne(db, sql, adapter: adapter)
/// row.scoped(on: "a") // [1]
/// row.scoped(on: "b") // [2, 3, 4]
/// row.scoped(on: "c") // [5, 6]
/// row.scoped(on: "d") // [7, 8]
public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] {
guard !columnCounts.isEmpty else {
// Identity adapter
return [SuffixRowAdapter(fromIndex: 0)]
}
// [1, 3, 2] -> [0, 1, 4, 6]
let columnIndexes = columnCounts.reduce(into: [0]) { (acc, count) in
acc.append(acc.last! + count)
}
// [0, 1, 4, 6] -> [(0..<1), (1..<4), (4..<6)]
let rangeAdapters = zip(columnIndexes, columnIndexes.suffix(from: 1))
.map { RangeRowAdapter($0..<$1) }
// (6...)
let suffixAdapter = SuffixRowAdapter(fromIndex: columnIndexes.last!)
// [(0..<1), (1..<4), (4..<6), (6...)]
return rangeAdapters + [suffixAdapter]
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// LayoutedColumnMapping is a type that supports the RowAdapter protocol.
///
/// :nodoc:
public struct LayoutedColumnMapping {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -56,6 +98,8 @@ public struct LayoutedColumnMapping {
}
/// LayoutedColumnMapping adopts LayoutedRowAdapter
///
/// :nodoc:
extension LayoutedColumnMapping : LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -72,6 +116,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter {
}
}
/// :nodoc:
extension LayoutedColumnMapping : RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -91,6 +136,8 @@ extension LayoutedColumnMapping : RowLayout {
///
/// GRBD ships with a ready-made type that adopts this protocol:
/// LayoutedColumnMapping.
///
/// :nodoc:
public protocol LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -108,6 +155,8 @@ public protocol LayoutedRowAdapter {
///
/// RowLayout is a protocol that supports the RowAdapter protocol. It describes
/// a layout of a base row.
///
/// :nodoc:
public protocol RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -124,11 +173,15 @@ public protocol RowLayout {
extension SelectStatement : RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public var layoutColumns: [(Int, String)] {
return Array(columnNames.enumerated())
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutIndex(ofColumn name: String) -> Int? {
return index(ofColumn: name)
}
@@ -186,7 +239,7 @@ extension RowAdapter {
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter {
return ScopeAdapter(mainAdapter: self, scopes: scopes)
return ScopeAdapter(base: self, scopes: scopes)
}
}
@@ -196,6 +249,19 @@ extension RowAdapter {
}
}
/// EmptyRowAdapter is a row adapter that hides all columns.
public struct EmptyRowAdapter: RowAdapter {
/// Creates an EmptyRowAdapter
public init() { }
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: [])
}
}
/// ColumnMapping is a row adapter that maps column names.
///
/// let adapter = ColumnMapping(["foo": "bar"])
@@ -214,6 +280,8 @@ public struct ColumnMapping : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
let layoutColumns = try mapping
.map { (mappedColumn, baseColumn) -> (Int, String) in
@@ -250,6 +318,8 @@ public struct SuffixRowAdapter : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
}
@@ -279,6 +349,8 @@ public struct RangeRowAdapter : RowAdapter {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
}
@@ -308,29 +380,57 @@ public struct RangeRowAdapter : RowAdapter {
/// }
public struct ScopeAdapter : RowAdapter {
/// The main adapter
let mainAdapter: RowAdapter
/// The base adapter
let base: RowAdapter
/// The scope adapters
let scopes: [String: RowAdapter]
/// Creates a scoped adapter.
/// Creates an adapter that preserves row contents and add scoped rows.
///
/// For example:
///
/// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
/// row // [1, 2, 3]
/// row.scoped(on: "suffix") // [2, 3]
///
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public init(_ scopes: [String: RowAdapter]) {
self.mainAdapter = SuffixRowAdapter(fromIndex: 0) // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
self.scopes = scopes
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
}
init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) {
self.mainAdapter = mainAdapter
/// Creates an adapter based on the base adapter, and add scoped rows.
///
/// For example:
///
/// let baseAdapter = RangeRowAdapter(0..<1)
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
/// row // [1]
/// row.scoped(on: "initial") // [2, 3]
///
/// If the base adapter already defines scopes, the given scopes replace
/// eventual existing scopes with the same name.
///
/// This initializer is equivalent to `baseAdapter.addingScopes(scopes)`.
///
/// - parameter base: A dictionary that maps scope names to
/// row adapters.
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public init(base: RowAdapter, scopes: [String: RowAdapter]) {
self.base = base
self.scopes = scopes
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout)
let layoutedAdapter = try base.layoutedAdapter(from: layout)
var layoutedScopes = layoutedAdapter.scopes
for (name, adapter) in scopes {
try layoutedScopes[name] = adapter.layoutedAdapter(from: layout)
@@ -390,12 +490,29 @@ struct AdapterRowImpl : RowImpl {
return base.isFetched
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return base[mapping.baseColumnIndex(atMappingIndex: index)]
func hasNull(atUncheckedIndex index: Int) -> Bool {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.hasNull(atUncheckedIndex: mappedIndex)
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.databaseValue(atUncheckedIndex: mappedIndex)
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.fastValue(atUncheckedIndex: mappedIndex)
}
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.fastValue(atUncheckedIndex: mappedIndex)
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
return base.dataNoCopy(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
}
func columnName(atUncheckedIndex index: Int) -> String {
+10 -14
View File
@@ -16,14 +16,15 @@ import Dispatch
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
///
/// Later on, the queue can be shared by several databases with the method
/// allowing(databases:execute:). See SerializedDatabase.sync() for
/// an example.
/// inheritingAllowedDatabases(from:execute:). See SerializedDatabase.sync()
/// for an example.
///
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
var databaseObservationBroker: DatabaseObservationBroker?
private init(allowedDatabase database: Database) {
allowedDatabases = [database]
@@ -36,27 +37,22 @@ final class SchedulingWatchdog {
return queue
}
// Temporarily allows `databases` while executing `body`
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
func inheritingAllowedDatabases<T>(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T {
let backup = allowedDatabases
allowedDatabases.append(contentsOf: databases)
allowedDatabases.append(contentsOf: other.allowedDatabases)
defer { allowedDatabases = backup }
return try body()
}
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(allows(db), message, file: file, line: line)
}
static func allows(_ db: Database) -> Bool {
return current?.allows(db) ?? false
}
func allows(_ db: Database) -> Bool {
return allowedDatabases.contains { $0 === db }
GRDBPrecondition(current?.allows(db) ?? false, message, file: file, line: line)
}
static var current: SchedulingWatchdog? {
return DispatchQueue.getSpecific(key: specificKey)
}
func allows(_ db: Database) -> Bool {
return allowedDatabases.contains { $0 === db }
}
}
+18 -7
View File
@@ -81,7 +81,8 @@ final class SerializedDatabase {
guard let watchdog = SchedulingWatchdog.current else {
// Case 1
return try queue.sync {
try block(db)
defer { preconditionNoTransactionLeft(db) }
return try block(db)
}
}
@@ -90,8 +91,9 @@ final class SerializedDatabase {
// Case 3
return try queue.sync {
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
try block(db)
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
defer { preconditionNoTransactionLeft(db) }
return try block(db)
}
}
}
@@ -125,19 +127,22 @@ final class SerializedDatabase {
guard let watchdog = SchedulingWatchdog.current else {
// Case 1
return try queue.sync {
try block(db)
defer { preconditionNoTransactionLeft(db) }
return try block(db)
}
}
// Case 2
if watchdog.allows(db) {
defer { preconditionNoTransactionLeft(db) }
return try block(db)
}
// Case 3
return try queue.sync {
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
try block(db)
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
defer { preconditionNoTransactionLeft(db) }
return try block(db)
}
}
}
@@ -146,12 +151,13 @@ final class SerializedDatabase {
func async(_ block: @escaping (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoTransactionLeft(self.db)
}
}
/// Returns true if any only if the current dispatch queue is valid.
var onValidQueue: Bool {
return SchedulingWatchdog.allows(db)
return SchedulingWatchdog.current?.allows(db) ?? false
}
/// Executes the block in the current queue.
@@ -166,4 +172,9 @@ final class SerializedDatabase {
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
SchedulingWatchdog.preconditionValidQueue(db, message, file: file, line: line)
}
/// Fatal error if a transaction has been left opened.
func preconditionNoTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message, file: file, line: line)
}
}
+32 -85
View File
@@ -291,9 +291,17 @@ extension AuthorizedStatement {
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement, AuthorizedStatement {
/// Information about the table and columns read by a SelectStatement
public private(set) var selectionInfo: SelectionInfo
public final class SelectStatement : Statement {
/// :nodoc:
@available(*, deprecated, renamed:"DatabaseRegion")
public typealias SelectionInfo = DatabaseRegion
/// :nodoc:
@available(*, deprecated, renamed:"fetchedRegion")
public var selectionInfo: DatabaseRegion { return fetchedRegion }
/// The database region that the statement looks into.
public private(set) var fetchedRegion: DatabaseRegion
/// Creates a prepared statement.
///
@@ -314,7 +322,7 @@ public final class SelectStatement : Statement, AuthorizedStatement {
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
self.selectionInfo = SelectionInfo()
self.fetchedRegion = DatabaseRegion()
try super.init(
database: database,
statementStart: statementStart,
@@ -324,7 +332,7 @@ public final class SelectStatement : Statement, AuthorizedStatement {
GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
self.selectionInfo = authorizer.selectionInfo
self.fetchedRegion = authorizer.region
}
/// The number of columns in the resulting rows.
@@ -364,70 +372,11 @@ public final class SelectStatement : Statement, AuthorizedStatement {
prepare(withArguments: arguments)
reset()
}
/// Information about the table and columns read by a SelectStatement
public struct SelectionInfo : CustomStringConvertible {
/// Selection is unknown when a statement uses the COUNT function,
/// and SQLite version < 3.19:
///
/// `SELECT COUNT(*) FROM t1` -> unknown selection
private let isUnknown: Bool
/// `SELECT a, b FROM t1` -> ["t1": ["a", "b"]]
private var columns: [String: Set<String>] = [:]
/// `SELECT COUNT(*) FROM t1` -> ["t1"]
private var tables: Set<String> = []
/// The unknown selection
static let unknown = SelectionInfo(isUnknown: true)
mutating func insert(allColumnsOfTable table: String) {
tables.insert(table)
}
mutating func insert(column: String, ofTable table: String) {
columns[table, default: []].insert(column)
}
/// Returns true if isUnknown is true
func contains(anyColumnFrom table: String) -> Bool {
if isUnknown { return true }
return tables.contains(table) || columns.index(forKey: table) != nil
}
/// Returns true if isUnknown is true
func contains(anyColumnIn columns: Set<String>, from table: String) -> Bool {
if isUnknown { return true }
return tables.contains(table) || !(self.columns[table]?.isDisjoint(with: columns) ?? true)
}
init() {
self.init(isUnknown: false)
}
private init(isUnknown: Bool) {
self.isUnknown = isUnknown
}
public var description: String {
if isUnknown {
return "unknown"
}
return tables.union(columns.keys)
.sorted()
.map { table -> String in
if let columns = columns[table] {
return "\(table)(\(columns.sorted().joined(separator: ",")))"
} else {
return "\(table)(*)"
}
}
.joined(separator: ",")
}
}
}
// Hide AuthorizedStatement from Jazzy
extension SelectStatement: AuthorizedStatement { }
/// A cursor that iterates a database statement without producing any value.
/// For example:
///
@@ -447,6 +396,7 @@ public final class StatementCursor: Cursor {
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Void? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
@@ -475,7 +425,7 @@ public final class StatementCursor: Cursor {
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
/// }
public final class UpdateStatement : Statement, AuthorizedStatement {
public final class UpdateStatement : Statement {
enum TransactionEffect {
case beginTransaction
case commitTransaction
@@ -489,10 +439,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
/// is executed.
private(set) var invalidatesDatabaseSchemaCache: Bool
/// If true, the statement needs support from TruncateOptimizationBlocker
/// when executed
private(set) var needsTruncateOptimizationPreventionDuringExecution: Bool
private(set) var transactionEffect: TransactionEffect?
private(set) var databaseEventKinds: [DatabaseEventKind]
@@ -516,7 +462,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
authorizer: StatementCompilationAuthorizer) throws
{
self.invalidatesDatabaseSchemaCache = false
self.needsTruncateOptimizationPreventionDuringExecution = false
self.databaseEventKinds = []
try super.init(
database: database,
@@ -524,7 +469,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
statementEnd: statementEnd,
prepFlags: prepFlags)
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.needsTruncateOptimizationPreventionDuringExecution = authorizer.needsTruncateOptimizationPreventionDuringExecution
self.transactionEffect = authorizer.transactionEffect
self.databaseEventKinds = authorizer.databaseEventKinds
}
@@ -539,10 +483,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
reset()
database.updateStatementWillExecute(self)
if needsTruncateOptimizationPreventionDuringExecution {
database.authorizer = TruncateOptimizationBlocker()
}
while true {
switch sqlite3_step(sqliteStatement) {
case SQLITE_ROW:
@@ -565,12 +505,10 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
continue
case SQLITE_DONE:
database.authorizer = nil
try database.updateStatementDidExecute(self)
return
case let code:
database.authorizer = nil
try database.updateStatementDidFail(self)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
}
@@ -578,6 +516,9 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
}
}
// Hide AuthorizedStatement from Jazzy
extension UpdateStatement: AuthorizedStatement { }
// MARK: - StatementArguments
@@ -652,7 +593,7 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
/// let row = try Row.fetchOne(db, sql, arguments: [1, 2, "bar"] + ["foo": "foo"])!
/// print(row)
/// // Prints <Row two:2 foo:"foo" one:1 foo2:"foo" bar:"bar">
public struct StatementArguments {
public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
var values: [DatabaseValue] = []
var namedValues: [String: DatabaseValue] = [:]
@@ -938,7 +879,8 @@ public struct StatementArguments {
}
}
extension StatementArguments : ExpressibleByArrayLiteral {
// ExpressibleByArrayLiteral
extension StatementArguments {
/// Returns a StatementArguments from an array literal:
///
/// db.selectRows("SELECT ...", arguments: ["Arthur", 41])
@@ -947,7 +889,8 @@ extension StatementArguments : ExpressibleByArrayLiteral {
}
}
extension StatementArguments : ExpressibleByDictionaryLiteral {
// ExpressibleByDictionaryLiteral
extension StatementArguments {
/// Returns a StatementArguments from a dictionary literal:
///
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
@@ -956,7 +899,9 @@ extension StatementArguments : ExpressibleByDictionaryLiteral {
}
}
extension StatementArguments : CustomStringConvertible {
// CustomStringConvertible
extension StatementArguments {
/// :nodoc:
public var description: String {
let valuesDescriptions = values.map { $0.description }
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
@@ -966,7 +911,9 @@ extension StatementArguments : CustomStringConvertible {
}
}
extension StatementArguments : Equatable {
// Equatable
extension StatementArguments {
/// :nodoc:
public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool {
if lhs.values != rhs.values { return false }
if lhs.namedValues != rhs.namedValues { return false }
+15 -16
View File
@@ -18,7 +18,7 @@ protocol StatementAuthorizer : class {
/// A class that gathers information about one statement during its compilation.
final class StatementCompilationAuthorizer : StatementAuthorizer {
/// What this statements reads
var selectionInfo = SelectStatement.SelectionInfo()
var region = DatabaseRegion()
/// What this statements writes
var databaseEventKinds: [DatabaseEventKind] = []
@@ -32,9 +32,6 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
/// savepoint statement.
var transactionEffect: UpdateStatement.TransactionEffect?
/// True if statement may trigger the truncate optimization
var needsTruncateOptimizationPreventionDuringExecution = false
private var isDropStatement = false
func authorize(
@@ -69,10 +66,10 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
selectionInfo.insert(allColumnsOfTable: tableName)
region.formUnion(DatabaseRegion(table: tableName))
} else {
// SELECT column FROM table
selectionInfo.insert(column: columnName, ofTable: tableName)
region.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
}
return SQLITE_OK
@@ -84,12 +81,17 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
case SQLITE_DELETE:
if isDropStatement { return SQLITE_OK }
guard let cString1 = cString1 else { return SQLITE_OK }
// Deletions from sqlite_master and sqlite_temp_master are not like
// other deletions: the update hook does not notify them, and they
// are prevented when the truncate optimization is disabled.
// Let's authorize such deletions by returning SQLITE_OK:
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
// Now we prevent the truncate optimization so that transaction
// observers are notified of individual row deletions.
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
// Prevent the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// See also TruncateOptimizationBlocker
needsTruncateOptimizationPreventionDuringExecution = true
return SQLITE_IGNORE
case SQLITE_UPDATE:
@@ -129,11 +131,11 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
// Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not
// trigger any authorization callback that tells about the
// counted table: any use of the COUNT function makes the
// selection undetermined.
// region undetermined (the full database).
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
guard let cString2 = cString2 else { return SQLITE_OK }
if sqlite3_stricmp(cString2, "COUNT") == 0 {
selectionInfo = .unknown
region = .fullDatabase
}
return SQLITE_OK
@@ -159,11 +161,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
/// which makes transaction observers unable to observe individual deletions
/// when user runs `DELETE FROM t` statements.
//
/// Warning: to perform well, this authorizer requires that:
//
/// - It is used during statement execution, not during statement compilation.
/// - Statement compilation was authorized with a StatementCompilationAuthorizer
/// that has set its needsTruncateOptimizationPreventionDuringExecution flag.
/// Warning: to perform well, this authorizer must be used during statement
/// execution, not during statement compilation.
final class TruncateOptimizationBlocker : StatementAuthorizer {
func authorize(
_ actionCode: Int32,
@@ -50,6 +50,27 @@ public protocol StatementColumnConvertible {
init(sqliteStatement: SQLiteStatement, index: Int32)
}
extension StatementColumnConvertible {
@inline(__always)
static func losslessConvert(sqliteStatement: SQLiteStatement, index: Int32) -> Self? {
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
return nil
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
@inline(__always)
static func losslessConvert(sqliteStatement: SQLiteStatement, index: Int32) -> Self {
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
// Programmer error
fatalError("could not convert database value NULL to \(Self.self)")
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
}
/// A cursor of database values extracted from a single column.
/// For example:
///
@@ -73,6 +94,7 @@ public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColum
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Value? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
@@ -118,6 +140,7 @@ public final class NullableColumnCursor<Value: DatabaseValueConvertible & Statem
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Value?? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
+388 -124
View File
@@ -51,11 +51,7 @@ extension Database {
// Ignore individual changes and transaction rollbacks
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
func databaseDidChange(with event: DatabaseEvent) { }
func databaseWillCommit() throws { }
func databaseDidRollback(_ db: Database) { }
// On commit, run closure
@@ -80,6 +76,8 @@ extension Database {
}
}
// MARK: - DatabaseObservationBroker
/// This class provides support for transaction observers.
///
/// Let's have a detailed look at how a transaction observer is notified:
@@ -163,74 +161,138 @@ extension Database {
/// After the statement *has been executed*, the broker calls
/// observer.databaseDidCommit().
class DatabaseObservationBroker {
unowned var database: Database
var savepointStack = SavepointStack()
var transactionState: TransactionState = .none
var transactionObservations = [TransactionObservation]()
var activeTransactionObservations = [TransactionObservation]()
private unowned var database: Database
private var savepointStack = SavepointStack()
private var transactionState: TransactionState = .none
private var transactionObservations: [TransactionObservation] = []
private var statementObservations: [StatementObservation] = [] {
didSet { observesDatabaseChanges = !statementObservations.isEmpty }
}
private var observesDatabaseChanges: Bool = false {
didSet {
if observesDatabaseChanges == oldValue { return }
if observesDatabaseChanges {
installUpdateHook()
} else {
uninstallUpdateHook()
}
}
}
init(_ database: Database) {
self.database = database
}
func setup() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
do {
try broker.databaseWillCommit()
broker.transactionState = .commit
// Next step: updateStatementDidExecute()
return 0
} catch {
broker.transactionState = .cancelledCommit(error)
// Next step: sqlite3_rollback_hook callback
return 1
}
}, brokerPointer)
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionState {
case .cancelledCommit:
// Next step: updateStatementDidFail()
break
default:
broker.transactionState = .rollback
// Next step: updateStatementDidExecute()
}
}, brokerPointer)
}
// MARK: - Transaction observers
func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent) {
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
if transactionObservations.count == 1 {
installUpdateHook()
}
}
func remove(transactionObserver: TransactionObserver) {
transactionObservations.removeFirst { $0.isWrapping(transactionObserver) }
if transactionObservations.isEmpty {
uninstallUpdateHook()
}
func disableUntilNextTransaction(transactionObserver: TransactionObserver) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver)}) {
observation.isDisabled = true
statementObservations.removeFirst { $0.0 === observation }
}
}
// MARK: - Statement execution
func updateStatementWillExecute(_ statement: UpdateStatement) {
// Activate the transaction observers that are interested in the actions
// performed by the statement.
let databaseEventKinds = statement.databaseEventKinds
activeTransactionObservations = transactionObservations.filter { observer in
return databaseEventKinds.contains(where: observer.observes)
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current:
SchedulingWatchdog.current!.databaseObservationBroker = self
// Fill statementObservations with observations that are interested in
// the kind of events performed by the statement.
//
// Those statementObservations will be notified of individual changes
// in databaseWillChange() and databaseDidChange().
let eventKinds = statement.databaseEventKinds
// If any observer observes row deletions, we'll have to disable
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// so that observers are notified.
var observesRowDeletion = false
switch eventKinds.count {
case 0:
// Statement has no effect on any database table.
//
// For example: PRAGMA foreign_keys = ON
statementObservations = []
case 1:
// We'll execute a simple statement without any side effect.
// Eventual database events will thus all have the same kind. All
// detabase events can be notified to interested observations.
//
// For example, if one observes all deletions in the table T, then
// all individual deletions of DELETE FROM T are notified:
let eventKind = eventKinds[0]
statementObservations = transactionObservations.flatMap { observation in
guard observation.observes(eventsOfKind: eventKind) else {
// observation is not interested
return nil
}
if case .delete = eventKind {
observesRowDeletion = true
}
// observation will be notified of all individual events
return (observation, DatabaseEventPredicate.true)
}
default:
// We'll execute a complex statement with side effects performed by
// an SQL trigger or a foreign key action. Eventual database events
// may not all have the same kind: we need to filter them before
// notifying interested observations.
//
// For example, if DELETE FROM T1 generates deletions in T1 and T2
// by the mean of a foreign key action, then when one only observes
// deletions in T1, one must not be notified of deletions in T2:
statementObservations = transactionObservations.flatMap { observation in
let observedKinds = eventKinds.filter(observation.observes)
if observedKinds.isEmpty {
// observation is not interested
return nil
}
for eventKind in observedKinds {
if case .delete = eventKind {
observesRowDeletion = true
break
}
}
// observation will only be notified of individual events that
// match one of the observed kinds.
return (observation, DatabaseEventPredicate.matching(observedKinds))
}
}
if observesRowDeletion {
database.authorizer = TruncateOptimizationBlocker()
} else {
database.authorizer = nil
}
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Wait for next statement
activeTransactionObservations = []
// Undo updateStatementWillExecute
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Reset transactionState before databaseDidRollback eventually
// executes other statements.
let transactionState = self.transactionState
@@ -251,9 +313,11 @@ class DatabaseObservationBroker {
}
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
// Wait for next statement
activeTransactionObservations = []
// Undo updateStatementWillExecute
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Has statement any effect on transaction/savepoints?
if let transactionEffect = statement.transactionEffect {
switch transactionEffect {
@@ -267,7 +331,7 @@ class DatabaseObservationBroker {
// BEGIN DEFERRED TRANSACTION; COMMIT
//
// This special case has a dedicated handling:
return try emptyDeferredTransactionDidCommit()
return try databaseDidCommitEmptyDeferredTransaction()
}
case .rollbackTransaction:
@@ -287,7 +351,7 @@ class DatabaseObservationBroker {
// SAVEPOINT foo; RELEASE SAVEPOINT foo
//
// This special case has a dedicated handling:
return try emptyDeferredTransactionDidCommit()
return try databaseDidCommitEmptyDeferredTransaction()
}
if savepointStack.isEmpty {
@@ -319,30 +383,41 @@ class DatabaseObservationBroker {
private func databaseWillChange(with event: DatabasePreUpdateEvent) {
if savepointStack.isEmpty {
// Notify now
for observation in activeTransactionObservations {
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
observation.databaseWillChange(with: event)
}
} else {
// Buffer
savepointStack.eventsBuffer.append((event: event.copy(), observations: activeTransactionObservations))
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
}
}
#endif
// Called from sqlite3_update_hook
private func databaseDidChange(with event: DatabaseEvent) {
// We're about to call the databaseDidChange(with:) method of
// transaction observers. In this method, observers may disable
// themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current:
assert(SchedulingWatchdog.current?.databaseObservationBroker != nil)
if savepointStack.isEmpty {
// Notify now
for observation in activeTransactionObservations {
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
observation.databaseDidChange(with: event)
}
} else {
// Buffer
savepointStack.eventsBuffer.append((event: event.copy(), observations: activeTransactionObservations))
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
}
}
// Called from sqlite3_commit_hook and emptyDeferredTransactionDidCommit()
// MARK: - End of transaction
// Called from sqlite3_commit_hook and databaseDidCommitEmptyDeferredTransaction()
private func databaseWillCommit() throws {
notifyBufferedEvents()
for observation in transactionObservations {
@@ -350,17 +425,6 @@ class DatabaseObservationBroker {
}
}
private func notifyBufferedEvents() {
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
for (event, observations) in eventsBuffer {
for observation in observations {
event.send(to: observation)
}
}
}
// Called from updateStatementDidExecute
private func databaseDidCommit() {
savepointStack.clear()
@@ -368,11 +432,11 @@ class DatabaseObservationBroker {
for observation in transactionObservations {
observation.databaseDidCommit(database)
}
cleanupTransactionObservations()
databaseDidEndTransaction()
}
// Called from updateStatementDidExecute
private func emptyDeferredTransactionDidCommit() throws {
private func databaseDidCommitEmptyDeferredTransaction() throws {
// A statement that ends a transaction has been executed. But for
// SQLite, no transaction at all has started, and sqlite3_commit_hook
// was not triggered:
@@ -404,6 +468,7 @@ class DatabaseObservationBroker {
// even if we actually execute an empty deferred transaction.
//
// For better or for worse, let's simulate a transaction:
do {
try databaseWillCommit()
databaseDidCommit()
@@ -422,11 +487,115 @@ class DatabaseObservationBroker {
observation.databaseDidRollback(database)
}
}
cleanupTransactionObservations()
databaseDidEndTransaction()
}
/// Remove transaction observers that have stopped observing transaction,
/// and uninstall SQLite update hooks if there is no remaining observers.
private func databaseDidEndTransaction() {
transactionObservations = transactionObservations.filter { $0.isObserving }
// Undo disableUntilNextTransaction(transactionObserver:)
for observation in transactionObservations {
observation.isDisabled = false
}
}
private func notifyBufferedEvents() {
// We're about to call the databaseDidChange(with:) method of
// transaction observers. In this method, observers may disable
// themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current.
//
// Normally, notifyBufferedEvents() is called as part of statement
// execution, and the current broker has been set in
// updateStatementWillExecute(). An assertion should be enough:
//
// assert(SchedulingWatchdog.current?.databaseObservationBroker != nil)
//
// But we have to deal with a particular case:
//
// let journalMode = String.fetchOne(db, "PRAGMA journal_mode = wal")
//
// It runs a SelectStatement, not an UpdateStatement. But this not why
// this case is particular. What is unexpected is that it triggers
// the commit hook when the "PRAGMA journal_mode = wal" statement is
// finalized, long after it has executed:
//
// 1. Statement.deinit()
// 2. sqlite3_finalize()
// 3. commit hook
// 4. DatabaseObservationBroker.databaseWillCommit()
// 5. DatabaseObservationBroker.notifyBufferedEvents()
//
// I don't know if this behavior is something that can be relied
// upon. One would naively expect, for example, that changing the
// journal mode would trigger the commit hook in sqlite3_step(),
// not in sqlite3_finalize().
//
// Anyway: in this scenario, updateStatementWillExecute() has not been
// called, and the current broker is nil.
//
// Let's not try to outsmart SQLite, and build a complex state machine.
// Instead, let's just make sure that the current broker is set to self
// when this method is called.
let watchDog = SchedulingWatchdog.current!
watchDog.databaseObservationBroker = self
defer {
watchDog.databaseObservationBroker = nil
}
// Now we can safely notify:
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
for (event, statementObservations) in eventsBuffer {
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
event.send(to: observation)
}
}
}
// MARK: - SQLite hooks
func installCommitAndRollbackHooks() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
do {
try broker.databaseWillCommit()
broker.transactionState = .commit
// Next step: updateStatementDidExecute()
return 0
} catch {
broker.transactionState = .cancelledCommit(error)
// Next step: sqlite3_rollback_hook callback
return 1
}
}, brokerPointer)
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionState {
case .cancelledCommit:
// Next step: updateStatementDidFail()
break
default:
broker.transactionState = .rollback
// Next step: updateStatementDidExecute()
}
}, brokerPointer)
}
private func installUpdateHook() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_update_hook(database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
broker.databaseDidChange(with: DatabaseEvent(
@@ -457,16 +626,7 @@ class DatabaseObservationBroker {
#endif
}
/// Remove transaction observers that have stopped observing transaction,
/// and uninstall SQLite update hooks if there is no remaining observers.
private func cleanupTransactionObservations() {
transactionObservations = transactionObservations.filter { $0.isObserving }
if transactionObservations.isEmpty {
uninstallUpdateHook()
}
}
/// The states that keep track of transaction completions
/// The various states of SQLite transactions
enum TransactionState {
case none
case commit
@@ -475,6 +635,8 @@ class DatabaseObservationBroker {
}
}
// MARK: - TransactionObserver
/// A transaction observer is notified of all changes and transactions committed
/// or rollbacked on a database.
///
@@ -487,13 +649,18 @@ public protocol TransactionObserver : class {
/// Notifies a database change (insert, update, or delete).
///
/// The change is pending until the end of the current transaction, notified
/// to databaseWillCommit, databaseDidCommit and databaseDidRollback.
/// The change is pending until the current transaction ends. See
/// databaseWillCommit, databaseDidCommit and databaseDidRollback.
///
/// This method is called on the database queue.
/// This method is called in a protected dispatch queue, serialized will all
/// database updates.
///
/// The event is only valid for the duration of this method call. If you
/// need to keep it longer, store a copy of its properties.
/// need to keep it longer, store a copy: `event.copy()`
///
/// The observer has an opportunity to stop receiving further change events
/// from the current transaction by calling the
/// stopObservingDatabaseChangesUntilNextTransaction() method.
///
/// - warning: this method must not change the database.
func databaseDidChange(with event: DatabaseEvent)
@@ -530,34 +697,80 @@ public protocol TransactionObserver : class {
/// This callback is mostly useful for calculating detailed change
/// information for a row, and provides the initial / final values.
///
/// This method is called on the database queue.
/// This method is called in a protected dispatch queue, serialized will all
/// database updates.
///
/// The event is only valid for the duration of this method call. If you
/// need to keep it longer, store a copy of its properties.
/// need to keep it longer, store a copy: `event.copy()`
///
/// - warning: this method must not change the database.
///
/// Availability Info:
/// **Availability Info**
///
/// Requires SQLite 3.13.0 +
/// Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK
/// Requires SQLite 3.13.0 +
/// Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK
///
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// copy using GRDBCustomSQLite. See the README.md in /SQLiteCustom/
///
/// The databaseDidChangeWithEvent callback is always available,
/// and may provide most/all of what you need.
/// (For example, FetchedRecordsController is built without using
/// this functionality.)
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
///
/// The databaseDidChangeWithEvent callback is always available,
/// and may provide most/all of what you need.
/// (For example, FetchedRecordsController is built without databaseWillChange)
func databaseWillChange(with event: DatabasePreUpdateEvent)
#endif
}
extension TransactionObserver {
/// Default implementation does nothing
public func databaseWillCommit() throws {
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Default implementation does nothing
public func databaseWillChange(with event: DatabasePreUpdateEvent) {
}
#endif
/// After this method has been called, the `databaseDidChange(with:)`
/// method won't be called until the next transaction.
///
/// For example:
///
/// class PlayerObserver: TransactionObserver {
/// var playersTableWasModified = false
///
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
/// return eventKind.tableName == "players"
/// }
///
/// func databaseDidChange(with event: DatabaseEvent) {
/// playersTableWasModified = true
///
/// // It is pointless to keep on tracking further changes:
/// stopObservingDatabaseChangesUntilNextTransaction()
/// }
/// }
///
/// - precondition: This method must be called from `databaseDidChange(with:)`.
public func stopObservingDatabaseChangesUntilNextTransaction() {
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
fatalError("stopObservingDatabaseChangesUntilNextTransaction must be called from the databaseDidChange method")
}
broker.disableUntilNextTransaction(transactionObserver: self)
}
}
// MARK: - TransactionObservation
/// This class manages the observation extent of a transaction observer
final class TransactionObservation {
let extent: Database.TransactionObservationExtent
// A disabled observation is not interested in individual database changes.
// It is still interested in transactions commits & rollbacks.
var isDisabled: Bool = false
private weak var weakObserver: TransactionObserver?
private var strongObserver: TransactionObserver?
private var observer: TransactionObserver? { return strongObserver ?? weakObserver }
@@ -584,10 +797,19 @@ final class TransactionObservation {
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
if isDisabled { return false }
return observer?.observes(eventsOfKind: eventKind) ?? false
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
if isDisabled { return }
observer?.databaseWillChange(with: event)
}
#endif
func databaseDidChange(with event: DatabaseEvent) {
if isDisabled { return }
observer?.databaseDidChange(with: event)
}
@@ -601,7 +823,7 @@ final class TransactionObservation {
observer?.databaseDidCommit(db)
case .nextTransaction:
if let observer = self.observer {
// Observer most not get any further notification.
// Observer must not get any further notification.
// So we "forget" the observer before its `databaseDidCommit`
// implementation eventually triggers another database change.
strongObserver = nil
@@ -616,7 +838,7 @@ final class TransactionObservation {
observer?.databaseDidRollback(db)
case .nextTransaction:
if let observer = self.observer {
// Observer most not get any further notification.
// Observer must not get any further notification.
// So we "forget" the observer before its `databaseDidRollback`
// implementation eventually triggers another database change.
strongObserver = nil
@@ -624,16 +846,14 @@ final class TransactionObservation {
}
}
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
observer?.databaseWillChange(with: event)
}
#endif
}
/// A kind of database event. See Database.add(transactionObserver:)
/// and DatabaseWriter.add(transactionObserver:).
typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate)
// MARK: - Database events
/// A kind of database event. See the TransactionObserver protocol for
/// more information.
public enum DatabaseEventKind {
/// The insertion of a row in a database table
case insert(tableName: String)
@@ -644,19 +864,22 @@ public enum DatabaseEventKind {
/// The update of a set of columns in a database table
case update(tableName: String, columnNames: Set<String>)
/// Returns whether event has any impact on tables and columns described
/// by selectionInfo.
public func impacts(_ selectionInfo: SelectStatement.SelectionInfo) -> Bool {
var modifiedRegion: DatabaseRegion {
switch self {
case .delete(let tableName):
return selectionInfo.contains(anyColumnFrom: tableName)
return DatabaseRegion(table: tableName)
case .insert(let tableName):
return selectionInfo.contains(anyColumnFrom: tableName)
return DatabaseRegion(table: tableName)
case .update(let tableName, let updatedColumnNames):
return selectionInfo.contains(anyColumnIn: updatedColumnNames, from: tableName)
return DatabaseRegion(table: tableName, columns: updatedColumnNames)
}
}
/// :nodoc:
@available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
public func impacts(_ region: DatabaseRegion) -> Bool {
return region.isModified(byEventsOfKind: self)
}
}
extension DatabaseEventKind {
@@ -672,6 +895,7 @@ extension DatabaseEventKind {
protocol DatabaseEventProtocol {
func send(to observer: TransactionObservation)
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool
}
/// A database event, notified to TransactionObserver.
@@ -689,6 +913,8 @@ public struct DatabaseEvent {
case update = 23
}
private let impl: DatabaseEventImpl
/// The event kind
public let kind: Kind
@@ -722,14 +948,22 @@ public struct DatabaseEvent {
init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
self.init(kind: kind, rowID: rowID, impl: MetalDatabaseEventImpl(databaseNameCString: databaseNameCString, tableNameCString: tableNameCString))
}
private let impl: DatabaseEventImpl
}
extension DatabaseEvent : DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseDidChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
}
/// Protocol for internal implementation of DatabaseEvent
@@ -883,6 +1117,16 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
func send(to observer: TransactionObservation) {
observer.databaseWillChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
}
/// Protocol for internal implementation of DatabaseEvent
@@ -1008,6 +1252,25 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
#endif
// A predicate that filters database events
enum DatabaseEventPredicate {
// Yes filter
case `true`
// Only events that match one of those kinds
case matching([DatabaseEventKind])
func evaluate(_ event: DatabaseEventProtocol) -> Bool {
switch self {
case .true:
return true
case .matching(let kinds):
return kinds.contains { event.matchesKind($0) }
}
}
}
// MARK: - SavepointStack
/// The SQLite savepoint stack is described at
/// https://www.sqlite.org/lang_savepoint.html
///
@@ -1018,8 +1281,8 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
/// notifying transaction observers of database events that could be
/// rollbacked.
class SavepointStack {
/// The buffered events. See Database.didChange(with:)
var eventsBuffer: [(event: DatabaseEventProtocol, observations: [TransactionObservation])] = []
/// The buffered events (see DatabaseObservationBroker.databaseDidChange(with:))
var eventsBuffer: [(event: DatabaseEventProtocol, statementObservations: [StatementObservation])] = []
/// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array).
/// Indexes let us drop rollbacked events from the event buffer.
@@ -1072,3 +1335,4 @@ class SavepointStack {
}
}
}
+1
View File
@@ -269,6 +269,7 @@ public final class FTS4ColumnDefinition {
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
///
/// - returns: Self so that you can further refine the column definition.
/// :nodoc:
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
+13
View File
@@ -44,6 +44,19 @@
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
/// Creates a pattern that matches a contiguous string prefix; returns
/// nil if no pattern could be built.
///
/// FTS5Pattern(matchingPrefixPhrase: "") // nil
/// FTS5Pattern(matchingPrefixPhrase: "foo bar") // ^"foo bar"
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPrefixPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
}
init(rawPattern: String, allowedColumns: [String] = []) throws {
// Correctness above all: use SQLite to validate the pattern.
//
+2
View File
@@ -85,6 +85,8 @@ public struct DatabaseMigrator {
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
///
/// :nodoc:
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
+21 -4
View File
@@ -1,23 +1,40 @@
/// A column in the database
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct Column {
public struct Column : SQLExpression {
/// The hidden rowID column
public static let rowID = Column("rowid")
/// The name of the column
public let name: String
private var qualifier: SQLTableQualifier?
/// Creates a column given its name.
public init(_ name: String) {
self.name = name
}
}
extension Column : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
if let qualifierName = qualifier?.name {
return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier
}
return name.quotedDatabaseIdentifier
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func qualified(by qualifier: SQLTableQualifier) -> Column {
if self.qualifier != nil {
// Never requalify
return self
}
var column = self
column.qualifier = qualifier
return column
}
}
+191 -7
View File
@@ -16,6 +16,8 @@ extension QueryInterfaceRequest : TypedRequest {
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
///
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try query.prepare(db)
}
@@ -23,9 +25,18 @@ extension QueryInterfaceRequest : TypedRequest {
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
///
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
return try query.fetchCount(db)
}
/// The database region that the request looks into.
///
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try query.fetchedRegion(db)
}
}
extension QueryInterfaceRequest {
@@ -104,13 +115,13 @@ extension QueryInterfaceRequest {
/// var request = Player.all()
/// request = request.filter(Column("email") == "arthur@example.com")
public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
var query = self.query
if let whereExpression = query.whereExpression {
query.whereExpression = whereExpression && predicate.sqlExpression
} else {
query.whereExpression = predicate.sqlExpression
}
return QueryInterfaceRequest(query: query)
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
if let expression = expression {
return expression && predicate.sqlExpression
} else {
return predicate.sqlExpression
}
})
}
/// A new QueryInterfaceRequest with the provided *predicate* added to the
@@ -235,6 +246,125 @@ extension QueryInterfaceRequest {
}
}
extension QueryInterfaceRequest where T: TableMapping {
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM players WHERE id = 1
/// var request = Player.all()
/// request = request.filter(key: 1)
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T> {
guard let key = key else {
return T.none()
}
return filter(keys: [key])
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
/// var request = Player.all()
/// request = request.filter(keys: [1, 2, 3])
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible {
let keys = Array(keys)
let makePredicate: (Column) -> SQLExpression
switch keys.count {
case 0:
return T.none()
case 1:
makePredicate = { $0 == keys[0] }
default:
makePredicate = { keys.contains($0) }
}
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
let primaryKey = try db.primaryKey(T.databaseTableName)
GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)")
let keysPredicate = makePredicate(Column(primaryKey.columns[0]))
if let expression = expression {
return expression && keysPredicate
} else {
return keysPredicate
}
})
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
/// var request = Player.all()
/// request = request.filter(key: ["personId": 1, "countryCode": "FR"])
///
/// When executed, this request raises a fatal error if there is no unique
/// index on the key columns.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T> {
guard let key = key else {
return T.none()
}
return filter(keys: [key])
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
///
/// When executed, this request raises a fatal error if there is no unique
/// index on the key columns.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T> {
guard !keys.isEmpty else {
return T.none()
}
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
let keyPredicates: [SQLExpression] = try keys.map { key in
// Prevent filter(db, keys: [[:]])
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
// ("foo", "bar") is not a unique key (primary key or columns of a
// unique index)
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else {
fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))")
}
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
let columnPredicates: [SQLExpression] = key
// Sort key columns in the same order as the unique index
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
.map { (column, value) in Column(column) == value }
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
}
let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keyPredicates is not empty
if let expression = expression {
return expression && keysPredicate
} else {
return keysPredicate
}
})
}
}
extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
// MARK: Deleting
@@ -308,6 +438,60 @@ extension TableMapping {
return all().filter(predicate)
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM players WHERE id = 1
/// let request = Player.filter(key: 1)
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self> {
return all().filter(key: key)
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
/// let request = Player.filter(keys: [1, 2, 3])
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
return all().filter(keys: keys)
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
/// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"])
///
/// When executed, this request raises a fatal error if there is no unique
/// index on the key columns.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self> {
return all().filter(key: key)
}
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
///
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
///
/// When executed, this request raises a fatal error if there is no unique
/// index on the key columns.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableMapping.databaseSelection` property, or
/// for individual requests with the `TableMapping.select` method.
public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self> {
return all().filter(keys: keys)
}
/// Creates a QueryInterfaceRequest with the provided *predicate*.
///
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
@@ -1,10 +1,28 @@
// MARK: - QueryInterfaceSelectQueryDefinition
struct DatabasePromise<T> {
let resolve: (Database) throws -> T
init(value: T) {
self.resolve = { _ in value }
}
init(_ resolve: @escaping (Database) throws -> T) {
self.resolve = resolve
}
func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise {
return DatabasePromise { db in
try transform(db, self.resolve(db))
}
}
}
struct QueryInterfaceSelectQueryDefinition {
var selection: [SQLSelectable]
var isDistinct: Bool
var source: SQLSource?
var whereExpression: SQLExpression?
var wherePromise: DatabasePromise<SQLExpression?>
var groupByExpressions: [SQLExpression]
var orderings: [SQLOrderingTerm]
var isReversed: Bool
@@ -25,7 +43,7 @@ struct QueryInterfaceSelectQueryDefinition {
self.selection = selection
self.isDistinct = isDistinct
self.source = source
self.whereExpression = whereExpression
self.wherePromise = DatabasePromise(value: whereExpression)
self.groupByExpressions = groupByExpressions
self.orderings = orderings
self.isReversed = isReversed
@@ -33,7 +51,13 @@ struct QueryInterfaceSelectQueryDefinition {
self.limit = limit
}
func sql(_ arguments: inout StatementArguments?) -> String {
func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceSelectQueryDefinition {
var query = self
query.wherePromise = query.wherePromise.map(transform)
return query
}
func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
var sql = "SELECT"
if isDistinct {
@@ -44,10 +68,10 @@ struct QueryInterfaceSelectQueryDefinition {
sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ")
if let source = source {
sql += " FROM " + source.sourceSQL(&arguments)
sql += try " FROM " + source.sourceSQL(db, &arguments)
}
if let whereExpression = whereExpression {
if let whereExpression = try wherePromise.resolve(db) {
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
}
@@ -86,10 +110,10 @@ struct QueryInterfaceSelectQueryDefinition {
var arguments: StatementArguments? = StatementArguments()
if let source = source {
sql += " FROM " + source.sourceSQL(&arguments)
sql += try " FROM " + source.sourceSQL(db, &arguments)
}
if let whereExpression = whereExpression {
if let whereExpression = try wherePromise.resolve(db) {
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
}
@@ -147,7 +171,7 @@ struct QueryInterfaceSelectQueryDefinition {
extension QueryInterfaceSelectQueryDefinition : Request {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
var arguments: StatementArguments? = StatementArguments()
let sql = self.sql(&arguments)
let sql = try self.sql(db, &arguments)
let statement = try db.makeSelectStatement(sql)
try statement.setArgumentsWithValidation(arguments!)
return (statement, nil)
@@ -157,6 +181,42 @@ extension QueryInterfaceSelectQueryDefinition : Request {
return try Int.fetchOne(db, countQuery)!
}
/// The database region that the request looks into.
func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
let (statement, _) = try prepare(db)
let region = statement.fetchedRegion
// Can we intersect the region with rowIds?
//
// Give up unless request feeds from a single database table
guard let source = source else {
return region
}
guard case .table(name: let tableName, alias: _) = source else {
return region
}
// Give up unless primary key is rowId
let primaryKeyInfo = try db.primaryKey(tableName)
guard primaryKeyInfo.isRowID else {
return region
}
// Give up unless there is a where clause
guard let whereExpression = try wherePromise.resolve(db) else {
return region
}
// The whereExpression knows better
guard let rowIds = whereExpression.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else {
return region
}
// Database regions are case-insensitive: use the canonical table name
let canonicalTableName = try db.canonicalName(table: tableName)
return region.tableIntersection(canonicalTableName, rowIds: rowIds)
}
private var countQuery: QueryInterfaceSelectQueryDefinition {
guard groupByExpressions.isEmpty && limit == nil else {
// SELECT ... GROUP BY ...
@@ -206,7 +266,7 @@ indirect enum SQLSource {
case table(name: String, alias: String?)
case query(query: QueryInterfaceSelectQueryDefinition, alias: String?)
func sourceSQL(_ arguments: inout StatementArguments?) -> String {
func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
switch self {
case .table(let table, let alias):
if let alias = alias {
@@ -216,9 +276,9 @@ indirect enum SQLSource {
}
case .query(let query, let alias):
if let alias = alias {
return "(" + query.sql(&arguments) + ") AS " + alias.quotedDatabaseIdentifier
return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier
} else {
return "(" + query.sql(&arguments) + ")"
return try "(" + query.sql(db, &arguments) + ")"
}
}
}
@@ -51,11 +51,15 @@ public struct SQLCollatedExpression {
extension SQLCollatedExpression : SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public var reversed: SQLOrderingTerm {
return desc
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.orderingTermSQL(&arguments)
}
+2
View File
@@ -3,6 +3,8 @@
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLCollection is the protocol for types that can be checked for inclusion.
///
/// :nodoc:
public protocol SQLCollection {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
+21
View File
@@ -8,6 +8,8 @@
/// like Column.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// :nodoc:
public protocol SQLExpressible {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -27,6 +29,8 @@ public protocol SQLExpressible {
/// and it adopts SQLSpecificExpressible.
///
/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
///
/// :nodoc:
public protocol SQLSpecificExpressible : SQLExpressible {
// SQLExpressible can be adopted by Swift standard types, and user
// types, through the DatabaseValueConvertible protocol which inherits
@@ -53,11 +57,15 @@ public protocol SQLSpecificExpressible : SQLExpressible {
extension SQLExpressible where Self: SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public var reversed: SQLOrderingTerm {
return SQLOrdering.desc(sqlExpression)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.expressionSQL(&arguments)
}
@@ -68,17 +76,30 @@ extension SQLExpressible where Self: SQLOrderingTerm {
extension SQLExpressible where Self: SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.expressionSQL(&arguments)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.expressionSQL(&arguments)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func count(distinct: Bool) -> SQLCount? {
return sqlExpression.count(distinct: distinct)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func columnCount(_ db: Database) throws -> Int {
return 1
}
}
@@ -5,6 +5,8 @@ extension SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Converts an expression to an SQLExpressionLiteral
///
/// :nodoc:
public var literal: SQLExpressionLiteral {
var arguments: StatementArguments? = []
let sql = expressionSQL(&arguments)
@@ -57,6 +59,8 @@ public struct SQLExpressionLiteral : SQLExpression {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
if let literalArguments = self.arguments {
guard arguments != nil else {
@@ -68,6 +72,13 @@ public struct SQLExpressionLiteral : SQLExpression {
}
return sql
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionLiteral {
return self
}
}
// MARK: - SQLExpressionUnary
@@ -75,6 +86,8 @@ public struct SQLExpressionLiteral : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLUnaryOperator is a SQLite unary operator.
///
/// :nodoc:
public struct SQLUnaryOperator : Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -97,11 +110,15 @@ public struct SQLUnaryOperator : Hashable {
}
/// The hash value
///
/// :nodoc:
public var hashValue: Int {
return sql.hashValue
}
/// Equality operator
///
/// :nodoc:
public static func == (lhs: SQLUnaryOperator, rhs: SQLUnaryOperator) -> Bool {
return lhs.sql == rhs.sql
}
@@ -113,6 +130,8 @@ public struct SQLUnaryOperator : Hashable {
/// an operand expression.
///
/// SQLExpressionUnary(.not, Column("favorite"))
///
/// :nodoc:
public struct SQLExpressionUnary : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -137,9 +156,18 @@ public struct SQLExpressionUnary : SQLExpression {
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&arguments)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionUnary {
return SQLExpressionUnary(op, expression.qualified(by: qualifier))
}
}
// MARK: - SQLExpressionBinary
@@ -147,6 +175,8 @@ public struct SQLExpressionUnary : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLBinaryOperator is a SQLite binary operator.
///
/// :nodoc:
public struct SQLBinaryOperator : Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -223,6 +253,8 @@ public struct SQLBinaryOperator : Hashable {
/// binary operator.
///
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
///
/// :nodoc:
public struct SQLExpressionBinary : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -265,6 +297,63 @@ public struct SQLExpressionBinary : SQLExpression {
return SQLExpressionNot(self)
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
switch op {
case .equal, .is:
// Look for `id == 1` or `id IS 1`?
switch (lhs, rhs) {
case (let column as Column, let dbValue as DatabaseValue),
(let dbValue as DatabaseValue, let column as Column):
// Look for `id == 1`, `rowid == 1`, `1 == id`, `1 == rowid`
var rowIdNames = [Column.rowID.name.lowercased()]
if let rowIdName = rowIdName {
rowIdNames.append(rowIdName.lowercased())
}
guard rowIdNames.contains(column.name.lowercased()) else {
return nil
}
if let rowId = Int64.fromDatabaseValue(dbValue) {
return [rowId]
} else {
return []
}
default:
return nil
}
case .and:
let lids = lhs.matchedRowIds(rowIdName: rowIdName)
let rids = rhs.matchedRowIds(rowIdName: rowIdName)
switch (lids, rids) {
case (nil, nil): return nil
case let (ids?, nil), let (nil, ids?): return ids
case let (lids?, rids?): return lids.intersection(rids)
}
case .or:
let lids = lhs.matchedRowIds(rowIdName: rowIdName)
let rids = rhs.matchedRowIds(rowIdName: rowIdName)
switch (lids, rids) {
case let (lids?, rids?): return lids.union(rids)
default: return nil
}
default:
return nil
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBinary {
return SQLExpressionBinary(op, lhs.qualified(by: qualifier), rhs.qualified(by: qualifier))
}
}
// MARK: - SQLExpressionContains
@@ -296,6 +385,38 @@ struct SQLExpressionContains : SQLExpression {
var negated: SQLExpression {
return SQLExpressionContains(expression, collection, negated: !isNegated)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
// Look for `id IN (1, 2, 3)`
guard let column = expression as? Column,
let array = collection as? SQLExpressionsArray else
{
return nil
}
var rowIdNames = [Column.rowID.name.lowercased()]
if let rowIdName = rowIdName {
rowIdNames.append(rowIdName.lowercased())
}
guard rowIdNames.contains(column.name.lowercased()) else {
return nil
}
var rowIDs: Set<Int64> = []
for expression in array.expressions {
guard let dbValue = expression as? DatabaseValue else { return nil }
if let rowId = Int64.fromDatabaseValue(dbValue) {
rowIDs.insert(rowId)
}
}
return rowIDs
}
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionContains {
return SQLExpressionContains(expression.qualified(by: qualifier), collection, negated: isNegated)
}
}
// MARK: - SQLExpressionBetween
@@ -331,6 +452,14 @@ struct SQLExpressionBetween : SQLExpression {
var negated: SQLExpression {
return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated)
}
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBetween {
return SQLExpressionBetween(
expression.qualified(by: qualifier),
lowerBound.qualified(by: qualifier),
upperBound.qualified(by: qualifier),
negated: isNegated)
}
}
// MARK: - SQLExpressionFunction
@@ -342,6 +471,8 @@ public struct SQLFunctionName : Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The SQL function name
///
/// :nodoc:
public let sql: String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -349,16 +480,22 @@ public struct SQLFunctionName : Hashable {
/// Creates a function name
///
/// SQLFunctionName("ABS")
///
/// :nodoc:
public init(_ sql: String) {
self.sql = sql
}
/// The hash value
///
/// :nodoc:
public var hashValue: Int {
return sql.hashValue
}
/// Equality operator
///
/// :nodoc:
public static func == (lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool {
return lhs.sql == rhs.sql
}
@@ -370,6 +507,8 @@ public struct SQLFunctionName : Hashable {
///
/// // ABS(-1)
/// SQLExpressionFunction(.abs, [-1.databaseValue])
///
/// :nodoc:
public struct SQLExpressionFunction : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -406,6 +545,13 @@ public struct SQLExpressionFunction : SQLExpression {
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")"
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionFunction {
return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualified(by: qualifier) })
}
}
// MARK: - SQLExpressionCount
@@ -425,6 +571,10 @@ struct SQLExpressionCount : SQLExpression {
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
return "COUNT(" + counted.countedSQL(&arguments) + ")"
}
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCount {
return SQLExpressionCount(counted.qualified(by: qualifier))
}
}
// MARK: - SQLExpressionCountDistinct
@@ -443,6 +593,10 @@ struct SQLExpressionCountDistinct : SQLExpression {
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
return "COUNT(DISTINCT " + counted.expressionSQL(&arguments) + ")"
}
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCountDistinct {
return SQLExpressionCountDistinct(counted.qualified(by: qualifier))
}
}
// MARK: - SQLExpressionCollate
@@ -468,4 +622,8 @@ struct SQLExpressionCollate : SQLExpression {
return sql + " COLLATE " + collationName.rawValue
}
}
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCollate {
return SQLExpressionCollate(expression.qualified(by: qualifier), collationName: collationName)
}
}
+25
View File
@@ -16,6 +16,8 @@
/// - SQLExpressionExists
/// - SQLExpressionFunction
/// - SQLExpressionCollate
///
/// :nodoc:
public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -53,6 +55,11 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi
/// let expression = [1,2,3].contains(Column("id")) // id IN (1,2,3)
/// expression.negated // id NOT IN (1,2,3)
var negated: SQLExpression { get }
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the rowIds matched by the expression.
func matchedRowIds(rowIdName: String?) -> Set<Int64>? // TODO: this method should take SQLTableQualifier in account
}
extension SQLExpression {
@@ -64,9 +71,19 @@ extension SQLExpression {
/// let column = Column("favorite")
/// column.negated // NOT favorite
///
/// :nodoc:
public var negated: SQLExpression {
return SQLExpressionNot(self)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The default implementation returns nil
///
/// :nodoc:
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
return nil
}
}
// SQLExpression: SQLExpressible
@@ -74,6 +91,8 @@ extension SQLExpression {
extension SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public var sqlExpression: SQLExpression {
return self
}
@@ -84,6 +103,8 @@ extension SQLExpression {
extension SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func count(distinct: Bool) -> SQLCount? {
if distinct {
// SELECT DISTINCT expr FROM tableName ...
@@ -115,4 +136,8 @@ struct SQLExpressionNot : SQLExpression {
var negated: SQLExpression {
return expression
}
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionNot {
return SQLExpressionNot(expression.qualified(by: qualifier))
}
}
+2
View File
@@ -4,6 +4,8 @@
///
/// The protocol for all types that can be used as an SQL ordering term, as
/// described at https://www.sqlite.org/syntax/ordering-term.html
///
/// :nodoc:
public protocol SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -15,33 +15,75 @@
/// // SELECT *, rowid FROM players
/// let request = Player.all()
public struct AllColumns {
private var qualifier: SQLTableQualifier?
///
public init() { }
}
extension AllColumns : SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
if let qualifierName = qualifier?.name {
return qualifierName.quotedDatabaseIdentifier + ".*"
}
return "*"
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
guard qualifier == nil else {
// SELECT COUNT(t.*) is invalid SQL
fatalError("Not implemented, or invalid query")
}
return "*"
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func count(distinct: Bool) -> SQLCount? {
// SELECT DISTINCT * FROM tableName ...
guard !distinct else {
return nil
}
guard qualifier == nil else {
return nil
}
// SELECT * FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
return .all
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func qualified(by qualifier: SQLTableQualifier) -> AllColumns {
if self.qualifier != nil {
// Never requalify
return self
}
var allColumns = AllColumns()
allColumns.qualifier = qualifier
return allColumns
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public func columnCount(_ db: Database) throws -> Int {
guard let qualifier = qualifier else {
fatalError("Can't compute number of columns without a qualifier")
}
return try db.columns(in: qualifier.tableName).count
}
}
@@ -67,4 +109,12 @@ struct SQLAliasedExpression : SQLSelectable {
func count(distinct: Bool) -> SQLCount? {
return expression.count(distinct: distinct)
}
func qualified(by qualifier: SQLTableQualifier) -> SQLAliasedExpression {
return SQLAliasedExpression(expression.qualified(by: qualifier), alias: alias)
}
func columnCount(_ db: Database) throws -> Int {
return 1
}
}
+27
View File
@@ -4,6 +4,8 @@
///
/// SQLSelectable is the protocol for types that can be selected, as
/// described at https://www.sqlite.org/syntax/result-column.html
///
/// :nodoc:
public protocol SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func resultColumnSQL(_ arguments: inout StatementArguments?) -> String
@@ -13,11 +15,36 @@ public protocol SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func count(distinct: Bool) -> SQLCount?
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func columnCount(_ db: Database) throws -> Int
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func qualified(by qualifier: SQLTableQualifier) -> Self
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public class SQLTableQualifier {
var tableName: String
private var alias: String?
init(tableName: String, alias: String?) {
self.tableName = tableName
self.alias = alias
}
var name: String? {
return alias
}
}
// MARK: - Counting
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public enum SQLCount {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -587,7 +587,7 @@ extension SQLBinaryOperator {
extension SQLUnaryOperator {
/// The `-` unary operator
public static let minus = SQLUnaryOperator("-", needsRightSpace: false)
static let minus = SQLUnaryOperator("-", needsRightSpace: false)
}
/// An SQL arithmetic multiplication.
+9 -3
View File
@@ -19,7 +19,9 @@ extension Database {
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false, no error is thrown if table already exists.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@@ -46,7 +48,9 @@ extension Database {
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false, no error is thrown if table already exists.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@@ -75,7 +79,9 @@ extension Database {
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false, no error is thrown if table already exists.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (TableDefinition) -> Void) throws {
+6 -2
View File
@@ -49,7 +49,9 @@ extension Database {
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false, no error is thrown if table already exists.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - module: The name of an SQLite virtual table module.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
@@ -88,7 +90,9 @@ extension Database {
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false, no error is thrown if table already exists.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - module: a VirtualTableModule
/// - body: An optional closure that defines the virtual table.
/// - throws: A DatabaseError whenever an SQLite error occurs.
+21 -27
View File
@@ -104,8 +104,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
{
self.itemsAreIdenticalFactory = itemsAreIdenticalFactory
self.request = request
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
}
self.databaseWriter = databaseWriter
self.queue = queue
@@ -133,7 +133,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
let initialItems = try Item<Record>.fetchAll(db, request)
fetchedItems = initialItems
if let fetchAndNotifyChanges = fetchAndNotifyChanges {
let observer = FetchedRecordsObserver(selectionInfo: self.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
let observer = FetchedRecordsObserver(region: self.region, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
observer.items = initialItems
db.add(transactionObserver: observer)
@@ -162,8 +162,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
/// main queue unless stated otherwise in the controller's initializer).
public func setRequest<Request>(_ request: Request) throws where Request: TypedRequest, Request.RowDecoder == Record {
self.request = request
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
}
// No observer: don't look for changes
@@ -179,7 +179,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
// and notify eventual changes
let initialItems = fetchedItems
databaseWriter.write { db in
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
observer.items = initialItems
db.add(transactionObserver: observer)
@@ -299,7 +299,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
onChange: onChange,
didChange: didChange,
didProcessTransaction: didProcessTransaction)
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
if let initialItems = initialItems {
observer.items = initialItems
@@ -378,8 +378,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
/// The request
fileprivate var request: Request
/// The observed selection info
private var selectionInfo : SelectStatement.SelectionInfo
/// The observed database region
private var region : DatabaseRegion
/// The eventual current database observer
private var observer: FetchedRecordsObserver<Record>?
@@ -387,16 +387,15 @@ public final class FetchedRecordsController<Record: RowConvertible> {
/// The eventual error handler
fileprivate var errorHandler: ((FetchedRecordsController<Record>, Error) -> ())?
private static func fetchSelectionInfoAndComparator(
private static func fetchRegionAndComparator(
_ db: Database,
request: Request,
itemsAreIdenticalFactory: ItemComparatorFactory<Record>) throws
-> (SelectStatement.SelectionInfo, ItemComparator<Record>)
-> (DatabaseRegion, ItemComparator<Record>)
{
let (statement, _) = try request.prepare(db)
let selectionInfo = statement.selectionInfo
let region = try request.fetchedRegion(db)
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
return (selectionInfo, itemsAreIdentical)
return (region, itemsAreIdentical)
}
}
@@ -522,15 +521,15 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
var needsComputeChanges: Bool
var items: [Item<Record>]! // ought to be not nil when observer has started tracking transactions
let queue: DispatchQueue // protects items
let selectionInfo: SelectStatement.SelectionInfo
let region: DatabaseRegion
var fetchAndNotifyChanges: (FetchedRecordsObserver<Record>) -> ()
init(selectionInfo: SelectStatement.SelectionInfo, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) {
init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) {
self.isValid = true
self.items = nil
self.needsComputeChanges = false
self.queue = DispatchQueue(label: "GRDB.FetchedRecordsObserver")
self.selectionInfo = selectionInfo
self.region = region
self.fetchAndNotifyChanges = fetchAndNotifyChanges
}
@@ -539,22 +538,17 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return eventKind.impacts(selectionInfo)
return region.isModified(byEventsOfKind: eventKind)
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Part of the TransactionObserverType protocol
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
/// Part of the TransactionObserverType protocol
func databaseDidChange(with event: DatabaseEvent) {
needsComputeChanges = true
if region.isModified(by: event) {
needsComputeChanges = true
stopObservingDatabaseChangesUntilNextTransaction()
}
}
/// Part of the TransactionObserverType protocol
func databaseWillCommit() throws { }
/// Part of the TransactionObserverType protocol
func databaseDidRollback(_ db: Database) {
needsComputeChanges = false
+69 -4
View File
@@ -13,14 +13,16 @@ extension Database.ConflictResolution {
// MARK: - PersistenceError
/// An error thrown by a type that adopts Persistable.
public enum PersistenceError: Error {
public enum PersistenceError: Error, CustomStringConvertible {
/// Thrown by MutablePersistable.update() when no matching row could be
/// found in the database.
case recordNotFound(MutablePersistable)
}
extension PersistenceError : CustomStringConvertible {
// CustomStringConvertible
extension PersistenceError {
/// :nodoc:
public var description: String {
switch self {
case .recordNotFound(let persistable):
@@ -96,6 +98,8 @@ public struct PersistenceContainer {
/// Accesses the value associated with the given column, in a
/// case-insensitive fashion.
///
/// :nodoc:
subscript(caseInsensitive column: String) -> DatabaseValueConvertible? {
get {
if let value = storage[column] {
@@ -385,6 +389,30 @@ extension MutablePersistable {
try update(db, columns: Set(columns.map { $0.name }))
}
/// If the record has differences from the other record, executes an UPDATE
/// statement so that those changes and only those changes are saved in
/// the database.
///
/// This method is guaranteed to have saved the eventual changes in the
/// database if it returns without error.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
@discardableResult
public func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool {
let changedColumns = Set(databaseChanges(from: record).keys)
if changedColumns.isEmpty {
return false
} else {
try update(db, columns: changedColumns)
return true
}
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
///
@@ -409,6 +437,43 @@ extension MutablePersistable {
return try performExists(db)
}
// MARK: - Changes Tracking
/// Returns a boolean indicating whether this record and the other record
/// have the same database representation.
public func databaseEqual(_ record: Self) -> Bool {
return databaseChangesIterator(from: record).next() == nil
}
/// A dictionary of values changed from the other record.
///
/// Its keys are column names. Its values come from the other record.
///
/// Note that this method is not symmetrical, not only in terms of values,
/// but also in terms of columns. When the two records don't define the
/// same set of columns in their `encode(to:)` method, only the columns
/// defined by the receiver record are considered.
public func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue] {
return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: record))
}
fileprivate func databaseChangesIterator(from record: MutablePersistable) -> AnyIterator<(String, DatabaseValue)> {
let oldContainer = PersistenceContainer(record)
var newValueIterator = PersistenceContainer(self).makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let oldValue = oldContainer[caseInsensitive: column]
let oldDbValue = oldValue?.databaseValue ?? .null
let newDbValue = newValue?.databaseValue ?? .null
if newDbValue != oldDbValue {
return (column, oldDbValue)
}
}
return nil
}
}
// MARK: - CRUD Internals
/// Return true if record has a non-null primary key
@@ -572,7 +637,7 @@ extension MutablePersistable {
// Avoid hitting the database
return 0
}
return try filter(db, keys: keys).deleteAll(db)
return try filter(keys: keys).deleteAll(db)
}
/// Delete a record, identified by its primary key; returns whether a
@@ -623,7 +688,7 @@ extension MutablePersistable {
// Avoid hitting the database
return 0
}
return try filter(db, keys: keys).deleteAll(db)
return try filter(keys: keys).deleteAll(db)
}
/// Delete a record, identified by a unique key (the primary key or any key
+48 -41
View File
@@ -13,7 +13,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
/// Creates a Record from a row.
required public init(row: Row) {
if row.isFetched {
// Take care of the hasPersistentChangedValues flag.
// Take care of the hasDatabaseChanges flag.
//
// Row may be a reused row which will turn invalid as soon as the
// SQLite statement is iterated. We need to store an
@@ -146,7 +146,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
/// `encode(to:)` method.
///
/// The eventual primary key is copied, as well as the
/// `hasPersistentChangedValues` flag.
/// `hasDatabaseChanges` flag.
///
/// - returns: A copy of self.
open func copy() -> Self {
@@ -181,11 +181,18 @@ open class Record : RowConvertible, TableMapping, Persistable {
/// you may set it to true or false when you know better. Setting it to
/// false does not prevent it from turning true on subsequent modifications
/// of the record.
public var hasPersistentChangedValues: Bool {
get { return makePersistentChangedValuesIterator().next() != nil }
public var hasDatabaseChanges: Bool {
get { return databaseChangesIterator().next() != nil }
set { referenceRow = newValue ? nil : Row(self) }
}
/// Deprecated alias for `hasDatabaseChanges`.
@available(*, deprecated, renamed: "hasDatabaseChanges")
public var hasPersistentChangedValues: Bool {
get { return hasDatabaseChanges }
set { hasDatabaseChanges = newValue }
}
/// A dictionary of changes that have not been saved.
///
/// Its keys are column names, and values the old values that have been
@@ -194,30 +201,31 @@ open class Record : RowConvertible, TableMapping, Persistable {
/// Unless the record has actually been fetched or saved, the old values
/// are nil.
///
/// See `hasPersistentChangedValues` for more information.
public var persistentChangedValues: [String: DatabaseValue?] {
var persistentChangedValues: [String: DatabaseValue?] = [:]
for (key, value) in makePersistentChangedValuesIterator() {
persistentChangedValues[key] = value
}
return persistentChangedValues
/// See `hasDatabaseChanges` for more information.
public var databaseChanges: [String: DatabaseValue?] {
return Dictionary(uniqueKeysWithValues: databaseChangesIterator())
}
// A change iterator that is used by both hasPersistentChangedValues and
/// Deprecated alias for `databaseChanges`.
@available(*, deprecated, renamed: "databaseChanges")
public var persistentChangedValues: [String: DatabaseValue?] {
return databaseChanges
}
// A change iterator that is used by both hasDatabaseChanges and
// persistentChangedValues properties.
private func makePersistentChangedValuesIterator() -> AnyIterator<(column: String, old: DatabaseValue?)> {
private func databaseChangesIterator() -> AnyIterator<(String, DatabaseValue?)> {
let oldRow = referenceRow
var newValueIterator = PersistenceContainer(self).makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let new = newValue?.databaseValue ?? .null
guard let oldRow = oldRow, let old: DatabaseValue = oldRow[column] else {
return (column: column, old: nil)
let newDbValue = newValue?.databaseValue ?? .null
guard let oldRow = oldRow, let oldDbValue: DatabaseValue = oldRow[column] else {
return (column, nil)
}
if new != old {
return (column: column, old: old)
if newDbValue != oldDbValue {
return (column, oldDbValue)
}
}
return nil
@@ -225,7 +233,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
}
/// Reference row for the *hasPersistentChangedValues* property.
/// Reference row for the *hasDatabaseChanges* property.
var referenceRow: Row?
@@ -233,8 +241,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
/// Executes an INSERT statement.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
/// On success, this method sets the *hasDatabaseChanges* flag to false.
///
/// This method is guaranteed to have inserted a row in the database if it
/// returns without error.
@@ -257,20 +264,19 @@ open class Record : RowConvertible, TableMapping, Persistable {
didInsert(with: rowID, for: rowIDColumn)
// Update persistenceContainer with inserted id, so that we can
// set hasPersistentChangedValues to false:
// set hasDatabaseChanges to false:
if let rowIDColumn = rowIDColumn {
persistenceContainer[caseInsensitive: rowIDColumn] = rowID
}
}
// Set hasPersistentChangedValues to false
// Set hasDatabaseChanges to false
referenceRow = Row(persistenceContainer)
}
/// Executes an UPDATE statement.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
/// On success, this method sets the *hasDatabaseChanges* flag to false.
///
/// This method is guaranteed to have updated a row in the database if it
/// returns without error.
@@ -284,7 +290,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
// The simplest code would be:
//
// try performUpdate(db, columns: columns)
// hasPersistentChangedValues = false
// hasDatabaseChanges = false
//
// But this would trigger two calls to `encode(to:)`.
let dao = try DAO(db, self)
@@ -297,30 +303,33 @@ open class Record : RowConvertible, TableMapping, Persistable {
throw PersistenceError.recordNotFound(self)
}
// Set hasPersistentChangedValues to false
// Set hasDatabaseChanges to false
referenceRow = Row(dao.persistenceContainer)
}
/// If the record has been changed, executes an UPDATE statement so that
/// those changes and only those changes are saved in the database.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
/// On success, this method sets the *hasDatabaseChanges* flag to false.
///
/// This method is guaranteed to have saved the eventual changes in the
/// database if it returns without error.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - returns: Whether the record had changes.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
final public func updateChanges(_ db: Database) throws {
let changedColumns = Set(persistentChangedValues.keys)
guard !changedColumns.isEmpty else {
return
@discardableResult
final public func updateChanges(_ db: Database) throws -> Bool {
let changedColumns = Set(databaseChanges.keys)
if changedColumns.isEmpty {
return false
} else {
try update(db, columns: changedColumns)
return true
}
try update(db, columns: changedColumns)
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
@@ -331,8 +340,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
///
/// Otherwise, performs an insert.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
/// On success, this method sets the *hasDatabaseChanges* flag to false.
///
/// This method is guaranteed to have inserted or updated a row in the
/// database if it returns without error.
@@ -346,8 +354,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
/// Executes a DELETE statement.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to true.
/// On success, this method sets the *hasDatabaseChanges* flag to true.
///
/// - parameter db: A database connection.
/// - returns: Whether a database row was deleted.
@@ -357,8 +364,8 @@ open class Record : RowConvertible, TableMapping, Persistable {
defer {
// Future calls to update() will throw NotFound. Make the user
// a favor and make sure this error is thrown even if she checks the
// hasPersistentChangedValues flag:
hasPersistentChangedValues = true
// hasDatabaseChanges flag:
hasDatabaseChanges = true
}
return try performDelete(db)
}
+101
View File
@@ -0,0 +1,101 @@
/// RecordBox is a subclass of Record that aims at giving any record type the
/// changes tracking provided by the Record class.
///
/// // A Regular record struct
/// struct Player: RowConvertible, MutablePersistable, Codable {
/// static let databaseTableName = "players"
/// var id: Int64?
/// var name: String
/// var score: Int
/// mutating func didInsert(with rowID: Int64, for column: String?) {
/// id = rowID
/// }
/// }
///
/// try dbQueue.inDatabase { db in
/// // Fetch a player record
/// let playerRecord = try RecordBox<Player>.fetchOne(db, key: 1)!
///
/// // Profit from changes tracking
/// playerRecord.value.score = 300
/// playerRecord.hasPersistentChangedValues // true
/// playerRecord.persistentChangedValues["score"] // 100 (the old value)
/// }
@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
public final class RecordBox<T: RowConvertible & MutablePersistable>: Record {
/// The boxed record
public var value: T
/// Creates a RecordBox that wraps the given record
public init(value: T) {
self.value = value
super.init()
}
// MARK: - RowConvertible
/// Initializes a record from `row`.
public required init(row: Row) {
self.value = T(row: row)
super.init(row: row)
}
// MARK: - TableMapping
/// :nodoc:
override public class var databaseTableName: String {
return T.databaseTableName
}
/// :nodoc:
override public class var databaseSelection: [SQLSelectable] {
return T.databaseSelection
}
// MARK: - MutablePersistable
/// :nodoc:
override public class var persistenceConflictPolicy: PersistenceConflictPolicy {
return T.persistenceConflictPolicy
}
/// :nodoc:
override public func encode(to container: inout PersistenceContainer) {
value.encode(to: &container)
}
/// :nodoc:
override public func didInsert(with rowID: Int64, for column: String?) {
value.didInsert(with: rowID, for: column)
}
/// :nodoc:
override public func insert(_ db: Database) throws {
try value.insert(db)
hasPersistentChangedValues = false
}
/// :nodoc:
override public func update(_ db: Database, columns: Set<String>) throws {
try value.update(db, columns: columns)
hasPersistentChangedValues = false
}
/// :nodoc:
@discardableResult
override public func delete(_ db: Database) throws -> Bool {
defer {
// Future calls to update() will throw NotFound. Make the user
// a favor and make sure this error is thrown even if she checks the
// hasPersistentChangedValues flag:
hasPersistentChangedValues = true
}
return try value.delete(db)
}
/// :nodoc:
public func exists(_ db: Database) throws -> Bool {
return try value.exists(db)
}
}
+85 -45
View File
@@ -1,19 +1,20 @@
private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
let row: Row
let decoder: RowDecoder
init(row: Row) {
self.row = row
init(decoder: RowDecoder) {
self.decoder = decoder
}
/// The path of coding keys taken to get to this point in decoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey] { return [] }
var codingPath: [CodingKey] { return decoder.codingPath }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
var allKeys: [Key] {
return row.columnNames.flatMap { Key(stringValue: $0) }
let row = decoder.row
let columnNames = Set(row.columnNames)
let scopeNames = row.scopeNames
return columnNames.union(scopeNames).flatMap { Key(stringValue: $0) }
}
/// Returns whether the `Decoder` contains a value associated with the given key.
@@ -23,7 +24,8 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool {
return row.hasColumn(key.stringValue)
let row = decoder.row
return row.hasColumn(key.stringValue) || (row.scoped(on: key.stringValue) != nil)
}
/// Decodes a null value for the given key.
@@ -32,7 +34,8 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
func decodeNil(forKey key: Key) throws -> Bool {
return row[key.stringValue] == nil
let row = decoder.row
return row[key.stringValue] == nil && (row.scoped(on: key.stringValue) == nil)
}
/// Decodes a value of the given type for the given key.
@@ -43,20 +46,50 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return row[key.stringValue] }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return row[key.stringValue] }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return row[key.stringValue] }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return row[key.stringValue] }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return row[key.stringValue] }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return row[key.stringValue] }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return row[key.stringValue] }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return row[key.stringValue] }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return row[key.stringValue] }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return row[key.stringValue] }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return row[key.stringValue] }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return row[key.stringValue] }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return row[key.stringValue] }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return row[key.stringValue] }
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return decoder.row[key.stringValue] }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return decoder.row[key.stringValue] }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return decoder.row[key.stringValue] }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return decoder.row[key.stringValue] }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return decoder.row[key.stringValue] }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return decoder.row[key.stringValue] }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return decoder.row[key.stringValue] }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return decoder.row[key.stringValue] }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] }
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns nil if the container does not have a value
/// associated with key, or if the value is null. The difference between
/// these states can be distinguished with a contains(_:) call.
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable {
let row = decoder.row
// Try column
if row.hasColumn(key.stringValue) {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T?
} else if dbValue.isNull {
return nil
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
// Fallback on scope
if let scopedRow = row.scoped(on: key.stringValue), scopedRow.containsNonNullValue {
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
}
return nil
}
/// Decodes a value of the given type for the given key.
///
@@ -67,14 +100,27 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
let row = decoder.row
// Try column
if row.hasColumn(key.stringValue) {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
// Fallback on scope
if let scopedRow = row.scoped(on: key.stringValue) {
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
}
let path = (codingPath.map { $0.stringValue } + [key.stringValue]).joined(separator: ".")
fatalError("No such column or scope: \(path)")
}
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
@@ -84,7 +130,7 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container.
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError("Not implemented")
fatalError("not implemented")
}
/// Returns the data stored for the given key as represented in an unkeyed container.
@@ -93,7 +139,9 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container.
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
fatalError("Not implemented")
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
@@ -104,7 +152,7 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key.
public func superDecoder() throws -> Decoder {
fatalError("Not implemented")
return decoder
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
@@ -114,16 +162,15 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
public func superDecoder(forKey key: Key) throws -> Decoder {
fatalError("Not implemented")
return decoder
}
}
private struct RowSingleValueDecodingContainer: SingleValueDecodingContainer {
let row: Row
var codingPath: [CodingKey]
let column: CodingKey
var codingPath: [CodingKey] { return [] }
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
@@ -182,14 +229,7 @@ private struct RowDecoder: Decoder {
var userInfo: [CodingUserInfoKey : Any] { return [:] }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
// Asked for a keyed type: top level required
guard codingPath.isEmpty else {
throw DecodingError.typeMismatch(
RowDecoder.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "nested decoding is not supported"))
}
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(row: row))
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(decoder: self))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
@@ -205,7 +245,7 @@ private struct RowDecoder: Decoder {
RowDecoder.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "single value decoding requires a coding key"))
}
return RowSingleValueDecodingContainer(row: row, column: codingKey)
return RowSingleValueDecodingContainer(row: row, codingPath: codingPath, column: codingKey)
}
}
+11 -8
View File
@@ -78,7 +78,7 @@ extension RowConvertible where Self: TableMapping {
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence.Element: DatabaseValueConvertible {
return try filter(db, keys: keys).fetchCursor(db)
return try filter(keys: keys).fetchCursor(db)
}
/// Returns an array of records, given their primary keys.
@@ -98,7 +98,7 @@ extension RowConvertible where Self: TableMapping {
// Avoid hitting the database
return []
}
return try filter(db, keys: keys).fetchAll(db)
return try filter(keys: keys).fetchAll(db)
}
/// Returns a single record given its primary key.
@@ -115,7 +115,7 @@ extension RowConvertible where Self: TableMapping {
// Avoid hitting the database
return nil
}
return try filter(db, keys: [key]).fetchOne(db)
return try filter(key: key).fetchOne(db)
}
}
@@ -139,7 +139,7 @@ extension RowConvertible where Self: TableMapping {
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor<Self> {
return try filter(db, keys: keys).fetchCursor(db)
return try filter(keys: keys).fetchCursor(db)
}
/// Returns an array of records identified by the provided unique keys
@@ -155,12 +155,11 @@ extension RowConvertible where Self: TableMapping {
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] {
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return []
}
return try filter(db, keys: keys).fetchAll(db)
return try filter(keys: keys).fetchAll(db)
}
/// Returns a single record identified by a unique key (the primary key or
@@ -173,7 +172,11 @@ extension RowConvertible where Self: TableMapping {
/// - key: A dictionary of values.
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? {
return try filter(db, keys: [key]).fetchOne(db)
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self? {
guard let key = key else {
// Avoid hitting the database
return nil
}
return try filter(key: key).fetchOne(db)
}
}
+2 -1
View File
@@ -24,7 +24,7 @@
/// RowConvertible is adopted by Record.
public protocol RowConvertible {
/// Initializes a record from `row`.
/// Creates a record from `row`.
///
/// For performance reasons, the row argument may be reused during the
/// iteration of a fetch query. If you want to keep the row for later use,
@@ -51,6 +51,7 @@ public final class RecordCursor<Record: RowConvertible> : Cursor {
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Record? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
+46 -56
View File
@@ -58,7 +58,7 @@ extension TableMapping {
extension TableMapping {
// MARK: Counting All
// MARK: - Counting All
/// The number of records.
///
@@ -70,63 +70,53 @@ extension TableMapping {
extension TableMapping {
// MARK: Key Requests
// MARK: - SQL Generation
static func filter<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
let primaryKey = try db.primaryKey(databaseTableName)
let columns = primaryKey.columns.map { Column($0) }
GRDBPrecondition(columns.count == 1, "table \(databaseTableName) has multiple columns in its primary key")
let column = columns[0]
let keys = Array(keys)
switch keys.count {
case 0:
return none()
case 1:
return filter(column == keys[0])
default:
return filter(keys.contains(column))
}
/// The selection as an SQL String.
///
/// For example:
///
/// struct Player: TableMapping {
/// static let databaseTableName = "players"
/// }
///
/// // SELECT "players".* FROM players
/// let sql = "SELECT \(Player.selectionSQL()) FROM players"
///
/// // SELECT "p".* FROM players AS p
/// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p"
public static func selectionSQL(alias: String? = nil) -> String {
let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: alias ?? databaseTableName)
let selection = databaseSelection.map { $0.qualified(by: qualifier) }
var arguments: StatementArguments? = nil
return selection
.map { $0.resultColumnSQL(&arguments) }
.joined(separator: ", ")
}
// Raises a fatal error if there is no unique index on the columns (unless
// fatalErrorOnMissingUniqueIndex is false, for testability).
//
// TODO: think about
// - allowing non unique keys in Type.fetchOne(db, key: ...) ???
// - allowing non unique keys in Type.fetchAll/Cursor(db, keys: ...)
// - forbidding nil values: Player.deleteOne(db, key: ["email": nil]) may delete several rows (case of a nullable unique key)
static func filter(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> QueryInterfaceRequest<Self> {
// SELECT * FROM table WHERE ((a=? AND b=?) OR (c=? AND d=?) OR ...)
let keyPredicates: [SQLExpression] = try keys.map { key in
// Prevent filter(db, keys: [[:]])
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
// Prevent filter(db, keys: [["foo": 1, "bar": 2]]) where
// ("foo", "bar") is not a unique key (primary key or columns of a
// unique index)
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
let message = "table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))"
if fatalErrorOnMissingUniqueIndex {
fatalError(message)
} else {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: message)
}
}
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
let columnPredicates: [SQLExpression] = key
// Sort key columns in the same order as the unique index
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
.map { (column, value) in Column(column) == value }
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
}
guard let predicate = SQLBinaryOperator.or.join(keyPredicates) else {
// No key
return none()
}
return filter(predicate)
/// Returns the number of selected columns.
///
/// For example:
///
/// struct Player: TableMapping {
/// static let databaseTableName = "players"
/// }
///
/// try dbQueue.inDatabase { db in
/// try db.create(table: "players") { t in
/// t.column("id", .integer).primaryKey()
/// t.column("name", .text)
/// t.column("score", .integer)
/// }
///
/// // 3
/// try Player.numberOfSelectedColumns(db)
/// }
public static func numberOfSelectedColumns(_ db: Database) throws -> Int {
let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: nil)
return try databaseSelection
.map { try $0.qualified(by: qualifier).columnCount(db) }
.reduce(0, +)
}
}
+8
View File
@@ -23,16 +23,24 @@ public func databaseQuestionMarks(count: Int) -> String {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// This protocol is an implementation detail of GRDB. Don't use it.
///
/// :nodoc:
public protocol _OptionalProtocol {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
associatedtype _Wrapped
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// This conformance is an implementation detail of GRDB. Don't rely on it.
///
/// :nodoc:
extension Optional : _OptionalProtocol {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// :nodoc:
public typealias _Wrapped = Wrapped
}
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '2.4.2'
s.version = '2.9.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
+120 -12
View File
@@ -86,7 +86,7 @@
560FC5A21CB00B880014AA8E /* DatabaseFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */; };
560FC5A41CB00B880014AA8E /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
560FC5A61CB00B880014AA8E /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
560FC5A61CB00B880014AA8E /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
560FC5A71CB00B880014AA8E /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
560FC5B21CB031E30014AA8E /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */; };
560FC5B31CB031EA0014AA8E /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
@@ -187,6 +187,10 @@
564448851EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564448881EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564448891EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
564E73F2203DA2A4000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
564F9C1F1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
564F9C201F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
564F9C231F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
@@ -250,6 +254,20 @@
566475D01D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; };
566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
5665F86C203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; };
5665F86D203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; };
5665F86E203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; };
5665F86F203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */; };
566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */; };
566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */; };
566A843020413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; };
566A843120413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; };
566A843220413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; };
566A843320413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; };
566A84462041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; };
566A84472041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; };
566A84482041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; };
566A84492041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; };
566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
566AD8C71D531BEA002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; };
@@ -319,7 +337,7 @@
567156601CB16729007DC145 /* DatabaseFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */; };
567156611CB16729007DC145 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
567156621CB16729007DC145 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
567156631CB16729007DC145 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
567156631CB16729007DC145 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
567156641CB16729007DC145 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
567156671CB16729007DC145 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 560FC54D1CB003810014AA8E /* GRDBCipher.framework */; };
5671FC211DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
@@ -380,6 +398,12 @@
567F45AA1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AD1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
5680520C2013209300E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520A2013209300E87861 /* RecordBox.swift */; };
5680520D2013209900E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520A2013209300E87861 /* RecordBox.swift */; };
5680521E2013296F00E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; };
5680521F2013296F00E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; };
568052202013297000E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; };
568052212013297000E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; };
568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568068361EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
@@ -462,6 +486,8 @@
569C1EB41CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; };
569C1EB61CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; };
569C1EB71CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; };
569EF0E9200D387000A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */; };
569EF0EA200D387000A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */; };
56A4CDB11D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
56A4CDB21D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
56A4CDB51D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
@@ -577,7 +603,7 @@
56AFCA731CB1AA9900F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; };
56AFCA741CB1AA9900F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
56AFCA751CB1AA9900F48B96 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56AFCA761CB1AA9900F48B96 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
56AFCA761CB1AA9900F48B96 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
56AFCA771CB1AA9900F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
56AFCA831CB1AAC900F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; };
56AFCA891CB1ABC800F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; };
@@ -637,7 +663,7 @@
56AFCACC1CB1ABC800F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; };
56AFCACD1CB1ABC800F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; };
56AFCACE1CB1ABC800F48B96 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56AFCACF1CB1ABC800F48B96 /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
56AFCACF1CB1ABC800F48B96 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
56AFCAD21CB1ABC800F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; };
56B021CA1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; };
@@ -668,6 +694,22 @@
56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; };
56C3F7571CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; };
56C3F7581CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; };
56CC9236201E009700CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */; };
56CC9237201E009800CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */; };
56CC9238201E009900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */; };
56CC9239201E009A00CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */; };
56CC923E201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */; };
56CC923F201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */; };
56CC9240201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */; };
56CC9241201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */; };
56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */; };
56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */; };
56CC924E201E059100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */; };
56CC924F201E059100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */; };
56CC9257201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; };
56CC9258201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; };
56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; };
56CC925A201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; };
56CEB4F21EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; };
56CEB4F51EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; };
56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; };
@@ -793,7 +835,7 @@
5605F1521C672E4000235C62 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+RawRepresentable.swift"; sourceTree = "<group>"; };
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementSelectionInfoTests.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = "<group>"; };
5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
@@ -838,6 +880,7 @@
5636E9BB1D22574100B9B05F /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = "<group>"; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
@@ -863,6 +906,10 @@
566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSpecificExpressible+QueryInterface.swift"; sourceTree = "<group>"; };
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableChangesTests.swift; sourceTree = "<group>"; };
566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = "<group>"; };
566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = "<group>"; };
566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = "<group>"; };
@@ -891,6 +938,8 @@
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
5680520A2013209300E87861 /* RecordBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = "<group>"; };
5680521C2013296800E87861 /* RecordBoxTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBoxTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = "<group>"; };
@@ -926,6 +975,7 @@
5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = "<group>"; };
5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = "<group>"; };
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = "<group>"; };
569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryTests.swift; sourceTree = "<group>"; };
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = "<group>"; };
@@ -989,6 +1039,10 @@
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLCipher/GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
56CC924B201E059100CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = "<group>"; };
56CC9256201E094E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = "<group>"; };
56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = "<group>"; };
56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = "<group>"; };
@@ -1151,9 +1205,10 @@
560B3FA41C19DFF800C58EC7 /* Persistable */ = {
isa = PBXGroup;
children = (
566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */,
56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */,
5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */,
56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */,
56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableTests.swift */,
563363AA1C933FF8000BE133 /* PersistableTests.swift */,
);
@@ -1378,11 +1433,11 @@
569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */,
563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */,
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */,
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */,
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */,
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */,
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */,
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */,
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */,
);
name = Private;
sourceTree = "<group>";
@@ -1390,6 +1445,7 @@
56A238111B9C74A90082EB20 /* Core */ = {
isa = PBXGroup;
children = (
5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */,
56DAA2C41DE99D8D006E10C8 /* Cursor */,
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */,
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */,
@@ -1401,6 +1457,7 @@
563363BB1C93FD32000BE133 /* DatabaseQueue */,
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
@@ -1471,8 +1528,10 @@
isa = PBXGroup;
children = (
56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */,
564E73EB203DA29B000C443C /* JoinSupportTests.swift */,
560B3FA41C19DFF800C58EC7 /* Persistable */,
56176C9E1EACEDF9000F3F2B /* Record */,
5680521C2013296800E87861 /* RecordBoxTests.swift */,
5674A7251F30A8EF0095F066 /* RowConvertible */,
56176C9C1EACEA8C000F3F2B /* TableMapping */,
);
@@ -1493,7 +1552,9 @@
560A37A31C8F625000949E71 /* DatabasePool.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
@@ -1505,8 +1566,8 @@
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
5605F1471C672E4000235C62 /* Support */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
);
path = Core;
sourceTree = "<group>";
@@ -1527,6 +1588,7 @@
560D92441C672C4B00F4F92B /* Persistable.swift */,
5674A6F31F307F600095F066 /* Persistable+Encodable.swift */,
56A238A11B9C753B0082EB20 /* Record.swift */,
5680520A2013209300E87861 /* RecordBox.swift */,
56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */,
5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */,
56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */,
@@ -1555,11 +1617,15 @@
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */,
5623935F1DEE06D300A6B01F /* CursorTests.swift */,
56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */,
56CC924B201E059100CB597E /* DropFirstCursorTests.swift */,
56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */,
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */,
562393561DEE013C00A6B01F /* FilterCursorTests.swift */,
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */,
562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */,
562393711DEE104400A6B01F /* MapCursorTests.swift */,
56CC9256201E094E00CB597E /* PrefixCursorTests.swift */,
56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */,
);
name = Cursor;
sourceTree = "<group>";
@@ -1925,6 +1991,7 @@
566B91241FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
56CEB5121EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
5659F4911EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */,
56CEB4F21EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */,
560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */,
@@ -1942,6 +2009,7 @@
560FC5221CB003810014AA8E /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
560FC5231CB003810014AA8E /* Configuration.swift in Sources */,
566475CD1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
569EF0E9200D387000A9FA45 /* DatabaseRegion.swift in Sources */,
5698AC381D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */,
5659F4991EA8D989004A4992 /* Pool.swift in Sources */,
@@ -1998,6 +2066,7 @@
560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */,
560FC53F1CB003810014AA8E /* Row.swift in Sources */,
560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */,
5680520C2013209300E87861 /* RecordBox.swift in Sources */,
560FC5411CB003810014AA8E /* Persistable.swift in Sources */,
566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
@@ -2024,6 +2093,7 @@
564448841EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
560FC5B21CB031E30014AA8E /* StatementColumnConvertibleFetchTests.swift in Sources */,
561667021D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */,
5680521E2013296F00E87861 /* RecordBoxTests.swift in Sources */,
562EA8271F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
569C1EB31CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */,
560FC5651CB00B880014AA8E /* RecordPrimaryKeyNoneTests.swift in Sources */,
@@ -2032,6 +2102,7 @@
56A8C2421D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */,
560FC5681CB00B880014AA8E /* SelectStatementTests.swift in Sources */,
5698AC811DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */,
56CC923E201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */,
560FC56A1CB00B880014AA8E /* QueryInterfaceExpressionsTests.swift in Sources */,
562393191DECC02000A6B01F /* RowFetchTests.swift in Sources */,
560FC56B1CB00B880014AA8E /* DatabaseCollationTests.swift in Sources */,
@@ -2057,8 +2128,10 @@
560FC5781CB00B880014AA8E /* RowFromStatementTests.swift in Sources */,
560FC5791CB00B880014AA8E /* RecordPrimaryKeyMultipleTests.swift in Sources */,
562393461DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */,
56CC9257201E094F00CB597E /* PrefixCursorTests.swift in Sources */,
5698AC971DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
5657AB4F1D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
56CC9236201E009700CB597E /* DropWhileCursorTests.swift in Sources */,
56D5075F1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
56176C631EACCCC7000F3F2B /* FTS5TokenizerTests.swift in Sources */,
5623934F1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
@@ -2075,8 +2148,10 @@
5698ACB71DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
5672DE5A1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */,
56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */,
564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */,
5674A7111F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
5657AB471D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
5665F86C203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */,
560FC5811CB00B880014AA8E /* RecordCopyTests.swift in Sources */,
560FC5821CB00B880014AA8E /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */,
@@ -2100,6 +2175,7 @@
560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */,
560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */,
560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */,
562393311DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
560FC5921CB00B880014AA8E /* RowConvertibleTests.swift in Sources */,
56A5EF101EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
@@ -2121,6 +2197,7 @@
5657AB671D108BA9006283EF /* FoundationURLTests.swift in Sources */,
560FC59D1CB00B880014AA8E /* TableMapping+QueryInterfaceRequestTests.swift in Sources */,
562205F51E420E48005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
566A84462041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */,
562393581DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
560FC59E1CB00B880014AA8E /* FoundationNSDateTests.swift in Sources */,
568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
@@ -2133,7 +2210,7 @@
5690C3271D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */,
560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */,
56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
560FC5A61CB00B880014AA8E /* StatementSelectionInfoTests.swift in Sources */,
560FC5A61CB00B880014AA8E /* DatabaseRegionTests.swift in Sources */,
5698AC8A1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
5698AC041D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */,
5690C3381D23E7D200E59934 /* FoundationDateTests.swift in Sources */,
@@ -2143,6 +2220,7 @@
56DAA2D31DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
560FC5A71CB00B880014AA8E /* GRDBTestCase.swift in Sources */,
562393611DEE06D300A6B01F /* CursorTests.swift in Sources */,
566A843020413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */,
569178471CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -2163,6 +2241,7 @@
564448851EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
567156241CB16729007DC145 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
567156251CB16729007DC145 /* RowFromDictionaryTests.swift in Sources */,
5680521F2013296F00E87861 /* RecordBoxTests.swift in Sources */,
562EA8281F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
565F03C41CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */,
567156261CB16729007DC145 /* SelectStatementTests.swift in Sources */,
@@ -2171,6 +2250,7 @@
5671562A1CB16729007DC145 /* UpdateStatementTests.swift in Sources */,
5698AC821DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */,
5657AB481D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
56CC923F201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */,
5671562B1CB16729007DC145 /* DatabaseMigratorTests.swift in Sources */,
5623931A1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
5671562E1CB16729007DC145 /* DatabasePoolCollationTests.swift in Sources */,
@@ -2196,8 +2276,10 @@
567156361CB16729007DC145 /* RowFromStatementTests.swift in Sources */,
567156371CB16729007DC145 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
5657AB401D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
56CC9258201E094F00CB597E /* PrefixCursorTests.swift in Sources */,
562393471DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */,
5698AC981DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
56CC9237201E009800CB597E /* DropWhileCursorTests.swift in Sources */,
56D507601F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
56176C691EACCCC8000F3F2B /* FTS5TokenizerTests.swift in Sources */,
562393501DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
@@ -2214,8 +2296,10 @@
5698ACB81DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
567156401CB16729007DC145 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
56176C661EACCCC8000F3F2B /* FTS5PatternTests.swift in Sources */,
564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */,
5674A7131F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
567156411CB16729007DC145 /* PersistableTests.swift in Sources */,
5665F86D203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */,
5657AB501D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
567156441CB16729007DC145 /* RecordSubClassTests.swift in Sources */,
5690C3391D23E7D200E59934 /* FoundationDateTests.swift in Sources */,
@@ -2239,6 +2323,7 @@
567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
567156511CB16729007DC145 /* RowConvertibleTests.swift in Sources */,
56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */,
56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */,
562393321DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
567156531CB16729007DC145 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
56A5EF111EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
@@ -2260,6 +2345,7 @@
5671565A1CB16729007DC145 /* StatementArguments+FoundationTests.swift in Sources */,
5657AB581D108BA9006283EF /* FoundationNSStringTests.swift in Sources */,
562205F81E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
566A84472041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */,
562393591DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
5671565B1CB16729007DC145 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */,
568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
@@ -2280,8 +2366,9 @@
5622060A1E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */,
562205F71E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */,
56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
567156631CB16729007DC145 /* StatementSelectionInfoTests.swift in Sources */,
567156631CB16729007DC145 /* DatabaseRegionTests.swift in Sources */,
562393621DEE06D300A6B01F /* CursorTests.swift in Sources */,
566A843120413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */,
567156641CB16729007DC145 /* GRDBTestCase.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -2298,6 +2385,7 @@
566B91271FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
56CEB5151EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
5659F4941EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */,
56CEB4F51EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */,
56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */,
@@ -2315,6 +2403,7 @@
56AFC9F51CB1A8BB00F48B96 /* Date.swift in Sources */,
56AFC9F71CB1A8BB00F48B96 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
566475D01D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
569EF0EA200D387000A9FA45 /* DatabaseRegion.swift in Sources */,
5698AC3B1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */,
5659F49C1EA8D989004A4992 /* Pool.swift in Sources */,
@@ -2371,6 +2460,7 @@
56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */,
56AFCA151CB1A8BB00F48B96 /* Persistable.swift in Sources */,
56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */,
5680520D2013209900E87861 /* RecordBox.swift in Sources */,
566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
5657AABD1D107001006283EF /* NSData.swift in Sources */,
5674A6E71F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
@@ -2397,6 +2487,7 @@
564448881EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56AFCA341CB1AA9900F48B96 /* RowFromDictionaryTests.swift in Sources */,
569C1EB61CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */,
568052202013297000E87861 /* RecordBoxTests.swift in Sources */,
562EA82B1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
5698AC4E1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
@@ -2405,6 +2496,7 @@
56AFCA371CB1AA9900F48B96 /* StatementColumnConvertibleFetchTests.swift in Sources */,
56AFCA381CB1AA9900F48B96 /* QueryInterfaceExpressionsTests.swift in Sources */,
56AFCA391CB1AA9900F48B96 /* SelectStatementTests.swift in Sources */,
56CC9240201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */,
56AFCA3A1CB1AA9900F48B96 /* UpdateStatementTests.swift in Sources */,
56AFCA3B1CB1AA9900F48B96 /* DatabaseMigratorTests.swift in Sources */,
5657AB4B1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
@@ -2430,8 +2522,10 @@
56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */,
566AD8CB1D531BED002EC1A8 /* TableDefinitionTests.swift in Sources */,
56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */,
56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */,
5657AB431D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
56AFCA4C1CB1AA9900F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
56CC9238201E009900CB597E /* DropWhileCursorTests.swift in Sources */,
56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
56176C751EACCCCA000F3F2B /* FTS5TokenizerTests.swift in Sources */,
56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */,
@@ -2448,8 +2542,10 @@
5657AB531D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
5698AC9B1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
56176C721EACCCCA000F3F2B /* FTS5PatternTests.swift in Sources */,
564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */,
5674A7101F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
56AFCA551CB1AA9900F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
5665F86E203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */,
5698ACBB1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
56AFCA561CB1AA9900F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */,
56AFCA571CB1AA9900F48B96 /* TransactionObserverTests.swift in Sources */,
@@ -2473,6 +2569,7 @@
56AFCA5E1CB1AA9900F48B96 /* RowConvertibleTests.swift in Sources */,
56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
56CC924E201E059100CB597E /* DropFirstCursorTests.swift in Sources */,
56AFCA611CB1AA9900F48B96 /* RecordEditedTests.swift in Sources */,
56AFCA621CB1AA9900F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */,
56A5EF141EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
@@ -2494,6 +2591,7 @@
565EFAF31D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
56AFCA671CB1AA9900F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
56AFCA681CB1AA9900F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
566A84482041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */,
56B14E841D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
56AFCA6B1CB1AA9900F48B96 /* DatabaseTimestampTests.swift in Sources */,
568068361EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
@@ -2513,9 +2611,10 @@
6340BF851E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
56AFCA751CB1AA9900F48B96 /* CGFloatTests.swift in Sources */,
562393531DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
56AFCA761CB1AA9900F48B96 /* StatementSelectionInfoTests.swift in Sources */,
56AFCA761CB1AA9900F48B96 /* DatabaseRegionTests.swift in Sources */,
5698ACA31DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
5691784A1CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */,
566A843220413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */,
56AFCA771CB1AA9900F48B96 /* GRDBTestCase.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -2536,6 +2635,7 @@
564448891EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56AFCA8D1CB1ABC800F48B96 /* RowFromDictionaryTests.swift in Sources */,
5657AB541D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
568052212013297000E87861 /* RecordBoxTests.swift in Sources */,
562EA82C1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
56DAA2D81DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
5698AC4F1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
@@ -2544,6 +2644,7 @@
56AFCA901CB1ABC800F48B96 /* StatementColumnConvertibleFetchTests.swift in Sources */,
5690C33D1D23E7D200E59934 /* FoundationDateTests.swift in Sources */,
5672DE6C1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */,
56CC9241201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */,
565F03C71CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */,
56AFCA911CB1ABC800F48B96 /* QueryInterfaceExpressionsTests.swift in Sources */,
56AFCA921CB1ABC800F48B96 /* SelectStatementTests.swift in Sources */,
@@ -2569,8 +2670,10 @@
569C1EB71CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */,
56AFCAA01CB1ABC800F48B96 /* RowFromStatementTests.swift in Sources */,
5690C32C1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */,
56CC925A201E094F00CB597E /* PrefixCursorTests.swift in Sources */,
56AFCAA21CB1ABC800F48B96 /* StatementArgumentsTests.swift in Sources */,
56AFCAA31CB1ABC800F48B96 /* RecordInitializersTests.swift in Sources */,
56CC9239201E009A00CB597E /* DropWhileCursorTests.swift in Sources */,
56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
56176C7B1EACCCCB000F3F2B /* FTS5TokenizerTests.swift in Sources */,
566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */,
@@ -2587,8 +2690,10 @@
56FF45461D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */,
5698AC9C1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
56176C781EACCCCB000F3F2B /* FTS5PatternTests.swift in Sources */,
564E73F2203DA2A4000C443C /* JoinSupportTests.swift in Sources */,
5674A70D1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
56AFCAAC1CB1ABC800F48B96 /* DatabaseValueConversionTests.swift in Sources */,
5665F86F203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */,
5698ACBC1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
5657AB441D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
5623935D1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
@@ -2612,6 +2717,7 @@
5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */,
56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */,
56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */,
56CC924F201E059100CB597E /* DropFirstCursorTests.swift in Sources */,
56AFCAB71CB1ABC800F48B96 /* RowConvertibleTests.swift in Sources */,
56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */,
56A5EF151EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
@@ -2633,6 +2739,7 @@
56AFCABF1CB1ABC800F48B96 /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
56AFCAC01CB1ABC800F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
56AFCAC11CB1ABC800F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
566A84492041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */,
56B14E851D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
56AFCAC41CB1ABC800F48B96 /* DatabaseTimestampTests.swift in Sources */,
568068371EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
@@ -2652,9 +2759,10 @@
6340BF861E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
567A80591D41350C00C7DCEC /* IndexInfoTests.swift in Sources */,
562393541DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
56AFCACF1CB1ABC800F48B96 /* StatementSelectionInfoTests.swift in Sources */,
56AFCACF1CB1ABC800F48B96 /* DatabaseRegionTests.swift in Sources */,
56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */,
5698ACA41DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
566A843320413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */,
565EFAF41D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
+79 -7
View File
@@ -45,6 +45,8 @@
5636E9C11D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; };
564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; };
564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; };
564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
@@ -87,6 +89,14 @@
566475D11D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; };
566475D51D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */; };
5665F869203EF4650084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */; };
566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; };
566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; };
566A843520413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; };
566A843620413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; };
566A84432041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */; };
566A84442041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */; };
566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; };
@@ -131,6 +141,10 @@
567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568052092013207000E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052072013206F00E87861 /* RecordBox.swift */; };
5680520E201320A200E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052072013206F00E87861 /* RecordBox.swift */; };
5680521A2013295600E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052182013295100E87861 /* RecordBoxTests.swift */; };
5680521B2013295700E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052182013295100E87861 /* RecordBoxTests.swift */; };
568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
56873BEE1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; };
@@ -175,6 +189,8 @@
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; };
5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; };
569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; };
56A4CDB31D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
@@ -212,6 +228,14 @@
56BF6D3F1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF6D2E1DEF47DA006039A3 /* Fixits-Swift2.swift */; };
56BF6D421DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF6D2E1DEF47DA006039A3 /* Fixits-Swift2.swift */; };
56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */; };
56CC923C201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */; };
56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */; };
56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */; };
56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; };
56CC9255201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; };
56CEB4F31EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; };
56CEB4F61EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; };
56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; };
@@ -305,7 +329,7 @@
F3BA80511CFB2B59003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; };
F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */; };
F3BA80531CFB2B59003DC1BA /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
F3BA80541CFB2B59003DC1BA /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; };
F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238711B9C75030082EB20 /* Database.swift */; };
F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; };
@@ -346,7 +370,7 @@
F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */; };
F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
F3BA80AE1CFB2FA6003DC1BA /* StatementSelectionInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */; };
F3BA80AE1CFB2FA6003DC1BA /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
F3BA80AF1CFB2FB1003DC1BA /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; };
@@ -513,7 +537,7 @@
5605F1521C672E4000235C62 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+RawRepresentable.swift"; sourceTree = "<group>"; };
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementSelectionInfoTests.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = "<group>"; };
5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
@@ -555,6 +579,7 @@
5636E9BB1D22574100B9B05F /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = "<group>"; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
@@ -580,6 +605,10 @@
566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSpecificExpressible+QueryInterface.swift"; sourceTree = "<group>"; };
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableChangesTests.swift; sourceTree = "<group>"; };
566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = "<group>"; };
566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = "<group>"; };
566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = "<group>"; };
@@ -607,6 +636,8 @@
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568052072013206F00E87861 /* RecordBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = "<group>"; };
568052182013295100E87861 /* RecordBoxTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBoxTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = "<group>"; };
@@ -637,6 +668,7 @@
5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = "<group>"; };
5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = "<group>"; };
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = "<group>"; };
569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryTests.swift; sourceTree = "<group>"; };
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = "<group>"; };
@@ -697,6 +729,10 @@
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLiteCustom/GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
56CC9248201E058900CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = "<group>"; };
56CC9253201E094600CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = "<group>"; };
56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = "<group>"; };
56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = "<group>"; };
@@ -856,9 +892,10 @@
560B3FA41C19DFF800C58EC7 /* Persistable */ = {
isa = PBXGroup;
children = (
566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */,
56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */,
5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */,
56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */,
56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableTests.swift */,
563363AA1C933FF8000BE133 /* PersistableTests.swift */,
);
@@ -1068,11 +1105,11 @@
569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */,
563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */,
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */,
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */,
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */,
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */,
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */,
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */,
5605F1861C69111300235C62 /* StatementSelectionInfoTests.swift */,
);
name = Private;
sourceTree = "<group>";
@@ -1080,6 +1117,7 @@
56A238111B9C74A90082EB20 /* Core */ = {
isa = PBXGroup;
children = (
5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */,
56DAA2C41DE99D8D006E10C8 /* Cursor */,
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */,
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */,
@@ -1091,6 +1129,7 @@
563363BB1C93FD32000BE133 /* DatabaseQueue */,
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
@@ -1161,8 +1200,10 @@
isa = PBXGroup;
children = (
56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */,
564E73E7203DA278000C443C /* JoinSupportTests.swift */,
560B3FA41C19DFF800C58EC7 /* Persistable */,
56176C9E1EACEDF9000F3F2B /* Record */,
568052182013295100E87861 /* RecordBoxTests.swift */,
5674A7251F30A8EF0095F066 /* RowConvertible */,
56176C9C1EACEA8C000F3F2B /* TableMapping */,
);
@@ -1183,7 +1224,9 @@
560A37A31C8F625000949E71 /* DatabasePool.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
@@ -1217,6 +1260,7 @@
560D92441C672C4B00F4F92B /* Persistable.swift */,
5674A6F31F307F600095F066 /* Persistable+Encodable.swift */,
56A238A11B9C753B0082EB20 /* Record.swift */,
568052072013206F00E87861 /* RecordBox.swift */,
56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */,
5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */,
56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */,
@@ -1245,11 +1289,15 @@
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */,
5623935F1DEE06D300A6B01F /* CursorTests.swift */,
56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */,
56CC9248201E058900CB597E /* DropFirstCursorTests.swift */,
56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */,
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */,
562393561DEE013C00A6B01F /* FilterCursorTests.swift */,
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */,
562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */,
562393711DEE104400A6B01F /* MapCursorTests.swift */,
56CC9253201E094600CB597E /* PrefixCursorTests.swift */,
56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */,
);
name = Cursor;
sourceTree = "<group>";
@@ -1644,6 +1692,7 @@
566B91281FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
56CEB5161EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */,
56CEB4F61EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */,
@@ -1661,6 +1710,7 @@
F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */,
F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */,
F3BA80161CFB2876003DC1BA /* Row.swift in Sources */,
569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */,
F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */,
564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */,
5659F49D1EA8D989004A4992 /* Pool.swift in Sources */,
@@ -1717,6 +1767,7 @@
F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */,
F3BA80361CFB28A4003DC1BA /* TableMapping.swift in Sources */,
F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
5680520E201320A200E87861 /* RecordBox.swift in Sources */,
566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
5657AABE1D107001006283EF /* NSData.swift in Sources */,
5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
@@ -1743,6 +1794,7 @@
5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */,
F3BA80BE1CFB2FD1003DC1BA /* DatabasePoolReadOnlyTests.swift in Sources */,
5680521B2013295700E87861 /* RecordBoxTests.swift in Sources */,
562EA82D1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
F3BA80C61CFB2FD8003DC1BA /* DatabaseQueueConcurrencyTests.swift in Sources */,
F3BA81161CFB305E003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
@@ -1751,6 +1803,7 @@
F3BA810A1CFB3056003DC1BA /* FoundationNSDateTests.swift in Sources */,
5657AB4D1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
5627564A1E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
56CC923C201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */,
F3BA80E51CFB3011003DC1BA /* DatabaseFunctionTests.swift in Sources */,
F3BA80531CFB2B59003DC1BA /* DataMemoryTests.swift in Sources */,
F3BA80511CFB2B59003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
@@ -1776,8 +1829,10 @@
F3BA80FD1CFB3024003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */,
F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
5657AB451D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
56CC9255201E094600CB597E /* PrefixCursorTests.swift in Sources */,
F3BA80EA1CFB3016003DC1BA /* RowFromStatementTests.swift in Sources */,
F3BA80AF1CFB2FB1003DC1BA /* DatabaseCollationTests.swift in Sources */,
56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */,
56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
F3BA80F31CFB301D003DC1BA /* StatementColumnConvertibleTests.swift in Sources */,
@@ -1794,8 +1849,10 @@
F3BA80DC1CFB300E003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5698AD021DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */,
56B964CA1DA521450002DA19 /* FTS5PatternTests.swift in Sources */,
564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */,
5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
5657AB551D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
5665F869203EF4650084C6C0 /* ColumnInfoTests.swift in Sources */,
F3BA81291CFB3063003DC1BA /* RecordInitializersTests.swift in Sources */,
56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
F3BA80F11CFB3019003DC1BA /* DatabaseSavepointTests.swift in Sources */,
@@ -1819,6 +1876,7 @@
F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */,
5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */,
56B964D21DA521450002DA19 /* FTS5RecordTests.swift in Sources */,
F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */,
56A5EF161EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
@@ -1838,8 +1896,9 @@
561667081D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */,
565EFAF51D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
F3BA81231CFB3063003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */,
F3BA80541CFB2B59003DC1BA /* StatementSelectionInfoTests.swift in Sources */,
F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */,
567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
566A84442041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */,
F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */,
F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */,
5698AC901DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
@@ -1862,6 +1921,7 @@
F3BA80B31CFB2FC9003DC1BA /* DatabaseQueueInMemoryTests.swift in Sources */,
F3BA80D91CFB300E003DC1BA /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
5698ACD51DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
566A843620413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */,
56B964DA1DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -1878,6 +1938,7 @@
566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
56CEB5131EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */,
56CEB4F31EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */,
@@ -1895,6 +1956,7 @@
F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */,
F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */,
F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */,
569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */,
F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */,
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */,
5659F49A1EA8D989004A4992 /* Pool.swift in Sources */,
@@ -1951,6 +2013,7 @@
F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */,
F3BA80921CFB2E7A003DC1BA /* TableMapping.swift in Sources */,
F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
568052092013207000E87861 /* RecordBox.swift in Sources */,
566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
5657AABB1D107001006283EF /* NSData.swift in Sources */,
5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
@@ -1977,6 +2040,7 @@
564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
5698ACCB1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */,
56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
5680521A2013295600E87861 /* RecordBoxTests.swift in Sources */,
562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
56B021CC1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */,
@@ -1985,6 +2049,7 @@
566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */,
56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */,
F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */,
56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */,
562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */,
F3BA80F61CFB301E003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */,
@@ -2010,8 +2075,10 @@
F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */,
562393481DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */,
5657AB511D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */,
562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */,
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */,
56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */,
56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */,
@@ -2028,8 +2095,10 @@
5698ACD11DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
562205FB1E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
5657AB611D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */,
5674A70C1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
5698AC8C1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */,
F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */,
56FF45431D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */,
F3BA80F01CFB3017003DC1BA /* RowConvertibleTests.swift in Sources */,
@@ -2053,11 +2122,12 @@
F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */,
56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */,
5623936C1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */,
56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
F3BA80B21CFB2FC5003DC1BA /* DatabaseTests.swift in Sources */,
F3BA80AE1CFB2FA6003DC1BA /* StatementSelectionInfoTests.swift in Sources */,
F3BA80AE1CFB2FA6003DC1BA /* DatabaseRegionTests.swift in Sources */,
F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */,
5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */,
@@ -2074,6 +2144,7 @@
565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */,
F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */,
566A84432041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */,
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */,
F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */,
@@ -2096,6 +2167,7 @@
5698AD011DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */,
F3BA80B51CFB2FCA003DC1BA /* DatabaseQueueInMemoryTests.swift in Sources */,
56A4CDB31D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
566A843520413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */,
F3BA80DF1CFB300F003DC1BA /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -41,7 +41,8 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
+13 -6
View File
@@ -13,7 +13,7 @@ default: test
# Requirements
# ============
#
# Xcode 8.3.3, with iOS8.1 Simulator installed
# Xcode >= 9.0, with iOS8.1 Simulator installed
# CocoaPods ~> 1.2.0 - https://cocoapods.org
# Carthage ~> 0.20.1 - https://github.com/carthage/carthage
# Jazzy ~> 0.7.4 - https://github.com/realm/jazzy
@@ -29,6 +29,7 @@ XCODEBUILD := set -o pipefail && $(shell command -v xcodebuild)
XCODEVERSION_FULL := $(word 2, $(shell xcodebuild -version))
XCODEVERSION_MAJOR := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f1)
XCODEVERSION_MINOR := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f2)
XCODEVERSION_PATCH := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f3)
# The Xcode Version, containing only the "MAJOR.MINOR" (ex. "8.3" for Xcode 8.3, 8.3.1, etc.)
XCODEVERSION := $(XCODEVERSION_MAJOR).$(XCODEVERSION_MINOR)
@@ -49,9 +50,15 @@ MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=8.1"
ifeq ($(XCODEVERSION),9.2)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.2"
else ifeq ($(XCODEVERSION),9.1)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.1"
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.1"
else ifeq ($(XCODEVERSION),9.0)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
ifeq ($(XCODEVERSION_PATCH),1)
# Xcode 9.0.1: @groue's personal computer
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0.1"
else
# Xcode 9.0: Travis https://docs.travis-ci.com/user/reference/osx/#Xcode-9.0
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
endif
else
# Xcode < 9.0 is not supported
endif
@@ -296,10 +303,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.4.2 \
--module-version 2.4 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.9.0 \
--module-version 2.9 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/2.4/ \
--root-url http://groue.github.io/GRDB.swift/docs/2.9/ \
--output Documentation/Reference \
--podspec GRDB.swift.podspec
else
+913 -331
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.4.2</string>
<string>2.9.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+17
View File
@@ -10,15 +10,32 @@
- [ ] REGEXP https://www.sqlite.org/lang_expr.html
- [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html
- [ ] Write regression tests for #156 and #157
- [ ] Allow concurrent reads from a snapshot
- [ ] Decode NSDecimalNumber from text database values
GRDB 3.0
- [ ] Refactor SQL generation and rowId extraction from expression on the visitor pattern. Provide more documentation for literal expressions which become the only way to extend GRDB.
- [ ] Hide useless scheduling methods behind protocols : https://forums.swift.org/t/discouraging-protocol-methods-on-concrete-values/8737/4?u=gwendal.roue
- [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970
- [ ] Do one of those two:
1. Make save() impossible to customize: remove it from Persistable protocol, and remove performSave() from tne public API.
2. Open Record.save(), and have RecordBox.save() forward this method to its underlying type.
- [ ] Not sure: Make the MutablePersistable.update(_:columns:) method mutating (as support for an updatedDate column)
- [ ] Not sure: type safety
- [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types.
- [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths?
- [ ] Rename Request to FetchRequest, because Request is a bad name: https://github.com/swift-server/http/pull/7#issuecomment-308448528
- [ ] Rename RowConvertible, TableMapping, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord?
- [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files.
- [ ] Drop IteratorCursor, use AnyCursor instead
- [ ] Drop TypedRequest, have FetchRequest defaults to Row requests.
- [ ] Rename columnCount -> numberOfColumns
- [ ] Try to remove double Persistable/MutablePersistable protocols: Would non-mutating Record methods help?
Not sure
- [ ] encode/decode nested records/arrays/dictionaries as JSON?
- [ ] Think about supporting Cursor's underestimatedCount, which could speed up Array(cursor) and fetchAll()
- [ ] Support for OR ROLLBACK, and mismatch between the Swift depth and the SQLite depth of nested transactions/savepoint:
+124
View File
@@ -0,0 +1,124 @@
import XCTest
#if GRDBCIPHER
@testable import GRDBCipher
#elseif GRDBCUSTOMSQLITE
@testable import GRDBCustomSQLite
#else
#if SWIFT_PACKAGE
import CSQLite
#else
import SQLite3
#endif
@testable import GRDB
#endif
class ColumnInfoTests: GRDBTestCase {
func testColumnInfo() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("""
CREATE TABLE t (
a INT,
b TEXT,
c VARCHAR(10),
d int DEFAULT NULL,
e Text NOT NULL DEFAULT 'foo',
"fooéı👨👨🏿🇫🇷🇨🇮" INT DEFAULT 0,
g INT DEFAULT 1e6,
h REAL DEFAULT 1.0,
i DATETIME DEFAULT CURRENT_TIMESTAMP,
j DATE DEFAULT (DATETIME('now', 'localtime')),
"" fooéı👨👨🏿🇫🇷🇨🇮,
PRIMARY KEY(c, a)
)
""")
let columns = try db.columns(in: "t")
XCTAssertEqual(columns.count, 11)
XCTAssertEqual(columns[0].name, "a")
XCTAssertEqual(columns[0].isNotNull, false)
XCTAssertEqual(columns[0].type, "INT")
// D. Richard Hipp wrote in SQLite mailing list on Tue Apr 30 22:43:47 EDT 2013 (http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html):
//
// > Re: Incorrect documentation for PRAGMA table_info (pk column)
// >
// > For SQLite 3.7.15 and earlier, the "pk" columns meaning was undocumented
// > and hence undefined. As it happened it was always 1. Beginning with
// > SQLite 3.7.16 we defined the meaning of the "pk" column to be the 1-based
// > index of the column in the primary key.
//
// https://sqlite.org/releaselog/3_7_16.html
//
// > Enhance the PRAGMA table_info command so that the "pk" column
// > is an increasing integer to show the order of columns in the
// > primary key.
if sqlite3_libversion_number() < 3007016 {
XCTAssertEqual(columns[0].primaryKeyIndex, 1)
} else {
XCTAssertEqual(columns[0].primaryKeyIndex, 2)
}
XCTAssertNil(columns[0].defaultValueSQL)
XCTAssertEqual(columns[1].name, "b")
XCTAssertEqual(columns[1].isNotNull, false)
XCTAssertEqual(columns[1].type, "TEXT")
XCTAssertEqual(columns[1].primaryKeyIndex, 0)
XCTAssertNil(columns[1].defaultValueSQL)
XCTAssertEqual(columns[2].name, "c")
XCTAssertEqual(columns[2].isNotNull, false)
XCTAssertEqual(columns[2].type, "VARCHAR(10)")
XCTAssertEqual(columns[2].primaryKeyIndex, 1)
XCTAssertNil(columns[2].defaultValueSQL)
XCTAssertEqual(columns[3].name, "d")
XCTAssertEqual(columns[3].isNotNull, false)
XCTAssertEqual(columns[3].type, "int")
XCTAssertEqual(columns[3].primaryKeyIndex, 0)
XCTAssertEqual(columns[3].defaultValueSQL, "NULL")
XCTAssertEqual(columns[4].name, "e")
XCTAssertEqual(columns[4].isNotNull, true)
XCTAssertEqual(columns[4].type, "Text")
XCTAssertEqual(columns[4].primaryKeyIndex, 0)
XCTAssertEqual(columns[4].defaultValueSQL, "'foo'")
XCTAssertEqual(columns[5].name, "fooéı👨👨🏿🇫🇷🇨🇮")
XCTAssertEqual(columns[5].isNotNull, false)
XCTAssertEqual(columns[5].type, "INT")
XCTAssertEqual(columns[5].primaryKeyIndex, 0)
XCTAssertEqual(columns[5].defaultValueSQL, "0")
XCTAssertEqual(columns[6].name, "g")
XCTAssertEqual(columns[6].isNotNull, false)
XCTAssertEqual(columns[6].type, "INT")
XCTAssertEqual(columns[6].primaryKeyIndex, 0)
XCTAssertEqual(columns[6].defaultValueSQL, "1e6")
XCTAssertEqual(columns[7].name, "h")
XCTAssertEqual(columns[7].isNotNull, false)
XCTAssertEqual(columns[7].type, "REAL")
XCTAssertEqual(columns[7].primaryKeyIndex, 0)
XCTAssertEqual(columns[7].defaultValueSQL, "1.0")
XCTAssertEqual(columns[8].name, "i")
XCTAssertEqual(columns[8].isNotNull, false)
XCTAssertEqual(columns[8].type, "DATETIME")
XCTAssertEqual(columns[8].primaryKeyIndex, 0)
XCTAssertEqual(columns[8].defaultValueSQL, "CURRENT_TIMESTAMP")
XCTAssertEqual(columns[9].name, "j")
XCTAssertEqual(columns[9].isNotNull, false)
XCTAssertEqual(columns[9].type, "DATE")
XCTAssertEqual(columns[9].primaryKeyIndex, 0)
XCTAssertEqual(columns[9].defaultValueSQL, "DATETIME('now', 'localtime')")
XCTAssertEqual(columns[10].name, "")
XCTAssertEqual(columns[10].isNotNull, false)
XCTAssertEqual(columns[10].type, "fooéı👨👨🏿🇫🇷🇨🇮")
XCTAssertEqual(columns[10].primaryKeyIndex, 0)
XCTAssertNil(columns[10].defaultValueSQL)
}
}
}
@@ -192,12 +192,8 @@ private class UserTypedRequest2<T> : TypedRequest {
private class UserTransactionObserver : TransactionObserver {
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseWillCommit() throws { }
func databaseDidCommit(_ db: Database) { }
func databaseDidRollback(_ db: Database) { }
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
}
// MARK: - VirtualTableModule
+68
View File
@@ -28,6 +28,13 @@ class CursorTests: GRDBTestCase {
}
}
func testDropLast() {
XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(0) == [1, 2, 3, 4, 5])
XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(2) == [1, 2, 3])
XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(10) == [])
XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast() == [1, 2, 3, 4])
}
func testContainsIsLazy() {
func makeCursor() -> AnyCursor<Int> {
var i = 0
@@ -103,9 +110,70 @@ class CursorTests: GRDBTestCase {
}
}
func testJoinedWithSeparator() throws {
do {
let x = try IteratorCursor([String]()).joined()
XCTAssertEqual(x, "")
}
do {
let x = try IteratorCursor([String]()).joined(separator: "><")
XCTAssertEqual(x, "")
}
do {
let x = try IteratorCursor(["foo"]).joined()
XCTAssertEqual(x, "foo")
}
do {
let x = try IteratorCursor(["foo"]).joined(separator: "><")
XCTAssertEqual(x, "foo")
}
do {
let x = try IteratorCursor(["foo", "bar", "baz"]).joined()
XCTAssertEqual(x, "foobarbaz")
}
do {
let x = try IteratorCursor(["foo", "bar", "baz"]).joined(separator: "><")
XCTAssertEqual(x, "foo><bar><baz")
}
}
func testMax() {
XCTAssertEqual(try IteratorCursor([1, 2, 3]).max(), 3)
XCTAssertEqual(try IteratorCursor([1, 2, 3]).max(by: >), 1)
}
func testMin() {
XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(), 1)
XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(by: >), 3)
}
func testReduce() throws {
let cursor = IteratorCursor([1, 2])
let squareSum = try cursor.reduce(0) { (acc, int) in acc + int * int }
XCTAssertEqual(squareSum, 5)
}
func testReduceInto() throws {
let cursor = IteratorCursor([1, 2])
let squareSum = try cursor.reduce(into: 0) { (acc, int) in acc += int * int }
XCTAssertEqual(squareSum, 5)
}
func testSuffix() throws {
do {
let cursor = IteratorCursor([1, 2, 3, 4, 5])
let suffix = try cursor.suffix(0)
XCTAssertTrue(suffix == [])
}
do {
let cursor = IteratorCursor([1, 2, 3, 4, 5])
let suffix = try cursor.suffix(2)
XCTAssertTrue(suffix == [4, 5])
}
do {
let cursor = IteratorCursor([1, 2, 3, 4, 5])
let suffix = try cursor.suffix(10)
XCTAssertTrue(suffix == [1, 2, 3, 4, 5])
}
}
}
@@ -865,6 +865,38 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
}
}
func testLongRunningReadTransaction() throws {
// A test for a "user-defined" DatabaseSnapshot based on DatabaseQueue
let dbName = "test.sqlite"
let dbPool = try makeDatabasePool(filename: dbName)
dbConfiguration.allowsUnsafeTransactions = true
dbConfiguration.readonly = true
let dbQueue = try makeDatabaseQueue(filename: dbName)
try dbPool.write { db in
try db.create(table: "t") { $0.column("id", .integer).primaryKey() }
try db.execute("INSERT INTO t DEFAULT VALUES")
}
try dbQueue.inDatabase { db in
try db.beginTransaction(.deferred)
}
try dbQueue.inDatabase { db in
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
}
try dbPool.write { db in
try db.execute("INSERT INTO t DEFAULT VALUES")
}
try dbQueue.inDatabase { db in
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
try db.rollback()
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 2)
}
}
func testIssue80() throws {
// See https://github.com/groue/GRDB.swift/issues/80
+13
View File
@@ -90,4 +90,17 @@ class DatabaseQueueTests: GRDBTestCase {
XCTAssertEqual(error.description.lowercased(), "sqlite error 1 with statement `create table files_fail (name text collate test_collation_foo)`: no such collation sequence: test_collation_foo")
}
}
func testAllowsUnsafeTransactions() throws {
dbConfiguration.allowsUnsafeTransactions = true
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.beginTransaction()
}
try dbQueue.inDatabase { db in
try db.commit()
}
}
}
+765
View File
@@ -0,0 +1,765 @@
import XCTest
#if GRDBCIPHER
@testable import GRDBCipher
#elseif GRDBCUSTOMSQLITE
@testable import GRDBCustomSQLite
#else
#if SWIFT_PACKAGE
import CSQLite
#else
import SQLite3
#endif
@testable import GRDB
#endif
class DatabaseRegionTests : GRDBTestCase {
func testRegionEquatable() {
// An array of distinct selection infos
let regions = [
DatabaseRegion.fullDatabase,
DatabaseRegion(),
DatabaseRegion(table: "foo"),
DatabaseRegion(table: "FOO"), // selection info is case-sensitive on table name
DatabaseRegion(table: "foo", columns: ["a", "b"]),
DatabaseRegion(table: "foo", columns: ["A", "B"]), // selection info is case-sensitive on columns names
DatabaseRegion(table: "foo", columns: ["b", "c"]),
DatabaseRegion(table: "foo", rowIds: [1, 2]),
DatabaseRegion(table: "foo", rowIds: [2, 3]),
DatabaseRegion(table: "bar")]
for (i1, s1) in regions.enumerated() {
for (i2, s2) in regions.enumerated() {
if i1 == i2 {
XCTAssertEqual(s1, s2)
} else {
XCTAssertNotEqual(s1, s2)
}
}
}
}
func testRegionUnion() {
let regions = [
DatabaseRegion.fullDatabase,
DatabaseRegion(),
DatabaseRegion(table: "foo"),
DatabaseRegion(table: "foo", columns: ["a", "b"]),
DatabaseRegion(table: "foo", columns: ["b", "c"]),
DatabaseRegion(table: "foo", rowIds: [1, 2]),
DatabaseRegion(table: "foo", rowIds: [2, 3]),
DatabaseRegion(table: "bar")]
var unions: [DatabaseRegion] = []
for s1 in regions {
for s2 in regions {
unions.append(s1.union(s2))
}
}
XCTAssertEqual(unions.map { $0.description }, [
"full database",
"full database",
"full database",
"full database",
"full database",
"full database",
"full database",
"full database",
"full database",
"empty",
"foo(*)",
"foo(a,b)",
"foo(b,c)",
"foo(*)[1,2]",
"foo(*)[2,3]",
"bar(*)",
"full database",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)",
"bar(*),foo(*)",
"full database",
"foo(a,b)",
"foo(*)",
"foo(a,b)",
"foo(a,b,c)",
"foo(*)",
"foo(*)",
"bar(*),foo(a,b)",
"full database",
"foo(b,c)",
"foo(*)",
"foo(a,b,c)",
"foo(b,c)",
"foo(*)",
"foo(*)",
"bar(*),foo(b,c)",
"full database",
"foo(*)[1,2]",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)[1,2]",
"foo(*)[1,2,3]",
"bar(*),foo(*)[1,2]",
"full database",
"foo(*)[2,3]",
"foo(*)",
"foo(*)",
"foo(*)",
"foo(*)[1,2,3]",
"foo(*)[2,3]",
"bar(*),foo(*)[2,3]",
"full database",
"bar(*)",
"bar(*),foo(*)",
"bar(*),foo(a,b)",
"bar(*),foo(b,c)",
"bar(*),foo(*)[1,2]",
"bar(*),foo(*)[2,3]",
"bar(*)"])
}
func testRegionUnionOfColumnsAndRows() {
let regions = [
DatabaseRegion(table: "foo", columns: ["a"]).intersection(DatabaseRegion(table: "foo", rowIds: [1])),
DatabaseRegion(table: "foo", columns: ["b"]).intersection(DatabaseRegion(table: "foo", rowIds: [2])),
]
var unions: [DatabaseRegion] = []
for s1 in regions {
for s2 in regions {
unions.append(s1.union(s2))
}
}
XCTAssertEqual(unions.map { $0.description }, ["foo(a)[1]", "foo(a,b)[1,2]", "foo(a,b)[1,2]", "foo(b)[2]"])
}
func testRegionIntersection() {
let regions = [
DatabaseRegion.fullDatabase,
DatabaseRegion(),
DatabaseRegion(table: "foo"),
DatabaseRegion(table: "foo", columns: ["a", "b"]),
DatabaseRegion(table: "foo", columns: ["b", "c"]),
DatabaseRegion(table: "foo", rowIds: [1, 2]),
DatabaseRegion(table: "foo", rowIds: [2, 3]),
DatabaseRegion(table: "bar")]
var intersection: [DatabaseRegion] = []
for s1 in regions {
for s2 in regions {
intersection.append(s1.intersection(s2))
}
}
XCTAssertEqual(intersection.map { $0.description }, [
"full database",
"empty",
"foo(*)",
"foo(a,b)",
"foo(b,c)",
"foo(*)[1,2]",
"foo(*)[2,3]",
"bar(*)",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"foo(*)",
"empty",
"foo(*)",
"foo(a,b)",
"foo(b,c)",
"foo(*)[1,2]",
"foo(*)[2,3]",
"empty",
"foo(a,b)",
"empty",
"foo(a,b)",
"foo(a,b)",
"foo(b)",
"foo(a,b)[1,2]",
"foo(a,b)[2,3]",
"empty",
"foo(b,c)",
"empty",
"foo(b,c)",
"foo(b)",
"foo(b,c)",
"foo(b,c)[1,2]",
"foo(b,c)[2,3]",
"empty",
"foo(*)[1,2]",
"empty",
"foo(*)[1,2]",
"foo(a,b)[1,2]",
"foo(b,c)[1,2]",
"foo(*)[1,2]",
"foo(*)[2]",
"empty",
"foo(*)[2,3]",
"empty",
"foo(*)[2,3]",
"foo(a,b)[2,3]",
"foo(b,c)[2,3]",
"foo(*)[2]",
"foo(*)[2,3]",
"empty",
"bar(*)",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"bar(*)"])
}
func testRegionIntersectionOfColumnsAndRows() {
let regions = [
DatabaseRegion(table: "foo", columns: ["a"]).intersection(DatabaseRegion(table: "foo", rowIds: [1])),
DatabaseRegion(table: "foo", columns: ["b"]).intersection(DatabaseRegion(table: "foo", rowIds: [2])),
]
var intersection: [DatabaseRegion] = []
for s1 in regions {
for s2 in regions {
intersection.append(s1.intersection(s2))
}
}
XCTAssertEqual(intersection.map { $0.description }, ["foo(a)[1]", "empty", "empty", "foo(b)[2]"])
}
func testSelectStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, name TEXT)")
try db.execute("CREATE TABLE bar (id INTEGER, fooId INTEGER)")
do {
let statement = try db.makeSelectStatement("SELECT foo.name FROM FOO JOIN BAR ON fooId = foo.id")
let expectedRegion = DatabaseRegion(table: "foo", columns: ["name", "id"])
.union(DatabaseRegion(table: "bar", columns: ["fooId"]))
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "bar(fooId),foo(id,name)")
}
do {
let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM foo")
if sqlite3_libversion_number() < 3019000 {
let expectedRegion = DatabaseRegion.fullDatabase
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "full database")
} else {
let expectedRegion = DatabaseRegion(table: "foo")
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "foo(*)")
}
}
}
}
func testRegionRowIds() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)")
struct Record: TableMapping {
static let databaseTableName = "foo"
}
// Undefined rowIds
do {
let request = Record.all()
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)")
}
do {
let request = Record.filter(Column("a") == 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)")
}
do {
let request = Record.filter(Column("id") >= 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)")
}
do {
let request = Record.filter((Column("id") == 1) || (Column("a") == "foo"))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)")
}
// No rowId
do {
let request = Record.filter(Column("id") == nil)
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter(Column("id") === nil)
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter(nil == Column("id"))
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter(nil === Column("id"))
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter((Column("id") == 1) && (Column("id") == 2))
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
do {
let request = Record.filter(key: 1).filter(key: 2)
try XCTAssertEqual(request.fetchedRegion(db).description, "empty")
}
// Single rowId
do {
let request = Record.filter(Column("id") == 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(Column("id") === 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(Column("id") == 1 && Column("a") == "foo")
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(Column.rowID == 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(1 == Column("id"))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(1 === Column("id"))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(1 === Column.rowID)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(key: 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(key: 1).filter(key: 1)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
do {
let request = Record.filter(key: 1).filter(Column("a") == "foo")
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]")
}
// Multiple rowIds
do {
let request = Record.filter(Column("id") == 1 || Column.rowID == 2)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2]")
}
do {
let request = Record.filter((Column("id") == 1 && Column("a") == "foo") || Column.rowID == 2)
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2]")
}
do {
let request = Record.filter([1, 2, 3].contains(Column("id")))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let request = Record.filter([1, 2, 3].contains(Column.rowID))
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let request = Record.filter(keys: [1, 2, 3])
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
}
}
func testDatabaseRegionOfDerivedRequests() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)")
struct Record: TableMapping {
static let databaseTableName = "foo"
}
let request = Record.filter(keys: [1, 2, 3])
try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
do {
let derivedRequest: AnyRequest = AnyRequest(request)
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let derivedRequest: AnyTypedRequest<Record> = AnyTypedRequest(request)
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let derivedRequest: AnyTypedRequest<Row> = request.asRequest(of: Row.self)
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let derivedRequest: AdaptedTypedRequest = request.adapted { db in SuffixRowAdapter(fromIndex: 1) }
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
let derivedRequest: AdaptedRequest = AnyRequest(request).adapted { db in SuffixRowAdapter(fromIndex: 1) }
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
// SQL request loses region info
let derivedRequest: SQLRequest = try request.asSQLRequest(db)
try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)")
}
}
}
func testUpdateStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
let statement = try db.makeUpdateStatement("UPDATE foo SET bar = 'bar', baz = 'baz' WHERE id = 1")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
XCTAssertEqual(columnNames, Set(["bar", "baz"]))
}
}
func testRowIdNameInSelectStatement() throws {
// Here we test that sqlite authorizer gives the "ROWID" name to
// the rowid column, regardless of its name in the request (rowid, oid, _rowid_)
//
// See also testRowIdNameInUpdateStatement
guard sqlite3_libversion_number() < 3019003 else {
// This test fails on SQLite 3.19.3 (iOS 11.2) and SQLite 3.21.0 (custom build),
// but succeeds on SQLite 3.16.0 (iOS 10.3.1).
// TODO: evaluate the consequences
return
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (name TEXT)")
do {
let statement = try db.makeSelectStatement("SELECT rowid FROM FOO")
let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"])
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)")
}
do {
let statement = try db.makeSelectStatement("SELECT _ROWID_ FROM FOO")
let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"])
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)")
}
do {
let statement = try db.makeSelectStatement("SELECT oID FROM FOO")
let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"])
XCTAssertEqual(statement.fetchedRegion, expectedRegion)
XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)")
}
}
}
func testRowIdNameInUpdateStatement() throws {
// Here we test that sqlite authorizer gives the "ROWID" name to
// the rowid column, regardless of its name in the request (rowid, oid, _rowid_)
//
// See also testRowIdNameInSelectStatement
guard sqlite3_libversion_number() > 3007013 else {
// This test fails on iOS 8.1 (SQLite 3.7.13)
// TODO: evaluate the consequences
return
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (name TEXT)")
do {
let statement = try db.makeUpdateStatement("UPDATE foo SET rowid = 1")
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
XCTAssertEqual(columnNames, ["ROWID"])
}
do {
let statement = try db.makeUpdateStatement("UPDATE foo SET _ROWID_ = 1")
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
XCTAssertEqual(columnNames, ["ROWID"])
}
do {
let statement = try db.makeUpdateStatement("UPDATE foo SET oID = 1")
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
XCTAssertEqual(columnNames, ["ROWID"])
}
}
}
func testInsertStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
let statement = try db.makeUpdateStatement("INSERT INTO foo (id, bar) VALUES (1, 'bar')")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .insert(let tableName) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
}
}
func testDeleteStatement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
let statement = try db.makeUpdateStatement("DELETE FROM foo")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
XCTAssertEqual(statement.databaseEventKinds.count, 1)
guard case .delete(let tableName) = statement.databaseEventKinds[0] else {
XCTFail()
return
}
XCTAssertEqual(tableName, "foo")
}
}
func testUpdateStatementInvalidatesDatabaseSchemaCache() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let statement = try db.makeUpdateStatement("CREATE TABLE foo (id INTEGER)")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
try statement.execute()
}
do {
let statement = try db.makeUpdateStatement("ALTER TABLE foo ADD COLUMN name TEXT")
XCTAssertTrue(statement.invalidatesDatabaseSchemaCache)
}
do {
let statement = try db.makeUpdateStatement("DROP TABLE foo")
XCTAssertTrue(statement.invalidatesDatabaseSchemaCache)
}
}
}
func testRegionIsModifiedByDatabaseEvent() {
do {
// Empty selection
let region = DatabaseRegion()
XCTAssertEqual(region.description, "empty")
do {
let eventKind = DatabaseEventKind.insert(tableName: "foo")
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.delete(tableName: "foo")
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.update(tableName: "foo", columnNames: ["a", "b"])
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
}
do {
// Full database selection
let region = DatabaseRegion.fullDatabase
XCTAssertEqual(region.description, "full database")
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.insert(tableName: tableName)
let event = DatabaseEvent(kind: .insert, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event))
}
}
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.delete(tableName: tableName)
let event = DatabaseEvent(kind: .delete, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event))
}
}
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.update(tableName: tableName, columnNames: ["a", "b"])
let event = DatabaseEvent(kind: .update, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event))
}
}
}
do {
// Complex selection
let region = DatabaseRegion(table: "foo")
.union(DatabaseRegion(table: "bar", columns: ["a"])
.intersection(DatabaseRegion(table: "bar", rowIds: [1])))
XCTAssertEqual(region.description, "bar(a)[1],foo(*)")
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.insert(tableName: tableName)
let event1 = DatabaseEvent(kind: .insert, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .insert, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertTrue(region.isModified(by: event2))
}
}
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.delete(tableName: tableName)
let event1 = DatabaseEvent(kind: .delete, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .delete, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertTrue(region.isModified(by: event2))
}
}
do {
let tableName = "foo"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.update(tableName: tableName, columnNames: ["a", "b"])
let event1 = DatabaseEvent(kind: .update, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .update, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertTrue(region.isModified(by: event2))
}
}
do {
let tableName = "bar"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.insert(tableName: tableName)
let event1 = DatabaseEvent(kind: .insert, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .insert, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertFalse(region.isModified(by: event2))
}
}
do {
let tableName = "bar"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.delete(tableName: tableName)
let event1 = DatabaseEvent(kind: .delete, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .delete, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertFalse(region.isModified(by: event2))
}
}
do {
let tableName = "bar"
tableName.withCString { tableNameCString in
let eventKind = DatabaseEventKind.update(tableName: tableName, columnNames: ["a", "b"])
let event1 = DatabaseEvent(kind: .update, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString)
let event2 = DatabaseEvent(kind: .update, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString)
XCTAssertTrue(region.isModified(byEventsOfKind: eventKind))
XCTAssertTrue(region.isModified(by: event1))
XCTAssertFalse(region.isModified(by: event2))
}
}
do {
let eventKind = DatabaseEventKind.update(tableName: "bar", columnNames: ["b", "c"])
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.insert(tableName: "qux")
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.delete(tableName: "qux")
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
do {
let eventKind = DatabaseEventKind.update(tableName: "qux", columnNames: ["a", "b"])
XCTAssertFalse(region.isModified(byEventsOfKind: eventKind))
// Can't test for individual events due to DatabaseRegion.isModified(by:) precondition
}
}
}
}
@@ -42,9 +42,6 @@ private class Observer : TransactionObserver {
allRecordedEvents.append(event.copy())
}
func databaseWillCommit() throws {
}
func databaseDidCommit(_ db: Database) {
}
+137
View File
@@ -0,0 +1,137 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
class DatabaseSnapshotTests: GRDBTestCase {
func testSnapshotIsReadOnly() throws {
let dbPool = try makeDatabasePool()
let snapshot = try dbPool.makeSnapshot()
do {
try snapshot.read { db in
try db.create(table: "t") { $0.column("id", .integer).primaryKey() }
}
XCTFail("Expected error")
} catch is DatabaseError {
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func testSnapshotSeesLatestTransaction() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.create(table: "t") { $0.column("id", .integer).primaryKey() }
try db.execute("INSERT INTO t DEFAULT VALUES")
let snapshot = try dbPool.makeSnapshot()
try snapshot.read { db in
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
}
try db.execute("INSERT INTO t DEFAULT VALUES")
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 2)
try snapshot.read { db in
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
}
}
}
func testSnapshotDoesNotSeeUncommittedTransaction() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.create(table: "t") { $0.column("id", .integer).primaryKey() }
try db.beginTransaction()
try db.execute("INSERT INTO t DEFAULT VALUES")
let snapshot = try dbPool.makeSnapshot()
try db.commit()
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
try snapshot.read { db in
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 0)
}
}
}
func testSnapshotCreatedOutsideOfWriterQueue() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.create(table: "t") { $0.column("id", .integer).primaryKey() }
try db.execute("INSERT INTO t DEFAULT VALUES")
}
let snapshot = try dbPool.makeSnapshot()
try snapshot.read { db in
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
}
try dbPool.write { db in
try db.execute("INSERT INTO t DEFAULT VALUES")
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 2)
}
try snapshot.read { db in
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
}
}
func testSnapshotInheritPoolFunctions() throws {
let dbPool = try makeDatabasePool()
let function = DatabaseFunction("foo", argumentCount: 0, pure: true) { _ in return "foo" }
dbPool.add(function: function)
let snapshot = try dbPool.makeSnapshot()
try snapshot.read { db in
try XCTAssertEqual(String.fetchOne(db, "SELECT foo()")!, "foo")
}
}
func testSnapshotFunctions() throws {
let dbPool = try makeDatabasePool()
let snapshot = try dbPool.makeSnapshot()
let function = DatabaseFunction("foo", argumentCount: 0, pure: true) { _ in return "foo" }
snapshot.add(function: function)
try snapshot.read { db in
try XCTAssertEqual(String.fetchOne(db, "SELECT foo()")!, "foo")
}
}
func testSnapshotInheritPoolCollations() throws {
let dbPool = try makeDatabasePool()
let collation = DatabaseCollation("reverse") { (string1, string2) in
return (string1 == string2) ? .orderedSame : ((string1 < string2) ? .orderedDescending : .orderedAscending)
}
dbPool.add(collation: collation)
try dbPool.write { db in
try db.execute("CREATE TABLE items (text TEXT)")
try db.execute("INSERT INTO items (text) VALUES ('a')")
try db.execute("INSERT INTO items (text) VALUES ('b')")
try db.execute("INSERT INTO items (text) VALUES ('c')")
}
let snapshot = try dbPool.makeSnapshot()
try snapshot.read { db in
XCTAssertEqual(try String.fetchAll(db, "SELECT text FROM items ORDER BY text COLLATE reverse"), ["c", "b", "a"])
}
}
func testSnapshotCollations() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (text TEXT)")
try db.execute("INSERT INTO items (text) VALUES ('a')")
try db.execute("INSERT INTO items (text) VALUES ('b')")
try db.execute("INSERT INTO items (text) VALUES ('c')")
}
let snapshot = try dbPool.makeSnapshot()
let collation = DatabaseCollation("reverse") { (string1, string2) in
return (string1 == string2) ? .orderedSame : ((string1 < string2) ? .orderedDescending : .orderedAscending)
}
snapshot.add(collation: collation)
try snapshot.read { db in
XCTAssertEqual(try String.fetchAll(db, "SELECT text FROM items ORDER BY text COLLATE reverse"), ["c", "b", "a"])
}
}
}
+15
View File
@@ -298,4 +298,19 @@ class DatabaseTests : GRDBTestCase {
// Make sure we can open another transaction
try dbQueue.inTransaction { db in .commit }
}
func testExplicitTransactionManagement() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.beginTransaction()
XCTAssertEqual(lastSQLQuery, "BEGIN DEFERRED TRANSACTION")
try db.rollback()
XCTAssertEqual(lastSQLQuery, "ROLLBACK TRANSACTION")
try db.beginTransaction(.immediate)
XCTAssertEqual(lastSQLQuery, "BEGIN IMMEDIATE TRANSACTION")
try db.commit()
XCTAssertEqual(lastSQLQuery, "COMMIT TRANSACTION")
}
}
}
@@ -0,0 +1,82 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct TestError : Error { }
class DropFirstCursorTests: GRDBTestCase {
func testDropFirstCursorFromCursor() throws {
do {
let base = IteratorCursor([1, 2, 3, 4, 5])
let cursor = base.dropFirst(0)
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 2)
try XCTAssertEqual(cursor.next()!, 3)
try XCTAssertEqual(cursor.next()!, 4)
try XCTAssertEqual(cursor.next()!, 5)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 4, 5])
let cursor = base.dropFirst(2)
try XCTAssertEqual(cursor.next()!, 3)
try XCTAssertEqual(cursor.next()!, 4)
try XCTAssertEqual(cursor.next()!, 5)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 4, 5])
let cursor = base.dropFirst(10)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 4, 5])
let cursor = base.dropFirst()
try XCTAssertEqual(cursor.next()!, 2)
try XCTAssertEqual(cursor.next()!, 3)
try XCTAssertEqual(cursor.next()!, 4)
try XCTAssertEqual(cursor.next()!, 5)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
}
func testDropFirstCursorFromThrowingCursor() throws {
var i = 1
let base: AnyCursor<Int> = AnyCursor {
guard i < 3 else { throw TestError() }
defer { i += 1 }
return i
}
let cursor = base.dropFirst(1)
try XCTAssertEqual(cursor.next()!, 2)
do {
_ = try cursor.next()
XCTFail()
} catch is TestError {
} catch {
XCTFail()
}
}
func testDropFirstChain() throws {
let base = IteratorCursor([1, 2, 3, 4, 5])
let cursor = base.dropFirst(1).dropFirst(1)
try XCTAssertEqual(cursor.next()!, 3)
try XCTAssertEqual(cursor.next()!, 4)
try XCTAssertEqual(cursor.next()!, 5)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
}
@@ -0,0 +1,70 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct TestError : Error { }
class DropWhileCursorTests: GRDBTestCase {
func testDropWhileCursorFromCursor() throws {
do {
let base = IteratorCursor([1, 2, 3, 1, 5])
let cursor = base.drop(while: { $0 < 3 })
try XCTAssertEqual(cursor.next()!, 3)
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 5)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 1, 5])
let cursor = base.drop(while: { _ in true })
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 1, 5])
let cursor = base.drop(while: { _ in false })
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 2)
try XCTAssertEqual(cursor.next()!, 3)
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 5)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 1, 5])
let cursor = base.drop(while: { _ in throw TestError() })
_ = try cursor.next()
XCTFail()
} catch is TestError {
} catch {
XCTFail()
}
}
func testDropWhileCursorFromThrowingCursor() throws {
var i = 0
let base: AnyCursor<Int> = AnyCursor {
guard i < 4 else { throw TestError() }
defer { i += 1 }
return i
}
let cursor = base.drop(while: { $0 < 3 })
try XCTAssertEqual(cursor.next()!, 3)
do {
_ = try cursor.next()
XCTFail()
} catch is TestError {
} catch {
XCTFail()
}
}
}
+34 -2
View File
@@ -17,7 +17,7 @@ class FTS5PatternTests: GRDBTestCase {
t.column("author")
t.column("body")
}
try db.execute("INSERT INTO books (title, author, body) VALUES (?, ?, ?)", arguments: ["Moby Dick", "Herman Melville", "Call me Ishmael. Some years ago--never mind how long precisely--having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world."])
try db.execute("INSERT INTO books (title, author, body) VALUES (?, ?, ?)", arguments: ["Moby-Dick", "Herman Melville", "Call me Ishmael. Some years ago--never mind how long precisely--having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world."])
try db.execute("INSERT INTO books (title, author, body) VALUES (?, ?, ?)", arguments: ["Red Mars", "Kim Stanley Robinson", "History is not evolution! It is a false analogy! Evolution is a matter of environment and chance, acting over millions of years. But history is a matter of environment and choice, acting within lifetimes, and sometimes within years, or months, or days! History is Lamarckian!"])
try db.execute("INSERT INTO books (title, author, body) VALUES (?, ?, ?)", arguments: ["Querelle de Brest", "Jean Genet", "L’idée de mer évoque souvent l’idée de mer, de marins. Mer et marins ne se présentent pas alors avec la précision d’une image, le meurtre plutôt fait en nous l’émotion déferler par vagues."])
try db.execute("INSERT INTO books (title, author, body) VALUES (?, ?, ?)", arguments: ["Éden, Éden, Éden", "Pierre Guyotat", "/ Les soldats, casqués, jambes ouvertes, foulent, muscles retenus, les nouveau-nés emmaillotés dans les châles écarlates, violets : les bébés roulent hors des bras des femmes accroupies sur les tôles mitraillées des G. M. C. ;"])
@@ -59,7 +59,7 @@ class FTS5PatternTests: GRDBTestCase {
func testInvalidFTS5Pattern() throws {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
let invalidRawPatterns = ["", "?!", "^", "^foo", "NOT", "(", "AND", "OR", "\"", "missing:foo"]
let invalidRawPatterns = ["", "?!", "^", "NOT", "(", "AND", "OR", "\"", "missing:foo"]
for rawPattern in invalidRawPatterns {
do {
_ = try db.makeFTS5Pattern(rawPattern: rawPattern, forTable: "books")
@@ -161,5 +161,37 @@ class FTS5PatternTests: GRDBTestCase {
}
}
}
func testFTS5PatternWithPrefixPhrase() throws {
let wrongInputs = ["", "*", "^", " ", "(", "()", "\"", "?!"]
for string in wrongInputs {
if let pattern = FTS5Pattern(matchingPrefixPhrase: string) {
let rawPattern = String.fromDatabaseValue(pattern.databaseValue)!
XCTFail("Unexpected raw pattern \(String(reflecting: rawPattern)) from string \(String(reflecting: string))")
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
// Couples (pattern, expected raw pattern, expected count of matching rows)
let cases = [
("écarlates", "^\"écarlates\"", 0),
("^Moby-dick*", "^\"moby dick\"", 1),
("not evolution", "^\"not evolution\"", 0),
("HISTORY IS", "^\"history is\"", 1),
(" \t\nyears \t\nmonths \t\n", "^\"years months\"", 0),
("\"years months days\"", "^\"years months days\"", 0),
("FOOÉı👨👨🏿🇫🇷🇨🇮", "^\"fooÉı👨👨🏿🇫🇷🇨🇮\"", 0),
]
for (string, expectedRawPattern, expectedCount) in cases {
if let pattern = FTS5Pattern(matchingPrefixPhrase: string) {
let rawPattern = String.fromDatabaseValue(pattern.databaseValue)!
XCTAssertEqual(rawPattern, expectedRawPattern)
let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: [pattern])!
XCTAssertEqual(count, expectedCount, "Expected pattern \(String(reflecting: rawPattern)) to yield \(expectedCount) results")
}
}
}
}
}
#endif
@@ -872,6 +872,42 @@ class FetchedRecordsControllerTests: GRDBTestCase {
XCTFail("Expected DatabaseError")
}
}
func testObservationOfSpecificRowIds() throws {
let dbQueue = try makeDatabaseQueue()
let generalController = try FetchedRecordsController(dbQueue, request: Person.all())
let specificController = try FetchedRecordsController(dbQueue, request: Person.filter(key: 1))
let generalExpectation = expectation(description: "expectation")
generalExpectation.expectedFulfillmentCount = 6
var generalChangeCount = 0
generalController.trackChanges(onChange: { (_, _, _) in
generalChangeCount += 1
generalExpectation.fulfill()
})
try generalController.performFetch()
let specificExpectation = expectation(description: "expectation")
specificExpectation.expectedFulfillmentCount = 3
var specificChangeCount = 0
specificController.trackChanges(onChange: { (_, _, _) in
specificChangeCount += 1
specificExpectation.fulfill()
})
try specificController.performFetch()
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [1, "Arthur"])
try db.execute("INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [2, "Barbara"])
try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Craig", 1])
try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["David", 2])
try db.execute("DELETE FROM persons")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(generalChangeCount, 6)
XCTAssertEqual(specificChangeCount, 3)
}
}
+7 -5
View File
@@ -15,6 +15,12 @@ import XCTest
// Support for Database.logError
var lastResultCode: ResultCode? = nil
var lastMessage: String? = nil
var logErrorSetup: Void = {
Database.logError = { (resultCode, message) in
lastResultCode = resultCode
lastMessage = message
}
}()
class GRDBTestCase: XCTestCase {
// The default configuration for tests
@@ -57,11 +63,7 @@ class GRDBTestCase: XCTestCase {
override func setUp() {
super.setUp()
// Must be set prior to any databaase connection
Database.logError = { (resultCode, message) in
lastResultCode = resultCode
lastMessage = message
}
_ = logErrorSetup
let dbPoolDirectoryName = "GRDBTestCase-\(ProcessInfo.processInfo.globallyUniqueString)"
dbDirectoryPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(dbPoolDirectoryName)
+465
View File
@@ -0,0 +1,465 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
let expectedSQL = """
SELECT
"t1".*,
"t2Left".*,
"t2Right".*,
"t3"."t1id", "t3"."name",
COUNT(DISTINCT t5.id) AS t5count
FROM t1
LEFT JOIN t2 t2Left ON t2Left.t1id = t1.id AND t2Left.name = 'left'
LEFT JOIN t2 t2Right ON t2Right.t1id = t1.id AND t2Right.name = 'right'
LEFT JOIN t3 ON t3.t1id = t1.id
LEFT JOIN t4 ON t4.t1id = t1.id
LEFT JOIN t5 ON t5.t3id = t3.t1id OR t5.t4id = t4.t1id
GROUP BY t1.id
ORDER BY t1.id
"""
let testedSQL = """
SELECT
\(T1.selectionSQL()),
\(T2.selectionSQL(alias: "t2Left")),
\(T2.selectionSQL(alias: "t2Right")),
\(T3.selectionSQL()),
COUNT(DISTINCT t5.id) AS t5count
FROM t1
LEFT JOIN t2 t2Left ON t2Left.t1id = t1.id AND t2Left.name = 'left'
LEFT JOIN t2 t2Right ON t2Right.t1id = t1.id AND t2Right.name = 'right'
LEFT JOIN t3 ON t3.t1id = t1.id
LEFT JOIN t4 ON t4.t1id = t1.id
LEFT JOIN t5 ON t5.t3id = t3.t1id OR t5.t4id = t4.t1id
GROUP BY t1.id
ORDER BY t1.id
"""
private struct T1: Codable, RowConvertible, TableMapping {
static let databaseTableName = "t1"
var id: Int64
var name: String
}
private struct T2: Codable, RowConvertible, TableMapping {
static let databaseTableName = "t2"
var id: Int64
var t1id: Int64
var name: String
}
private struct T3: Codable, RowConvertible, TableMapping {
static let databaseTableName = "t3"
static let databaseSelection: [SQLSelectable] = [Column("t1id"), Column("name")]
var t1id: Int64
var name: String
}
private struct T4: Codable, RowConvertible, TableMapping {
static let databaseTableName = "t4"
var t1id: Int64
var name: String
}
private struct T5: Codable, RowConvertible, TableMapping {
static let databaseTableName = "t5"
var id: Int64
var t3id: Int64?
var t4id: Int64?
var name: String
}
private struct FlatModel: RowConvertible {
private enum Scopes {
static let t1 = "t1"
static let t2Left = "t2Left"
static let t2Right = "t2Right"
static let t3 = "t3"
static let suffix = "suffix"
}
var t1: T1
var t2Left: T2?
var t2Right: T2?
var t3: T3?
var t5count: Int
init(row: Row) {
self.t1 = row[Scopes.t1]
self.t2Left = row[Scopes.t2Left]
self.t2Right = row[Scopes.t2Right]
self.t3 = row[Scopes.t3]
self.t5count = row.scoped(on: Scopes.suffix)!["t5count"]
}
static func all() -> AnyTypedRequest<FlatModel> {
return SQLRequest(testedSQL).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
T3.numberOfSelectedColumns(db)])
return ScopeAdapter([
Scopes.t1: adapters[0],
Scopes.t2Left: adapters[1],
Scopes.t2Right: adapters[2],
Scopes.t3: adapters[3],
Scopes.suffix: adapters[4]]) // The only test for adapters[4]
}
.asRequest(of: FlatModel.self)
}
}
private struct CodableFlatModel: RowConvertible, Codable {
var t1: T1
var t2Left: T2?
var t2Right: T2?
var t3: T3?
var t5count: Int
static func all() -> AnyTypedRequest<CodableFlatModel> {
return SQLRequest(testedSQL).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
T3.numberOfSelectedColumns(db)])
return ScopeAdapter([
CodingKeys.t1.stringValue: adapters[0],
CodingKeys.t2Left.stringValue: adapters[1],
CodingKeys.t2Right.stringValue: adapters[2],
CodingKeys.t3.stringValue: adapters[3]])
}
.asRequest(of: CodableFlatModel.self)
}
}
private struct CodableNestedModel: RowConvertible, Codable {
struct T2Pair: Codable {
var left: T2?
var right: T2?
}
var t1: T1
var optionalT2Pair: T2Pair?
var t2Pair: T2Pair
var t3: T3?
var t5count: Int
static func all() -> AnyTypedRequest<CodableNestedModel> {
return SQLRequest(testedSQL).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
T3.numberOfSelectedColumns(db)])
return ScopeAdapter([
CodingKeys.t1.stringValue: adapters[0],
CodingKeys.optionalT2Pair.stringValue: ScopeAdapter(base: EmptyRowAdapter(), scopes: [ // EmptyRowAdapter base so that optionalT2Pair only instantiates when its scopes contain non-null values
"left": adapters[1],
"right": adapters[2]]),
CodingKeys.t2Pair.stringValue: ScopeAdapter([
"left": adapters[1],
"right": adapters[2]]),
CodingKeys.t3.stringValue: adapters[3]])
}
.asRequest(of: CodableNestedModel.self)
}
}
class JoinSupportTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "t1") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text).notNull()
}
try db.create(table: "t2") { t in
t.column("id", .integer).primaryKey()
t.column("t1id", .integer).notNull().references("t1", onDelete: .cascade)
t.column("name", .text).notNull()
t.uniqueKey(["t1id", "name"])
}
try db.create(table: "t3") { t in
t.column("t1id", .integer).primaryKey().references("t1", onDelete: .cascade)
t.column("name", .text).notNull()
t.column("ignored", .integer)
}
try db.create(table: "t4") { t in
t.column("t1id", .integer).primaryKey().references("t1", onDelete: .cascade)
t.column("name", .text).notNull()
}
try db.create(table: "t5") { t in
t.column("id", .integer).primaryKey()
t.column("t3id", .integer).references("t3", onDelete: .cascade)
t.column("t4id", .integer).references("t4", onDelete: .cascade)
t.column("name", .text).notNull()
t.check(sql: "(t3id IS NOT NULL) + (t4id IS NOT NULL) = 1")
}
// Sample data
try db.execute("""
INSERT INTO t1 (id, name) VALUES (1, 'A1');
INSERT INTO t1 (id, name) VALUES (2, 'A2');
INSERT INTO t1 (id, name) VALUES (3, 'A3');
INSERT INTO t2 (id, t1id, name) VALUES (1, 1, 'left');
INSERT INTO t2 (id, t1id, name) VALUES (2, 1, 'right');
INSERT INTO t2 (id, t1id, name) VALUES (3, 2, 'left');
INSERT INTO t3 (t1id, name) VALUES (1, 'A3');
INSERT INTO t4 (t1id, name) VALUES (1, 'A4');
INSERT INTO t4 (t1id, name) VALUES (2, 'B4');
INSERT INTO t5 (id, t3id, t4id, name) VALUES (1, 1, NULL, 'A5');
INSERT INTO t5 (id, t3id, t4id, name) VALUES (2, 1, NULL, 'B5');
INSERT INTO t5 (id, t3id, t4id, name) VALUES (3, NULL, 1, 'C5');
INSERT INTO t5 (id, t3id, t4id, name) VALUES (4, NULL, 1, 'D5');
INSERT INTO t5 (id, t3id, t4id, name) VALUES (5, NULL, 1, 'E5');
INSERT INTO t5 (id, t3id, t4id, name) VALUES (6, NULL, 2, 'F5');
INSERT INTO t5 (id, t3id, t4id, name) VALUES (7, NULL, 2, 'G5');
""")
}
}
func testSampleData() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let rows = try Row.fetchAll(db, expectedSQL)
XCTAssertEqual(rows.count, 3)
XCTAssertEqual(rows[0], [
// t1.*
"id": 1, "name": "A1",
// t2Left.*
"id": 1, "t1id": 1, "name": "left",
// t2Right.*
"id": 2, "t1id": 1, "name": "right",
// t3.*
"t1id": 1, "name": "A3",
// t5count
"t5count": 5])
XCTAssertEqual(rows[1], [
// t1.*
"id": 2, "name": "A2",
// t2Left.*
"id": 3, "t1id": 2, "name": "left",
// t2Right.*
"id": nil, "t1id": nil, "name": nil,
// t3.*
"t1id": nil, "name": nil,
// t5count
"t5count": 2])
XCTAssertEqual(rows[2], [
// t1.*
"id": 3, "name": "A3",
// t2Left.*
"id": nil, "t1id": nil, "name": nil,
// t2Right.*
"id": nil, "t1id": nil, "name": nil,
// t3.*
"t1id": nil, "name": nil,
// t5count
"t5count": 0])
}
}
func testTestedSQL() throws {
XCTAssertEqual(testedSQL, expectedSQL)
}
func testSplittingRowAdapters() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = SQLRequest(testedSQL).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
T3.numberOfSelectedColumns(db)])
XCTAssertEqual(adapters.count, 5)
return ScopeAdapter([
"t1": adapters[0],
"t2Left": adapters[1],
"t2Right": adapters[2],
"t3": adapters[3],
"suffix": adapters[4]])
}
let rows = try Row.fetchAll(db, request)
XCTAssertEqual(rows.count, 3)
XCTAssertEqual(rows[0].unscoped, [
// t1.*
"id": 1, "name": "A1",
// t2Left.*
"id": 1, "t1id": 1, "name": "left",
// t2Right.*
"id": 2, "t1id": 1, "name": "right",
// t3.*
"t1id": 1, "name": "A3",
// t5count
"t5count": 5])
XCTAssertEqual(rows[0].scoped(on: "t1")!, ["id": 1, "name": "A1"])
XCTAssertEqual(rows[0].scoped(on: "t2Left")!, ["id": 1, "t1id": 1, "name": "left"])
XCTAssertEqual(rows[0].scoped(on: "t2Right")!, ["id": 2, "t1id": 1, "name": "right"])
XCTAssertEqual(rows[0].scoped(on: "t3")!, ["t1id": 1, "name": "A3"])
XCTAssertEqual(rows[0].scoped(on: "suffix")!, ["t5count": 5])
XCTAssertEqual(rows[1].unscoped, [
// t1.*
"id": 2, "name": "A2",
// t2Left.*
"id": 3, "t1id": 2, "name": "left",
// t2Right.*
"id": nil, "t1id": nil, "name": nil,
// t3.*
"t1id": nil, "name": nil,
// t5count
"t5count": 2])
XCTAssertEqual(rows[1].scoped(on: "t1")!, ["id": 2, "name": "A2"])
XCTAssertEqual(rows[1].scoped(on: "t2Left")!, ["id": 3, "t1id": 2, "name": "left"])
XCTAssertEqual(rows[1].scoped(on: "t2Right")!, ["id": nil, "t1id": nil, "name": nil])
XCTAssertEqual(rows[1].scoped(on: "t3")!, ["t1id": nil, "name": nil])
XCTAssertEqual(rows[1].scoped(on: "suffix")!, ["t5count": 2])
XCTAssertEqual(rows[2].unscoped, [
// t1.*
"id": 3, "name": "A3",
// t2Left.*
"id": nil, "t1id": nil, "name": nil,
// t2Right.*
"id": nil, "t1id": nil, "name": nil,
// t3.*
"t1id": nil, "name": nil,
// t5count
"t5count": 0])
XCTAssertEqual(rows[2].scoped(on: "t1")!, ["id": 3, "name": "A3"])
XCTAssertEqual(rows[2].scoped(on: "t2Left")!, ["id": nil, "t1id": nil, "name": nil])
XCTAssertEqual(rows[2].scoped(on: "t2Right")!, ["id": nil, "t1id": nil, "name": nil])
XCTAssertEqual(rows[2].scoped(on: "t3")!, ["t1id": nil, "name": nil])
XCTAssertEqual(rows[2].scoped(on: "suffix")!, ["t5count": 0])
}
}
func testFlatModel() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let models = try FlatModel.all().fetchAll(db)
XCTAssertEqual(models.count, 3)
XCTAssertEqual(models[0].t1.id, 1)
XCTAssertEqual(models[0].t1.name, "A1")
XCTAssertEqual(models[0].t2Left!.id, 1)
XCTAssertEqual(models[0].t2Left!.t1id, 1)
XCTAssertEqual(models[0].t2Left!.name, "left")
XCTAssertEqual(models[0].t2Right!.id, 2)
XCTAssertEqual(models[0].t2Right!.t1id, 1)
XCTAssertEqual(models[0].t2Right!.name, "right")
XCTAssertEqual(models[0].t3!.t1id, 1)
XCTAssertEqual(models[0].t3!.name, "A3")
XCTAssertEqual(models[0].t5count, 5)
XCTAssertEqual(models[1].t1.id, 2)
XCTAssertEqual(models[1].t1.name, "A2")
XCTAssertEqual(models[1].t2Left!.id, 3)
XCTAssertEqual(models[1].t2Left!.t1id, 2)
XCTAssertEqual(models[1].t2Left!.name, "left")
XCTAssertNil(models[1].t2Right)
XCTAssertNil(models[1].t3)
XCTAssertEqual(models[1].t5count, 2)
XCTAssertEqual(models[2].t1.id, 3)
XCTAssertEqual(models[2].t1.name, "A3")
XCTAssertNil(models[2].t2Left)
XCTAssertNil(models[2].t2Right)
XCTAssertNil(models[2].t3)
XCTAssertEqual(models[2].t5count, 0)
}
}
func testCodableFlatModel() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let models = try CodableFlatModel.all().fetchAll(db)
XCTAssertEqual(models.count, 3)
XCTAssertEqual(models[0].t1.id, 1)
XCTAssertEqual(models[0].t1.name, "A1")
XCTAssertEqual(models[0].t2Left!.id, 1)
XCTAssertEqual(models[0].t2Left!.t1id, 1)
XCTAssertEqual(models[0].t2Left!.name, "left")
XCTAssertEqual(models[0].t2Right!.id, 2)
XCTAssertEqual(models[0].t2Right!.t1id, 1)
XCTAssertEqual(models[0].t2Right!.name, "right")
XCTAssertEqual(models[0].t3!.t1id, 1)
XCTAssertEqual(models[0].t3!.name, "A3")
XCTAssertEqual(models[0].t5count, 5)
XCTAssertEqual(models[1].t1.id, 2)
XCTAssertEqual(models[1].t1.name, "A2")
XCTAssertEqual(models[1].t2Left!.id, 3)
XCTAssertEqual(models[1].t2Left!.t1id, 2)
XCTAssertEqual(models[1].t2Left!.name, "left")
XCTAssertNil(models[1].t2Right)
XCTAssertNil(models[1].t3)
XCTAssertEqual(models[1].t5count, 2)
XCTAssertEqual(models[2].t1.id, 3)
XCTAssertEqual(models[2].t1.name, "A3")
XCTAssertNil(models[2].t2Left)
XCTAssertNil(models[2].t2Right)
XCTAssertNil(models[2].t3)
XCTAssertEqual(models[2].t5count, 0)
}
}
func testCodableNestedModel() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let models = try CodableNestedModel.all().fetchAll(db)
XCTAssertEqual(models.count, 3)
XCTAssertEqual(models[0].t1.id, 1)
XCTAssertEqual(models[0].t1.name, "A1")
XCTAssertEqual(models[0].optionalT2Pair!.left!.id, 1)
XCTAssertEqual(models[0].optionalT2Pair!.left!.t1id, 1)
XCTAssertEqual(models[0].optionalT2Pair!.left!.name, "left")
XCTAssertEqual(models[0].optionalT2Pair!.right!.id, 2)
XCTAssertEqual(models[0].optionalT2Pair!.right!.t1id, 1)
XCTAssertEqual(models[0].optionalT2Pair!.right!.name, "right")
XCTAssertEqual(models[0].t2Pair.left!.id, 1)
XCTAssertEqual(models[0].t2Pair.left!.t1id, 1)
XCTAssertEqual(models[0].t2Pair.left!.name, "left")
XCTAssertEqual(models[0].t2Pair.right!.id, 2)
XCTAssertEqual(models[0].t2Pair.right!.t1id, 1)
XCTAssertEqual(models[0].t2Pair.right!.name, "right")
XCTAssertEqual(models[0].t3!.t1id, 1)
XCTAssertEqual(models[0].t3!.name, "A3")
XCTAssertEqual(models[0].t5count, 5)
XCTAssertEqual(models[1].t1.id, 2)
XCTAssertEqual(models[1].t1.name, "A2")
XCTAssertEqual(models[1].optionalT2Pair!.left!.id, 3)
XCTAssertEqual(models[1].optionalT2Pair!.left!.t1id, 2)
XCTAssertEqual(models[1].optionalT2Pair!.left!.name, "left")
XCTAssertEqual(models[1].t2Pair.left!.id, 3)
XCTAssertEqual(models[1].t2Pair.left!.t1id, 2)
XCTAssertEqual(models[1].t2Pair.left!.name, "left")
XCTAssertNil(models[1].optionalT2Pair!.right)
XCTAssertNil(models[1].t2Pair.right)
XCTAssertNil(models[1].t3)
XCTAssertEqual(models[1].t5count, 2)
XCTAssertEqual(models[2].t1.id, 3)
XCTAssertEqual(models[2].t1.name, "A3")
XCTAssertNil(models[2].optionalT2Pair)
XCTAssertNil(models[2].t2Pair.left)
XCTAssertNil(models[2].t2Pair.right)
XCTAssertNil(models[2].t3)
XCTAssertEqual(models[2].t5count, 0)
}
}
}
@@ -0,0 +1,272 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct Player: RowConvertible, MutablePersistable, Codable {
static let databaseTableName = "players"
var id: Int64?
var name: String?
var score: Int?
var creationDate: Date?
init(id: Int64? = nil, name: String? = nil, score: Int? = nil, creationDate: Date? = nil) {
self.id = id
self.name = name
self.score = score
self.creationDate = creationDate
}
mutating func insert(_ db: Database) throws {
if creationDate == nil {
creationDate = Date()
}
try performInsert(db)
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
class MutablePersistableChangesTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "players") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text)
t.column("score", .integer)
t.column("creationDate", .datetime)
}
}
}
func testDegenerateDatabaseEqualWithSelf() throws {
struct DegenerateRecord: MutablePersistable {
static let databaseTableName = "ignored"
func encode(to container: inout PersistenceContainer) {
}
}
let record = DegenerateRecord()
XCTAssertTrue(record.databaseEqual(record))
XCTAssertTrue(record.databaseChanges(from: record).isEmpty)
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let totalChangesCount = db.totalChangesCount
try XCTAssertFalse(record.updateChanges(db, from: record))
XCTAssertEqual(db.totalChangesCount, totalChangesCount)
}
}
func testDatabaseEqualWithSelf() throws {
do {
let player = Player(id: nil, name: nil, score: nil, creationDate: nil)
XCTAssertTrue(player.databaseEqual(player))
XCTAssertTrue(player.databaseChanges(from: player).isEmpty)
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let totalChangesCount = db.totalChangesCount
try XCTAssertFalse(player.updateChanges(db, from: player))
XCTAssertEqual(db.totalChangesCount, totalChangesCount)
}
}
do {
let player = Player(id: 1, name: "foo", score: 42, creationDate: Date())
XCTAssertTrue(player.databaseEqual(player))
XCTAssertTrue(player.databaseChanges(from: player).isEmpty)
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let totalChangesCount = db.totalChangesCount
try XCTAssertFalse(player.updateChanges(db, from: player))
XCTAssertEqual(db.totalChangesCount, totalChangesCount)
}
}
}
func testRecordValueChange() throws {
let dbQueue = try makeDatabaseQueue()
var player = Player(id: 1, name: "Arthur", score: nil, creationDate: nil)
try dbQueue.inDatabase { db in
try player.insert(db)
}
do {
// non-nil vs. non-nil
var newPlayer = player
newPlayer.name = "Bobby"
XCTAssertFalse(newPlayer.databaseEqual(player))
let changes = newPlayer.databaseChanges(from: player)
XCTAssertEqual(changes.count, 1)
XCTAssertEqual(changes["name"]!, "Arthur".databaseValue)
try dbQueue.inDatabase { db in
let totalChangesCount = db.totalChangesCount
try XCTAssertTrue(newPlayer.updateChanges(db, from: player))
XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1)
XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=\'Bobby\' WHERE \"id\"=1")
}
}
do {
// non-nil vs. nil
var newPlayer = player
newPlayer.name = nil
XCTAssertFalse(newPlayer.databaseEqual(player))
let changes = newPlayer.databaseChanges(from: player)
XCTAssertEqual(changes.count, 1)
XCTAssertEqual(changes["name"]!, "Arthur".databaseValue)
try dbQueue.inDatabase { db in
let totalChangesCount = db.totalChangesCount
try XCTAssertTrue(newPlayer.updateChanges(db, from: player))
XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1)
XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=NULL WHERE \"id\"=1")
}
}
do {
// nil vs. non-nil
var newPlayer = player
newPlayer.score = 41
XCTAssertFalse(newPlayer.databaseEqual(player))
let changes = newPlayer.databaseChanges(from: player)
XCTAssertEqual(changes.count, 1)
XCTAssertEqual(changes["score"]!, .null)
try dbQueue.inDatabase { db in
let totalChangesCount = db.totalChangesCount
try XCTAssertTrue(newPlayer.updateChanges(db, from: player))
XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1)
XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"score\"=41 WHERE \"id\"=1")
}
}
do {
// multiple changes
var newPlayer = player
newPlayer.name = "Bobby"
newPlayer.score = 41
XCTAssertFalse(newPlayer.databaseEqual(player))
let changes = newPlayer.databaseChanges(from: player)
XCTAssertEqual(changes.count, 2)
XCTAssertEqual(changes["name"]!, "Arthur".databaseValue)
XCTAssertEqual(changes["score"]!, .null)
try dbQueue.inDatabase { db in
let totalChangesCount = db.totalChangesCount
try XCTAssertTrue(newPlayer.updateChanges(db, from: player))
XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1)
let fetchedPlayer = try Player.fetchOne(db, key: player.id)
XCTAssertEqual(fetchedPlayer?.name, newPlayer.name)
XCTAssertEqual(fetchedPlayer?.score, newPlayer.score)
}
}
}
func testDatabaseEqualWithDifferentTypesAndDifferentWidth() throws {
// Mangle column case as well, for fun ;-)
struct NarrowPlayer: MutablePersistable, Codable {
static let databaseTableName = "players"
var ID: Int64?
var NAME: String?
}
let dbQueue = try makeDatabaseQueue()
do {
var oldPlayer = NarrowPlayer(ID: 1, NAME: "Arthur")
let newPlayer = Player(id: 1, name: "Arthur", score: 41, creationDate: nil)
let changes = newPlayer.databaseChanges(from: oldPlayer)
XCTAssertEqual(changes.count, 1)
XCTAssertEqual(changes["score"]!, .null)
try dbQueue.inTransaction { db in
try oldPlayer.insert(db)
let totalChangesCount = db.totalChangesCount
try XCTAssertTrue(newPlayer.updateChanges(db, from: oldPlayer))
XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1)
XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"score\"=41 WHERE \"id\"=1")
return .rollback
}
}
do {
var oldPlayer = NarrowPlayer(ID: 1, NAME: "Bobby")
let newPlayer = Player(id: 1, name: "Arthur", score: 42, creationDate: nil)
let changes = newPlayer.databaseChanges(from: oldPlayer)
XCTAssertEqual(changes.count, 2)
XCTAssertEqual(changes["name"]!, "Bobby".databaseValue)
XCTAssertEqual(changes["score"]!, .null)
try dbQueue.inTransaction { db in
try oldPlayer.insert(db)
let totalChangesCount = db.totalChangesCount
try XCTAssertTrue(newPlayer.updateChanges(db, from: oldPlayer))
XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1)
let fetchedPlayer = try Player.fetchOne(db, key: newPlayer.id)
XCTAssertEqual(fetchedPlayer?.name, newPlayer.name)
XCTAssertEqual(fetchedPlayer?.score, newPlayer.score)
return .rollback
}
}
do {
let oldPlayer = Player(id: 1, name: "Arthur", score: 42, creationDate: nil)
let newPlayer = NarrowPlayer(ID: 1, NAME: "Arthur")
let changes = newPlayer.databaseChanges(from: oldPlayer)
XCTAssertTrue(changes.isEmpty)
try dbQueue.inTransaction { db in
let totalChangesCount = db.totalChangesCount
try XCTAssertFalse(newPlayer.updateChanges(db, from: oldPlayer))
XCTAssertEqual(db.totalChangesCount, totalChangesCount)
return .rollback
}
}
do {
let oldPlayer = Player(id: 1, name: "Arthur", score: nil, creationDate: nil)
let newPlayer = NarrowPlayer(ID: 1, NAME: "Arthur")
let changes = newPlayer.databaseChanges(from: oldPlayer)
XCTAssertTrue(changes.isEmpty)
try dbQueue.inTransaction { db in
let totalChangesCount = db.totalChangesCount
try XCTAssertFalse(newPlayer.updateChanges(db, from: oldPlayer))
XCTAssertEqual(db.totalChangesCount, totalChangesCount)
return .rollback
}
}
do {
var oldPlayer = Player(id: 1, name: "Arthur", score: nil, creationDate: nil)
let newPlayer = NarrowPlayer(ID: 1, NAME: "Bobby")
let changes = newPlayer.databaseChanges(from: oldPlayer)
XCTAssertEqual(changes.count, 1)
XCTAssertEqual(changes["NAME"]!, "Arthur".databaseValue)
try dbQueue.inTransaction { db in
try oldPlayer.insert(db)
let totalChangesCount = db.totalChangesCount
try XCTAssertTrue(newPlayer.updateChanges(db, from: oldPlayer))
XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1)
XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"NAME\"='Bobby' WHERE \"id\"=1")
return .rollback
}
}
}
}
@@ -174,9 +174,6 @@ class MutablePersistablePersistenceConflictPolicyTests: GRDBTestCase {
transactionEvents.append(event.copy())
}
func databaseWillCommit() throws {
}
func databaseDidCommit(_ db: Database) {
events = transactionEvents
transactionEvents = []
@@ -186,11 +183,6 @@ class MutablePersistablePersistenceConflictPolicyTests: GRDBTestCase {
events = []
transactionEvents = []
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
}
#endif
}
let dbQueue = try makeDatabaseQueue()
+69
View File
@@ -0,0 +1,69 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct TestError : Error { }
class PrefixCursorTests: GRDBTestCase {
func testPrefixCursorFromCursor() throws {
do {
let base = IteratorCursor([1, 2, 3, 4, 5])
let cursor = base.prefix(0)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 4, 5])
let cursor = base.prefix(2)
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 2)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 4, 5])
let cursor = base.prefix(10)
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 2)
try XCTAssertEqual(cursor.next()!, 3)
try XCTAssertEqual(cursor.next()!, 4)
try XCTAssertEqual(cursor.next()!, 5)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
}
func testPrefixCursorFromThrowingCursor() throws {
var i = 1
let base: AnyCursor<Int> = AnyCursor {
guard i < 3 else { throw TestError() }
defer { i += 1 }
return i
}
let cursor = base.prefix(3)
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 2)
do {
_ = try cursor.next()
XCTFail()
} catch is TestError {
} catch {
XCTFail()
}
}
func testPrefixCursorChain() throws {
let base = IteratorCursor([1, 2, 3, 4, 5])
let cursor = base.prefix(2).prefix(1)
try XCTAssertEqual(cursor.next()!, 1)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
}
@@ -0,0 +1,70 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct TestError : Error { }
class PrefixWhileCursorTests: GRDBTestCase {
func testPrefixWhileCursorFromCursor() throws {
do {
let base = IteratorCursor([1, 2, 3, 1, 5])
let cursor = base.prefix(while: { $0 < 3 })
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 2)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 1, 5])
let cursor = base.prefix(while: { _ in true })
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 2)
try XCTAssertEqual(cursor.next()!, 3)
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 5)
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 1, 5])
let cursor = base.prefix(while: { _ in false })
XCTAssertTrue(try cursor.next() == nil) // end
XCTAssertTrue(try cursor.next() == nil) // past the end
}
do {
let base = IteratorCursor([1, 2, 3, 1, 5])
let cursor = base.prefix(while: { _ in throw TestError() })
_ = try cursor.next()
XCTFail()
} catch is TestError {
} catch {
XCTFail()
}
}
func testPrefixWhileCursorFromThrowingCursor() throws {
var i = 1
let base: AnyCursor<Int> = AnyCursor {
guard i < 3 else { throw TestError() }
defer { i += 1 }
return i
}
let cursor = base.prefix(while: { $0 < 4 })
try XCTAssertEqual(cursor.next()!, 1)
try XCTAssertEqual(cursor.next()!, 2)
do {
_ = try cursor.next()
XCTFail()
} catch is TestError {
} catch {
XCTFail()
}
}
}
+483
View File
@@ -0,0 +1,483 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
typealias RecordBox = GRDBCipher.RecordBox // Single deprecation warning
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
typealias RecordBox = GRDBCustomSQLite.RecordBox // Single deprecation warning
#else
import GRDB
typealias RecordBox = GRDB.RecordBox // Single deprecation warning
#endif
private struct Player: RowConvertible, MutablePersistable, Codable {
static let databaseTableName = "players"
var id: Int64?
var name: String?
var score: Int?
var creationDate: Date?
init(id: Int64? = nil, name: String? = nil, score: Int? = nil, creationDate: Date? = nil) {
self.id = id
self.name = name
self.score = score
self.creationDate = creationDate
}
mutating func insert(_ db: Database) throws {
if creationDate == nil {
creationDate = Date()
}
try performInsert(db)
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
class RecordBoxTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "players") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text)
t.column("score", .integer)
t.column("creationDate", .datetime)
}
}
}
func testRecordIsEditedAfterInit() {
// Create a Record. No fetch has happen, so we don't know if it is
// identical to its eventual row in the database. So it is edited.
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
XCTAssertTrue(player.hasDatabaseChanges)
}
func testRecordIsEditedAfterInitFromRow() {
// Create a Record from a row. The row may not come from the database.
// So it is edited.
let row = Row(["name": "Arthur", "score": 41])
let player = RecordBox<Player>(row: row)
XCTAssertTrue(player.hasDatabaseChanges)
}
func testRecordIsNotEditedAfterFullFetch() throws {
// Fetch a record from a row that contains all the columns in
// persistence container: An update statement, which only saves the
// columns in persistence container would perform no change. So the
// record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
let player = try RecordBox<Player>.fetchOne(db, "SELECT * FROM players")!
XCTAssertFalse(player.hasDatabaseChanges)
}
}
func testRecordIsNotEditedAfterWiderThanFullFetch() throws {
// Fetch a record from a row that contains all the columns in
// persistence container, plus extra ones: An update statement,
// which only saves the columns in persistence container would
// perform no change. So the record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
let player = try RecordBox<Player>.fetchOne(db, "SELECT *, 1 AS foo FROM players")!
XCTAssertFalse(player.hasDatabaseChanges)
}
}
func testRecordIsEditedAfterPartialFetch() throws {
// Fetch a record from a row that does not contain all the columns in
// persistence container: An update statement saves the columns in
// persistence container, so it may perform unpredictable change.
// So the record is edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
let player = try RecordBox<Player>.fetchOne(db, "SELECT name FROM players")!
XCTAssertTrue(player.hasDatabaseChanges)
}
}
func testRecordIsNotEditedAfterInsert() throws {
// After insertion, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
XCTAssertFalse(player.hasDatabaseChanges)
}
}
func testRecordIsEditedAfterValueChange() throws {
// Any change in a value exposed in persistence container yields a
// record that is edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.name != nil)
player.value.name = "Bobby" // non-nil vs. non-nil
XCTAssertTrue(player.hasDatabaseChanges)
}
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.name != nil)
player.value.name = nil // non-nil vs. nil
XCTAssertTrue(player.hasDatabaseChanges)
}
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.score == nil)
player.value.score = 41 // nil vs. non-nil
XCTAssertTrue(player.hasDatabaseChanges)
}
}
}
func testRecordIsNotEditedAfterSameValueChange() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.name != nil)
player.value.name = "Arthur" // non-nil vs. non-nil
XCTAssertFalse(player.hasDatabaseChanges)
}
do {
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
XCTAssertTrue(player.value.score == nil)
player.value.score = nil // nil vs. nil
XCTAssertFalse(player.hasDatabaseChanges)
}
}
}
func testRecordIsNotEditedAfterUpdate() throws {
// After update, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
player.value.name = "Bobby"
try player.update(db)
XCTAssertFalse(player.hasDatabaseChanges)
}
}
func testRecordIsNotEditedAfterSave() throws {
// After save, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.save(db)
XCTAssertFalse(player.hasDatabaseChanges)
player.value.name = "Bobby"
XCTAssertTrue(player.hasDatabaseChanges)
try player.save(db)
XCTAssertFalse(player.hasDatabaseChanges)
}
}
func testRecordIsEditedAfterPrimaryKeyChange() throws {
// After reload, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
player.value.id = player.value.id! + 1
XCTAssertTrue(player.hasDatabaseChanges)
}
}
func testCopyTransfersEditedFlag() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
XCTAssertFalse(player.hasDatabaseChanges)
XCTAssertFalse(player.copy().hasDatabaseChanges)
player.value.name = "Barbara"
XCTAssertTrue(player.hasDatabaseChanges)
XCTAssertTrue(player.copy().hasDatabaseChanges)
player.hasDatabaseChanges = false
XCTAssertFalse(player.hasDatabaseChanges)
XCTAssertFalse(player.copy().hasDatabaseChanges)
player.hasDatabaseChanges = true
XCTAssertTrue(player.hasDatabaseChanges)
XCTAssertTrue(player.copy().hasDatabaseChanges)
}
}
func testChangesAfterInit() {
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
let changes = player.databaseChanges
XCTAssertEqual(changes.count, 4)
for (column, old) in changes {
switch column {
case "id":
XCTAssertTrue(old == nil)
case "name":
XCTAssertTrue(old == nil)
case "score":
XCTAssertTrue(old == nil)
case "creationDate":
XCTAssertTrue(old == nil)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
func testChangesAfterInitFromRow() {
let player = RecordBox<Player>(row: Row(["name": "Arthur", "score": 41]))
let changes = player.databaseChanges
XCTAssertEqual(changes.count, 4)
for (column, old) in changes {
switch column {
case "id":
XCTAssertTrue(old == nil)
case "name":
XCTAssertTrue(old == nil)
case "score":
XCTAssertTrue(old == nil)
case "creationDate":
XCTAssertTrue(old == nil)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
func testChangesAfterFullFetch() throws {
// Fetch a record from a row that contains all the columns in
// persistence container: An update statement, which only saves the
// columns in persistence container would perform no change. So the
// record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
do {
let player = try RecordBox<Player>.fetchOne(db, "SELECT * FROM players")!
let changes = player.databaseChanges
XCTAssertEqual(changes.count, 0)
}
do {
let players = try RecordBox<Player>.fetchAll(db, "SELECT * FROM players")
let changes = players[0].databaseChanges
XCTAssertEqual(changes.count, 0)
}
do {
let players = try RecordBox<Player>.fetchCursor(db, "SELECT * FROM players")
let changes = try players.next()!.databaseChanges
XCTAssertEqual(changes.count, 0)
}
do {
let player = try RecordBox<Player>.fetchOne(db, "SELECT * FROM players", adapter: SuffixRowAdapter(fromIndex: 0))!
let changes = player.databaseChanges
XCTAssertEqual(changes.count, 0)
}
}
}
func testChangesAfterPartialFetch() throws {
// Fetch a record from a row that does not contain all the columns in
// persistence container: An update statement saves the columns in
// persistence container, so it may perform unpredictable change.
// So the record is edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try RecordBox<Player>(value: Player(name: "Arthur", score: 41)).insert(db)
let player = try RecordBox<Player>.fetchOne(db, "SELECT name FROM players")!
let changes = player.databaseChanges
XCTAssertEqual(changes.count, 3)
for (column, old) in changes {
switch column {
case "id":
XCTAssertTrue(old == nil)
case "score":
XCTAssertTrue(old == nil)
case "creationDate":
XCTAssertTrue(old == nil)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
}
func testChangesAfterInsert() throws {
// After insertion, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
let changes = player.databaseChanges
XCTAssertEqual(changes.count, 0)
}
}
func testChangesAfterValueChange() throws {
// Any change in a value exposed in persistence container yields a
// record that is edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur"))
try player.insert(db)
player.value.name = "Bobby" // non-nil -> non-nil
player.value.score = 41 // nil -> non-nil
player.value.creationDate = nil // non-nil -> nil
let changes = player.databaseChanges
XCTAssertEqual(changes.count, 3)
for (column, old) in changes {
switch column {
case "name":
XCTAssertEqual(old, "Arthur".databaseValue)
case "score":
XCTAssertEqual(old, DatabaseValue.null)
case "creationDate":
XCTAssertTrue(Date.fromDatabaseValue(old!) != nil)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
}
func testChangesAfterUpdate() throws {
// After update, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
player.value.name = "Bobby"
try player.update(db)
XCTAssertEqual(player.databaseChanges.count, 0)
}
}
func testChangesAfterSave() throws {
// After save, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.save(db)
XCTAssertEqual(player.databaseChanges.count, 0)
player.value.name = "Bobby"
let changes = player.databaseChanges
XCTAssertEqual(changes.count, 1)
for (column, old) in changes {
switch column {
case "name":
XCTAssertEqual(old, "Arthur".databaseValue)
default:
XCTFail("Unexpected column: \(column)")
}
}
try player.save(db)
XCTAssertEqual(player.databaseChanges.count, 0)
}
}
func testChangesAfterPrimaryKeyChange() throws {
// After reload, a record is not edited.
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
player.value.id = player.value.id! + 1
let changes = player.databaseChanges
XCTAssertEqual(changes.count, 1)
for (column, old) in changes {
switch column {
case "id":
XCTAssertEqual(old, (player.value.id! - 1).databaseValue)
default:
XCTFail("Unexpected column: \(column)")
}
}
}
}
func testCopyTransfersChanges() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
try player.insert(db)
XCTAssertEqual(player.databaseChanges.count, 0)
XCTAssertEqual(player.copy().databaseChanges.count, 0)
player.value.name = "Barbara"
XCTAssertTrue(player.databaseChanges.count > 0) // TODO: compare actual changes
XCTAssertEqual(player.databaseChanges.count, player.copy().databaseChanges.count)
player.hasDatabaseChanges = false
XCTAssertEqual(player.databaseChanges.count, 0)
XCTAssertEqual(player.copy().databaseChanges.count, 0)
player.hasDatabaseChanges = true
XCTAssertTrue(player.databaseChanges.count > 0) // TODO: compare actual changes
XCTAssertEqual(player.databaseChanges.count, player.copy().databaseChanges.count)
}
}
func testUpdateChanges() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let player = RecordBox<Player>(value: Player(name: "Arthur", score: 41))
do {
XCTAssertTrue(player.hasDatabaseChanges)
try player.updateChanges(db)
XCTFail("Expected PersistenceError")
} catch is PersistenceError { }
try player.insert(db)
// Nothing to update
let initialChangesCount = db.totalChangesCount
XCTAssertFalse(player.hasDatabaseChanges)
try XCTAssertFalse(player.updateChanges(db))
XCTAssertEqual(db.totalChangesCount, initialChangesCount)
// Nothing to update
player.value.score = 41
XCTAssertFalse(player.hasDatabaseChanges)
try XCTAssertFalse(player.updateChanges(db))
XCTAssertEqual(db.totalChangesCount, initialChangesCount)
// Update single column
player.value.score = 42
XCTAssertEqual(Set(player.databaseChanges.keys), ["score"])
try XCTAssertTrue(player.updateChanges(db))
XCTAssertEqual(db.totalChangesCount, initialChangesCount + 1)
XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"score\"=42 WHERE \"id\"=1")
// Update two columns
player.value.name = "Barbara"
player.value.score = 43
XCTAssertEqual(Set(player.databaseChanges.keys), ["score", "name"])
try XCTAssertTrue(player.updateChanges(db))
XCTAssertEqual(db.totalChangesCount, initialChangesCount + 2)
let fetchedPlayer = try RecordBox<Player>.fetchOne(db, key: player.value.id)!
XCTAssertEqual(fetchedPlayer.value.name, player.value.name)
XCTAssertEqual(fetchedPlayer.value.score, player.value.score)
}
}
}
+103 -103
View File
@@ -147,7 +147,7 @@ class RecordEditedTests: GRDBTestCase {
// Create a Record. No fetch has happen, so we don't know if it is
// identical to its eventual row in the database. So it is edited.
let person = Person(name: "Arthur", age: 41)
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
func testRecordIsEditedAfterInitFromRow() {
@@ -155,7 +155,7 @@ class RecordEditedTests: GRDBTestCase {
// So it is edited.
let row = Row(["name": "Arthur", "age": 41])
let person = Person(row: row)
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
func testRecordIsNotEditedAfterFullFetch() throws {
@@ -167,12 +167,12 @@ class RecordEditedTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try Person(name: "Arthur", age: 41).insert(db)
let person = try Person.fetchOne(db, "SELECT * FROM persons")!
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
try dbQueue.inDatabase { db in
try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db)
let person = try PersonWithModifiedCaseColumns.fetchOne(db, "SELECT * FROM persons")!
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
}
@@ -182,7 +182,7 @@ class RecordEditedTests: GRDBTestCase {
try db.execute("CREATE TABLE t (value REAL)")
try db.execute("INSERT INTO t (value) VALUES (1)")
let record = try IntegerPropertyOnRealAffinityColumn.fetchOne(db, "SELECT * FROM t")!
XCTAssertFalse(record.hasPersistentChangedValues)
XCTAssertFalse(record.hasDatabaseChanges)
}
}
@@ -195,12 +195,12 @@ class RecordEditedTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try Person(name: "Arthur", age: 41).insert(db)
let person = try Person.fetchOne(db, "SELECT *, 1 AS foo FROM persons")!
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
try dbQueue.inDatabase { db in
try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db)
let person = try PersonWithModifiedCaseColumns.fetchOne(db, "SELECT *, 1 AS foo FROM persons")!
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
}
@@ -213,12 +213,12 @@ class RecordEditedTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try Person(name: "Arthur", age: 41).insert(db)
let person = try Person.fetchOne(db, "SELECT name FROM persons")!
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
try dbQueue.inDatabase { db in
try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db)
let person = try PersonWithModifiedCaseColumns.fetchOne(db, "SELECT name FROM persons")!
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
}
@@ -228,12 +228,12 @@ class RecordEditedTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let person = Person(name: "Arthur", age: 41)
try person.insert(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
try dbQueue.inDatabase { db in
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.insert(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
}
@@ -247,21 +247,21 @@ class RecordEditedTests: GRDBTestCase {
try person.insert(db)
XCTAssertTrue(person.name != nil)
person.name = "Bobby" // non-nil vs. non-nil
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
do {
let person = Person(name: "Arthur")
try person.insert(db)
XCTAssertTrue(person.name != nil)
person.name = nil // non-nil vs. nil
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
do {
let person = Person(name: "Arthur")
try person.insert(db)
XCTAssertTrue(person.age == nil)
person.age = 41 // nil vs. non-nil
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
}
try dbQueue.inDatabase { db in
@@ -270,21 +270,21 @@ class RecordEditedTests: GRDBTestCase {
try person.insert(db)
XCTAssertTrue(person.name != nil)
person.name = "Bobby" // non-nil vs. non-nil
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
do {
let person = PersonWithModifiedCaseColumns(name: "Arthur")
try person.insert(db)
XCTAssertTrue(person.name != nil)
person.name = nil // non-nil vs. nil
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
do {
let person = PersonWithModifiedCaseColumns(name: "Arthur")
try person.insert(db)
XCTAssertTrue(person.age == nil)
person.age = 41 // nil vs. non-nil
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
}
}
@@ -297,14 +297,14 @@ class RecordEditedTests: GRDBTestCase {
try person.insert(db)
XCTAssertTrue(person.name != nil)
person.name = "Arthur" // non-nil vs. non-nil
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
do {
let person = Person(name: "Arthur")
try person.insert(db)
XCTAssertTrue(person.age == nil)
person.age = nil // nil vs. nil
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
}
try dbQueue.inDatabase { db in
@@ -313,14 +313,14 @@ class RecordEditedTests: GRDBTestCase {
try person.insert(db)
XCTAssertTrue(person.name != nil)
person.name = "Arthur" // non-nil vs. non-nil
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
do {
let person = PersonWithModifiedCaseColumns(name: "Arthur")
try person.insert(db)
XCTAssertTrue(person.age == nil)
person.age = nil // nil vs. nil
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
}
}
@@ -333,14 +333,14 @@ class RecordEditedTests: GRDBTestCase {
try person.insert(db)
person.name = "Bobby"
try person.update(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
try dbQueue.inDatabase { db in
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.insert(db)
person.name = "Bobby"
try person.update(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
}
@@ -350,20 +350,20 @@ class RecordEditedTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let person = Person(name: "Arthur", age: 41)
try person.save(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
person.name = "Bobby"
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
try person.save(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
try dbQueue.inDatabase { db in
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.save(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
person.name = "Bobby"
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
try person.save(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
}
}
@@ -374,13 +374,13 @@ class RecordEditedTests: GRDBTestCase {
let person = Person(name: "Arthur", age: 41)
try person.insert(db)
person.id = person.id + 1
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
try dbQueue.inDatabase { db in
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.insert(db)
person.id = person.id + 1
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
}
}
@@ -390,45 +390,45 @@ class RecordEditedTests: GRDBTestCase {
let person = Person(name: "Arthur", age: 41)
try person.insert(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.copy().hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
XCTAssertFalse(person.copy().hasDatabaseChanges)
person.name = "Barbara"
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.copy().hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
XCTAssertTrue(person.copy().hasDatabaseChanges)
person.hasPersistentChangedValues = false
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.copy().hasPersistentChangedValues)
person.hasDatabaseChanges = false
XCTAssertFalse(person.hasDatabaseChanges)
XCTAssertFalse(person.copy().hasDatabaseChanges)
person.hasPersistentChangedValues = true
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.copy().hasPersistentChangedValues)
person.hasDatabaseChanges = true
XCTAssertTrue(person.hasDatabaseChanges)
XCTAssertTrue(person.copy().hasDatabaseChanges)
}
try dbQueue.inDatabase { db in
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.insert(db)
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.copy().hasPersistentChangedValues)
XCTAssertFalse(person.hasDatabaseChanges)
XCTAssertFalse(person.copy().hasDatabaseChanges)
person.name = "Barbara"
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.copy().hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
XCTAssertTrue(person.copy().hasDatabaseChanges)
person.hasPersistentChangedValues = false
XCTAssertFalse(person.hasPersistentChangedValues)
XCTAssertFalse(person.copy().hasPersistentChangedValues)
person.hasDatabaseChanges = false
XCTAssertFalse(person.hasDatabaseChanges)
XCTAssertFalse(person.copy().hasDatabaseChanges)
person.hasPersistentChangedValues = true
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.copy().hasPersistentChangedValues)
person.hasDatabaseChanges = true
XCTAssertTrue(person.hasDatabaseChanges)
XCTAssertTrue(person.copy().hasDatabaseChanges)
}
}
func testChangesAfterInit() {
let person = Person(name: "Arthur", age: 41)
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 4)
for (column, old) in changes {
switch column {
@@ -448,7 +448,7 @@ class RecordEditedTests: GRDBTestCase {
func testChangesAfterInitFromRow() {
let person = Person(row: Row(["name": "Arthur", "age": 41]))
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 4)
for (column, old) in changes {
switch column {
@@ -476,29 +476,29 @@ class RecordEditedTests: GRDBTestCase {
try Person(name: "Arthur", age: 41).insert(db)
do {
let person = try Person.fetchOne(db, "SELECT * FROM persons")!
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 0)
}
do {
let persons = try Person.fetchAll(db, "SELECT * FROM persons")
let changes = persons[0].persistentChangedValues
let changes = persons[0].databaseChanges
XCTAssertEqual(changes.count, 0)
}
do {
let persons = try Person.fetchCursor(db, "SELECT * FROM persons")
let changes = try persons.next()!.persistentChangedValues
let changes = try persons.next()!.databaseChanges
XCTAssertEqual(changes.count, 0)
}
do {
let person = try Person.fetchOne(db, "SELECT * FROM persons", adapter: SuffixRowAdapter(fromIndex: 0))!
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 0)
}
}
try dbQueue.inDatabase { db in
try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db)
let person = try PersonWithModifiedCaseColumns.fetchOne(db, "SELECT * FROM persons")!
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 0)
}
}
@@ -512,7 +512,7 @@ class RecordEditedTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try Person(name: "Arthur", age: 41).insert(db)
let person = try Person.fetchOne(db, "SELECT name FROM persons")!
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 3)
for (column, old) in changes {
switch column {
@@ -530,7 +530,7 @@ class RecordEditedTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try PersonWithModifiedCaseColumns(name: "Arthur", age: 41).insert(db)
let person = try PersonWithModifiedCaseColumns.fetchOne(db, "SELECT name FROM persons")!
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 3)
for (column, old) in changes {
switch column {
@@ -553,13 +553,13 @@ class RecordEditedTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let person = Person(name: "Arthur", age: 41)
try person.insert(db)
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 0)
}
try dbQueue.inDatabase { db in
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.insert(db)
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 0)
}
}
@@ -575,7 +575,7 @@ class RecordEditedTests: GRDBTestCase {
person.name = "Bobby" // non-nil -> non-nil
person.age = 41 // nil -> non-nil
person.creationDate = nil // non-nil -> nil
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 3)
for (column, old) in changes {
switch column {
@@ -597,7 +597,7 @@ class RecordEditedTests: GRDBTestCase {
person.name = "Bobby" // non-nil -> non-nil
person.age = 41 // nil -> non-nil
person.creationDate = nil // non-nil -> nil
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 3)
for (column, old) in changes {
switch column {
@@ -622,14 +622,14 @@ class RecordEditedTests: GRDBTestCase {
try person.insert(db)
person.name = "Bobby"
try person.update(db)
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.databaseChanges.count, 0)
}
try dbQueue.inDatabase { db in
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.insert(db)
person.name = "Bobby"
try person.update(db)
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.databaseChanges.count, 0)
}
}
@@ -639,10 +639,10 @@ class RecordEditedTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let person = Person(name: "Arthur", age: 41)
try person.save(db)
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.databaseChanges.count, 0)
person.name = "Bobby"
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 1)
for (column, old) in changes {
switch column {
@@ -653,15 +653,15 @@ class RecordEditedTests: GRDBTestCase {
}
}
try person.save(db)
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.databaseChanges.count, 0)
}
try dbQueue.inDatabase { db in
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.save(db)
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.databaseChanges.count, 0)
person.name = "Bobby"
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 1)
for (column, old) in changes {
switch column {
@@ -672,7 +672,7 @@ class RecordEditedTests: GRDBTestCase {
}
}
try person.save(db)
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.databaseChanges.count, 0)
}
}
@@ -683,7 +683,7 @@ class RecordEditedTests: GRDBTestCase {
let person = Person(name: "Arthur", age: 41)
try person.insert(db)
person.id = person.id + 1
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 1)
for (column, old) in changes {
switch column {
@@ -698,7 +698,7 @@ class RecordEditedTests: GRDBTestCase {
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.insert(db)
person.id = person.id + 1
let changes = person.persistentChangedValues
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 1)
for (column, old) in changes {
switch column {
@@ -717,39 +717,39 @@ class RecordEditedTests: GRDBTestCase {
let person = Person(name: "Arthur", age: 41)
try person.insert(db)
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.copy().persistentChangedValues.count, 0)
XCTAssertEqual(person.databaseChanges.count, 0)
XCTAssertEqual(person.copy().databaseChanges.count, 0)
person.name = "Barbara"
XCTAssertTrue(person.persistentChangedValues.count > 0) // TODO: compare actual changes
XCTAssertEqual(person.persistentChangedValues.count, person.copy().persistentChangedValues.count)
XCTAssertTrue(person.databaseChanges.count > 0) // TODO: compare actual changes
XCTAssertEqual(person.databaseChanges.count, person.copy().databaseChanges.count)
person.hasPersistentChangedValues = false
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.copy().persistentChangedValues.count, 0)
person.hasDatabaseChanges = false
XCTAssertEqual(person.databaseChanges.count, 0)
XCTAssertEqual(person.copy().databaseChanges.count, 0)
person.hasPersistentChangedValues = true
XCTAssertTrue(person.persistentChangedValues.count > 0) // TODO: compare actual changes
XCTAssertEqual(person.persistentChangedValues.count, person.copy().persistentChangedValues.count)
person.hasDatabaseChanges = true
XCTAssertTrue(person.databaseChanges.count > 0) // TODO: compare actual changes
XCTAssertEqual(person.databaseChanges.count, person.copy().databaseChanges.count)
}
try dbQueue.inDatabase { db in
let person = PersonWithModifiedCaseColumns(name: "Arthur", age: 41)
try person.insert(db)
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.copy().persistentChangedValues.count, 0)
XCTAssertEqual(person.databaseChanges.count, 0)
XCTAssertEqual(person.copy().databaseChanges.count, 0)
person.name = "Barbara"
XCTAssertTrue(person.persistentChangedValues.count > 0) // TODO: compare actual changes
XCTAssertEqual(person.persistentChangedValues.count, person.copy().persistentChangedValues.count)
XCTAssertTrue(person.databaseChanges.count > 0) // TODO: compare actual changes
XCTAssertEqual(person.databaseChanges.count, person.copy().databaseChanges.count)
person.hasPersistentChangedValues = false
XCTAssertEqual(person.persistentChangedValues.count, 0)
XCTAssertEqual(person.copy().persistentChangedValues.count, 0)
person.hasDatabaseChanges = false
XCTAssertEqual(person.databaseChanges.count, 0)
XCTAssertEqual(person.copy().databaseChanges.count, 0)
person.hasPersistentChangedValues = true
XCTAssertTrue(person.persistentChangedValues.count > 0) // TODO: compare actual changes
XCTAssertEqual(person.persistentChangedValues.count, person.copy().persistentChangedValues.count)
person.hasDatabaseChanges = true
XCTAssertTrue(person.databaseChanges.count > 0) // TODO: compare actual changes
XCTAssertEqual(person.databaseChanges.count, person.copy().databaseChanges.count)
}
}
@@ -759,7 +759,7 @@ class RecordEditedTests: GRDBTestCase {
let person = Person(name: "Arthur", age: 41)
do {
XCTAssertTrue(person.hasPersistentChangedValues)
XCTAssertTrue(person.hasDatabaseChanges)
try person.updateChanges(db)
XCTFail("Expected PersistenceError")
} catch is PersistenceError { }
@@ -768,28 +768,28 @@ class RecordEditedTests: GRDBTestCase {
// Nothing to update
let initialChangesCount = db.totalChangesCount
XCTAssertFalse(person.hasPersistentChangedValues)
try person.updateChanges(db)
XCTAssertFalse(person.hasDatabaseChanges)
try XCTAssertFalse(person.updateChanges(db))
XCTAssertEqual(db.totalChangesCount, initialChangesCount)
// Nothing to update
person.age = 41
XCTAssertFalse(person.hasPersistentChangedValues)
try person.updateChanges(db)
XCTAssertFalse(person.hasDatabaseChanges)
try XCTAssertFalse(person.updateChanges(db))
XCTAssertEqual(db.totalChangesCount, initialChangesCount)
// Update single column
person.age = 42
XCTAssertEqual(Set(person.persistentChangedValues.keys), ["age"])
try person.updateChanges(db)
XCTAssertEqual(Set(person.databaseChanges.keys), ["age"])
try XCTAssertTrue(person.updateChanges(db))
XCTAssertEqual(db.totalChangesCount, initialChangesCount + 1)
XCTAssertEqual(lastSQLQuery, "UPDATE \"persons\" SET \"age\"=42 WHERE \"id\"=1")
// Update two columns
person.name = "Barbara"
person.age = 43
XCTAssertEqual(Set(person.persistentChangedValues.keys), ["age", "name"])
try person.updateChanges(db)
XCTAssertEqual(Set(person.databaseChanges.keys), ["age", "name"])
try XCTAssertTrue(person.updateChanges(db))
XCTAssertEqual(db.totalChangesCount, initialChangesCount + 2)
let fetchedPerson = try Person.fetchOne(db, key: person.id)
XCTAssertEqual(fetchedPerson?.name, person.name)
@@ -310,6 +310,76 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalRowID()
try record1.insert(db)
let record2 = MinimalRowID()
try record2.insert(db)
do {
let cursor = try MinimalRowID.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try MinimalRowID.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try MinimalRowID.filter(keys: [["id": record1.id], ["id": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.id!, record1.id!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalRowID()
try record1.insert(db)
let record2 = MinimalRowID()
try record2.insert(db)
do {
let fetchedRecords = try MinimalRowID.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try MinimalRowID.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
}
do {
let fetchedRecords = try MinimalRowID.filter(keys: [["id": record1.id], ["id": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalRowID()
try record.insert(db)
let fetchedRecord = try MinimalRowID.filter(key: ["id": record.id]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
}
}
// MARK: - Fetch With Primary Key
@@ -379,6 +449,75 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalRowID()
try record1.insert(db)
let record2 = MinimalRowID()
try record2.insert(db)
do {
let ids: [Int64] = []
let cursor = try MinimalRowID.filter(keys: ids).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let ids = [record1.id!, record2.id!]
let cursor = try MinimalRowID.filter(keys: ids).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalRowID()
try record1.insert(db)
let record2 = MinimalRowID()
try record2.insert(db)
do {
let ids: [Int64] = []
let fetchedRecords = try MinimalRowID.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [record1.id!, record2.id!]
let fetchedRecords = try MinimalRowID.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalRowID()
try record.insert(db)
do {
let id: Int64? = nil
let fetchedRecord = try MinimalRowID.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try MinimalRowID.filter(key: record.id).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
}
}
}
// MARK: - Exists
@@ -321,6 +321,81 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalSingle()
record1.UUID = "theUUID1"
try record1.insert(db)
let record2 = MinimalSingle()
record2.UUID = "theUUID2"
try record2.insert(db)
do {
let cursor = try MinimalSingle.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalSingle()
record1.UUID = "theUUID1"
try record1.insert(db)
let record2 = MinimalSingle()
record2.UUID = "theUUID2"
try record2.insert(db)
do {
let fetchedRecords = try MinimalSingle.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = try MinimalSingle.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let fetchedRecord = try MinimalSingle.filter(key: ["UUID": record.UUID]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
}
}
// MARK: - Fetch With Primary Key
@@ -395,6 +470,80 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalSingle()
record1.UUID = "theUUID1"
try record1.insert(db)
let record2 = MinimalSingle()
record2.UUID = "theUUID2"
try record2.insert(db)
do {
let UUIDs: [String] = []
let cursor = try MinimalSingle.filter(keys: UUIDs).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let cursor = try MinimalSingle.filter(keys: UUIDs).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = MinimalSingle()
record1.UUID = "theUUID1"
try record1.insert(db)
let record2 = MinimalSingle()
record2.UUID = "theUUID2"
try record2.insert(db)
do {
let UUIDs: [String] = []
let fetchedRecords = try MinimalSingle.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = try MinimalSingle.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
do {
let id: String? = nil
let fetchedRecord = try MinimalSingle.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try MinimalSingle.filter(key: record.UUID).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
}
}
}
// MARK: - Exists
@@ -390,6 +390,79 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let cursor = try Person.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Person.filter(keys: [["rowid": record1.id], ["rowid": record2.id]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Person.filter(keys: [["rowid": record1.id], ["rowid": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.id!, record1.id!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let fetchedRecords = try Person.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Person.filter(keys: [["rowid": record1.id], ["rowid": record2.id]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
}
do {
let fetchedRecords = try Person.filter(keys: [["rowid": record1.id], ["rowid": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Person(name: "Arthur")
try record.insert(db)
let fetchedRecord = try Person.filter(key: ["rowid": record.id]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertTrue(fetchedRecord.age == record.age)
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
}
}
// MARK: - Fetch With Primary Key
@@ -462,6 +535,78 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let ids: [Int64] = []
let cursor = try Person.filter(keys: ids).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let ids = [record1.id!, record2.id!]
let cursor = try Person.filter(keys: ids).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let ids: [Int64] = []
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [record1.id!, record2.id!]
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Person(name: "Arthur")
try record.insert(db)
do {
let id: Int64? = nil
let fetchedRecord = try Person.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Person.filter(key: record.id).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertTrue(fetchedRecord.age == record.age)
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
}
}
}
// MARK: - Exists
@@ -344,6 +344,78 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Citizenship(personName: "Arthur", countryName: "France", native: true)
try record1.insert(db)
let record2 = Citizenship(personName: "Barbara", countryName: "France", native: false)
try record2.insert(db)
do {
let cursor = try Citizenship.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": record2.personName, "countryName": record2.countryName]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.personName }), Set([record1.personName, record2.personName]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": nil, "countryName": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.personName, record1.personName)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Citizenship(personName: "Arthur", countryName: "France", native: true)
try record1.insert(db)
let record2 = Citizenship(personName: "Barbara", countryName: "France", native: false)
try record2.insert(db)
do {
let fetchedRecords = try Citizenship.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": record2.personName, "countryName": record2.countryName]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.personName }), Set([record1.personName, record2.personName]))
}
do {
let fetchedRecords = try Citizenship.filter(keys: [["personName": record1.personName, "countryName": record1.countryName], ["personName": nil, "countryName": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.personName, record1.personName!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Citizenship(personName: "Arthur", countryName: "France", native: true)
try record.insert(db)
let fetchedRecord = try Citizenship.filter(key: ["personName": record.personName, "countryName": record.countryName]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.personName == record.personName)
XCTAssertTrue(fetchedRecord.countryName == record.countryName)
XCTAssertTrue(fetchedRecord.native == record.native)
}
}
// MARK: - Exists
@@ -103,6 +103,20 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Item(email: "item@example.com")
try record.insert(db)
let fetchedRecord = try Item.filter(key: ["email": record.email]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.email == record.email)
}
}
// MARK: - Fetch With Primary Key
@@ -176,4 +190,78 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Item(name: "Table")
try record1.insert(db)
let id1 = db.lastInsertedRowID
let record2 = Item(name: "Chair")
try record2.insert(db)
let id2 = db.lastInsertedRowID
do {
let ids: [Int64] = []
let cursor = try Item.filter(keys: ids).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let ids = [id1, id2]
let cursor = try Item.filter(keys: ids).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.name! }), Set([record1, record2].map { $0.name! }))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Item(name: "Table")
try record1.insert(db)
let id1 = db.lastInsertedRowID
let record2 = Item(name: "Chair")
try record2.insert(db)
let id2 = db.lastInsertedRowID
do {
let ids: [Int64] = []
let fetchedRecords = try Item.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [id1, id2]
let fetchedRecords = try Item.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.name! }), Set([record1, record2].map { $0.name! }))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Item(name: "Table")
try record.insert(db)
let id = db.lastInsertedRowID
do {
let id: Int64? = nil
let fetchedRecord = try Item.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Item.filter(key: id).fetchOne(db)!
XCTAssertTrue(fetchedRecord.name == record.name)
}
}
}
}
@@ -386,6 +386,79 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let cursor = try Person.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Person.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Person.filter(keys: [["id": record1.id], ["id": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.id!, record1.id!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let fetchedRecords = try Person.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Person.filter(keys: [["id": record1.id], ["id": record2.id]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set([record1.id, record2.id]))
}
do {
let fetchedRecords = try Person.filter(keys: [["id": record1.id], ["id": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.id, record1.id!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Person(name: "Arthur")
try record.insert(db)
let fetchedRecord = try Person.filter(key: ["id": record.id]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertTrue(fetchedRecord.age == record.age)
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
}
}
// MARK: - Fetch With Primary Key
@@ -458,6 +531,78 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let ids: [Int64] = []
let cursor = try Person.filter(keys: ids).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let ids = [record1.id!, record2.id!]
let cursor = try Person.filter(keys: ids).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Person(name: "Arthur")
try record1.insert(db)
let record2 = Person(name: "Barbara")
try record2.insert(db)
do {
let ids: [Int64] = []
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let ids = [record1.id!, record2.id!]
let fetchedRecords = try Person.filter(keys: ids).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Person(name: "Arthur")
try record.insert(db)
do {
let id: Int64? = nil
let fetchedRecord = try Person.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Person.filter(key: record.id).fetchOne(db)!
XCTAssertTrue(fetchedRecord.id == record.id)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertTrue(fetchedRecord.age == record.age)
XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond.
}
}
}
// MARK: - Exists
@@ -336,6 +336,77 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let cursor = try Pet.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let fetchedRecords = try Pet.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
let fetchedRecord = try Pet.filter(key: ["UUID": record.UUID]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
XCTAssertTrue(fetchedRecord.name == record.name)
}
}
// MARK: - Fetch With Primary Key
@@ -406,6 +477,76 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
do {
let id: String? = nil
let fetchedRecord = try Pet.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Pet.filter(key: record.UUID).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
XCTAssertTrue(fetchedRecord.name == record.name)
}
}
}
// MARK: - Exists
@@ -327,6 +327,81 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Email()
record1.email = "me@domain.com"
try record1.insert(db)
let record2 = Email()
record2.email = "you@domain.com"
try record2.insert(db)
do {
let cursor = try Email.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Email.filter(keys: [["email": record1.email], ["email": record2.email]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set([record1.email, record2.email]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Email.filter(keys: [["email": record1.email], ["email": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.email, record1.email)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Email()
record1.email = "me@domain.com"
try record1.insert(db)
let record2 = Email()
record2.email = "you@domain.com"
try record2.insert(db)
do {
let fetchedRecords = try Email.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Email.filter(keys: [["email": record1.email], ["email": record2.email]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set([record1.email, record2.email]))
}
do {
let fetchedRecords = try Email.filter(keys: [["email": record1.email], ["email": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.email, record1.email!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Email()
record.email = "me@domain.com"
try record.insert(db)
let fetchedRecord = try Email.filter(key: ["email": record.email]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.email == record.email)
}
}
// MARK: - Fetch With Primary Key
@@ -401,6 +476,80 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Email()
record1.email = "me@domain.com"
try record1.insert(db)
let record2 = Email()
record2.email = "you@domain.com"
try record2.insert(db)
do {
let emails: [String] = []
let cursor = try Email.filter(keys: emails).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let emails = [record1.email!, record2.email!]
let cursor = try Email.filter(keys: emails).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.email! }), Set(emails))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Email()
record1.email = "me@domain.com"
try record1.insert(db)
let record2 = Email()
record2.email = "you@domain.com"
try record2.insert(db)
do {
let emails: [String] = []
let fetchedRecords = try Email.filter(keys: emails).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let emails = [record1.email!, record2.email!]
let fetchedRecords = try Email.filter(keys: emails).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.email }), Set(emails))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Email()
record.email = "me@domain.com"
try record.insert(db)
do {
let id: String? = nil
let fetchedRecord = try Email.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Email.filter(key: record.email).fetchOne(db)!
XCTAssertTrue(fetchedRecord.email == record.email)
}
}
}
// MARK: - Exists
+3 -19
View File
@@ -15,29 +15,13 @@ private struct Person : RowConvertible, TableMapping {
class RecordUniqueIndexTests: GRDBTestCase {
func testKeyFilterRequiresUniqueIndex() throws {
func testKeyFilterAcceptsUniqueIndex() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
_ = try Person.filter(db, keys: [["id": nil]])
_ = try Person.filter(db, keys: [["email": nil]])
do {
_ = try Person.filter(db, keys: [["id": nil, "email": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) email, id")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) email, id")
}
do {
_ = try Person.filter(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_MISUSE)
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) name")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) name")
}
_ = try Person.filter(keys: [["id": nil]]).fetchOne(db)
_ = try Person.filter(keys: [["email": nil]]).fetchOne(db)
}
}
}
@@ -66,7 +66,7 @@ class RecordWithColumnNameManglingTests: GRDBTestCase {
try record.save(db)
// Nothing special here
XCTAssertFalse(record.hasPersistentChangedValues)
XCTAssertFalse(record.hasDatabaseChanges)
}
do {
let record = try BadlyMangledStuff.fetchOne(db, "SELECT id AS mangled_id, name AS mangled_name FROM stuffs")!
@@ -76,7 +76,7 @@ class RecordWithColumnNameManglingTests: GRDBTestCase {
// But here lies the problem with BadlyMangledStuff.
// It should not be edited:
XCTAssertTrue(record.hasPersistentChangedValues)
XCTAssertTrue(record.hasDatabaseChanges)
}
}
}
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more