Compare commits

...
644 Commits
Author SHA1 Message Date
Gwendal Roué 786ab176c9 v2.0 2017-09-16 18:37:27 +02:00
Gwendal Roué 973af107da More performance tests, upgrade SQLite.swift submodule 2017-09-16 18:25:24 +02:00
Gwendal Roué 1911ef0172 Merge branch 'master' of github.com:groue/GRDB.swift into Swift4
Conflicts:
	README.md
2017-09-16 14:49:39 +02:00
Gwendal Roué d2e9b340c9 Adapt FT5 support for the non optional Database.primaryKey(_:) 2017-09-15 19:05:39 +02:00
Gwendal Roué 5b487d1722 Fix compiler warning 2017-09-15 19:01:49 +02:00
Gwendal Roué a91da59448 Database.primaryKey(_:) no longer returns an Optional. PrimaryKeyInfo.isRowID tells whether the primary key is the rowed. 2017-09-15 09:00:56 +02:00
Gwendal Roué 2846254304 Improve make distclean, with submodules 2017-09-14 21:51:11 +02:00
Gwendal Roué 5fe765dd29 Improve make distclean 2017-09-14 21:49:06 +02:00
Gwendal Roué 9815f44134 Remove sqlite3.h from the distribution 2017-09-14 20:34:22 +02:00
Gwendal Roué 3f8969b88f PerformanceComparisonTests: update Realm to 2.10.0, SQLite.swift to latest swift-4 branch 2017-09-13 08:11:31 +02:00
Gwendal Roué 4fc7a44a9d Tweak JSONSynchronization playground 2017-09-12 08:30:05 +02:00
Gwendal Roué e132688e00 Simplify JSONSynchronization playground 2017-09-12 08:25:09 +02:00
Gwendal Roué 588df57840 Fix typo 2017-09-12 08:13:23 +02:00
Gwendal Roué 4a8ca6fdc1 TODO 2017-09-11 09:04:05 +02:00
Gwendal Roué 2bb2493731 Turn MutablePersistable.databaseDictionary into a property 2017-09-11 08:53:56 +02:00
Gwendal Roué c61949ceaf DatabaseError.description contains primary result code, not extended result code. 2017-09-11 08:12:43 +02:00
Gwendal Roué 3fce1e00c9 Introduce AnyDatabaseReader and AnyDatabaseWriter 2017-09-10 13:37:48 +02:00
Gwendal Roué 2f2add1c49 Update podspec 2017-09-09 13:29:24 +02:00
Gwendal Roué 697acb103f Cleanup 2017-09-08 21:45:35 +02:00
Gwendal Roué c830e43e8f Update JSONSynchronization playground with Record.updateChanges(_:) 2017-09-08 21:41:39 +02:00
Gwendal Roué 834ef45ca6 Document how to convert a Row to Dictionary 2017-09-08 20:38:03 +02:00
Gwendal Roué 279faa13e9 Less TODO 2017-09-08 13:23:20 +02:00
Gwendal Roué 0309abca6f Tests for Statement.SelectionInfo.description 2017-09-08 13:18:45 +02:00
Gwendal Roué fedee67bda Enhance documentation of fatal errors that happen during value conversion 2017-09-08 08:19:09 +02:00
Gwendal Roué a6c3566aa5 Record.updateChanges(_:) documentation 2017-09-08 08:08:07 +02:00
Gwendal Roué 52fa24e1c4 QueryInterfaceRequest.deleteAll() now honors the order and limit clauses when SQLite is compiled with the SQLITE_ENABLE_UPDATE_DELETE_LIMIT option 2017-09-08 07:07:43 +02:00
Gwendal Roué a7ecf41e3b QueryInterfaceRequest.deleteAll() now honors the order and limit clauses. New Set(cursor) initialiser. 2017-09-07 19:22:21 +02:00
Gwendal Roué e68e5f6265 Tests for Record.updateChangedColumns(_:) 2017-09-06 09:12:38 +02:00
Gwendal Roué aad5a9b060 Less TODO 2017-09-06 08:59:02 +02:00
Gwendal Roué aa064029ec More typed cursor tests 2017-09-06 08:58:27 +02:00
Gwendal Roué e84060e01c More value tests 2017-09-06 08:50:30 +02:00
Gwendal Roué f4f72ebb43 Record.updateChanges(_:) 2017-09-06 08:36:13 +02:00
Gwendal Roué da51e81e38 Fix typo 2017-09-05 09:01:57 +02:00
Gwendal Roué 247cbdd0d0 Date and NSDate interpret database numbers as unix timestamps. 2017-09-05 08:58:17 +02:00
Gwendal Roué c528740154 Documentation 2017-09-05 07:57:00 +02:00
Gwendal Roué 37b357b050 TODO 2017-09-05 05:50:11 +02:00
Gwendal Roué 18c376979d Reformat links to other Swift versions 2017-09-03 11:39:25 +02:00
Gwendal Roué 9cc4357a70 Merge branch 'master' of github.com:groue/GRDB.swift into Swift4 2017-09-03 11:03:36 +02:00
Gwendal Roué f2d35a052f Cleanup 2017-09-03 10:54:13 +02:00
Gwendal Roué 221f378d10 Tests for zero-length blobs as function arguments 2017-09-03 10:31:02 +02:00
Gwendal Roué 06a8c8b940 GRDB is now able to store and load zero-length blobs. 2017-09-03 10:09:00 +02:00
Gwendal Roué eee80b421a Hide StatementCursor from public interface 2017-09-03 08:48:31 +02:00
Gwendal Roué f6e22c3636 Fix Typo 2017-09-02 16:34:07 +02:00
Gwendal Roué 20d77fbba5 README.md 2017-09-02 16:32:52 +02:00
Gwendal Roué 0393ebe012 Try to force SWIFT_VERSION to 4.0 with pod_target_xcconfig 2017-09-02 12:42:50 +02:00
Gwendal Roué 2beddcf77b Cleanup 2017-09-02 12:42:07 +02:00
Gwendal Roué e784ebbcdd Remove public StatementArguments() 2017-08-31 19:35:11 +02:00
Gwendal Roué 30ee538dbd StatementArguments(), tests, changeling 2017-08-30 20:07:34 +02:00
Gwendal Roué 7939ba6e05 Expose RowCursor.statement, StatementCursor.statement, Statement.index(ofColumn:) 2017-08-30 14:06:50 +02:00
Gwendal Roué 2785e69fc1 Data adopts StatementColumnConvertible 2017-08-29 19:27:47 +02:00
Gwendal Roué d472c1696d Workaround SR-5707 2017-08-28 13:49:08 +02:00
Gwendal Roué d9cfa71fc7 MutablePersistable.databaseDictionary() return [String: DatabaseValue] 2017-08-28 08:13:20 +02:00
Gwendal Roué 715e12912b New MutablePersistable.databaseDictionary() convenience method 2017-08-25 18:20:35 +02:00
Gwendal Roué b182fe27f6 Merge branch 'Swift4' of github.com:groue/GRDB.swift into Swift4 2017-08-25 17:43:19 +02:00
Gwendal Roué 5594b33933 Performance tests: distinguish fetching records with change tracking from simple record structs 2017-08-25 17:43:15 +02:00
Gwendal Roué 059b8800f6 TODO 2017-08-25 14:00:12 +02:00
Gwendal Roué 9f687b1848 Documentation 2017-08-25 06:06:59 +02:00
Gwendal Roué a4a05b1f0a Introduce DatabaseValueCursor, NullableDatabaseValueCursor 2017-08-25 05:54:37 +02:00
Gwendal Roué 1a7b0b0626 Introduce RecordCursor 2017-08-24 09:08:29 +02:00
Gwendal Roué 4c467e46cf CHANGELOG 2017-08-24 08:17:09 +02:00
Gwendal Roué fa71edeb07 Consistently use GRDB as the library name 2017-08-23 13:59:51 +02:00
Gwendal Roué 4ff436371d README 2017-08-23 13:57:25 +02:00
Gwendal Roué 9d8fa0bc5a Documentation 2017-08-23 10:03:03 +02:00
Gwendal Roué 1a8ecd7889 Documentation 2017-08-23 10:01:43 +02:00
Gwendal Roué f6614fdfda Documentation 2017-08-23 10:00:02 +02:00
Gwendal Roué a6055df756 New "Documentation diff" section in CHANGELOG 2017-08-23 08:43:35 +02:00
Gwendal Roué 5af91c5eab Documentation 2017-08-23 08:24:08 +02:00
Gwendal Roué 41974c4a46 Documentation 2017-08-23 08:21:28 +02:00
Gwendal Roué f001b5bd76 Documentation 2017-08-23 08:19:29 +02:00
Gwendal Roué 28cf457853 Add a performance test target that doesn't depend on Core Data, FMDB, Realm, and SQLite.swift. 2017-08-23 08:17:47 +02:00
Gwendal Roué 8ccc23333d Replace DatabaseCursor with new concrete cursors RowCursor, StatementColumnCursor, NullableStatementColumnCursor, and StatementCursor. 2017-08-23 08:16:30 +02:00
Gwendal Roué d95954d980 TODO: learn about Decoder.dateEncodingStrategy 2017-08-22 09:04:00 +02:00
Gwendal Roué 3506881c2a Documentation 2017-08-21 19:23:10 +02:00
Gwendal Roué 51d127c378 TODO.md 2017-08-21 08:48:03 +02:00
Gwendal Roué 2d5dd7ef63 Update GRDBProfiling project 2017-08-21 08:47:53 +02:00
Gwendal Roué ef23ba55a1 sqlite3.h is a private header when the SQLite3 module is used 2017-08-21 08:47:31 +02:00
Gwendal Roué ffdbf2f3f1 TODO.md 2017-08-20 05:33:27 +02:00
Gwendal Roué 56cad83f55 CHANGELOG.md 2017-08-19 16:34:28 +02:00
Gwendal Roué 719f33f7a7 GRDBDemoiOS: use default IPHONEOS_DEPLOYMENT_TARGET 2017-08-19 16:09:30 +02:00
Gwendal Roué 700ffacdb1 Minor 2017-08-19 15:55:36 +02:00
Gwendal Roué a6ef4ed55c Minor 2017-08-19 15:53:50 +02:00
Gwendal Roué c5da564fb3 Use built-in SQLite3 module when available 2017-08-19 15:21:44 +02:00
Gwendal Roué a6b04ebb64 FTS5 Cleanup 2017-08-19 12:35:45 +02:00
Gwendal Roué 99ba6db257 Documentation 2017-08-19 11:42:45 +02:00
Gwendal Roué a3cddb72b9 Documentation: rename "person" to "player" (and avoid both "persons" and "people") 2017-08-19 10:36:28 +02:00
Gwendal Roué 2a9e896095 Remove documentation for PrimaryKeyInfo (reference is enough) 2017-08-19 10:25:20 +02:00
Gwendal Roué 89d522d325 Rename "point of interest" to "place" (addresses #246) 2017-08-19 10:21:57 +02:00
Gwendal Roué 3c4ff587ca Documentation 2017-08-19 10:13:40 +02:00
Gwendal Roué e111529035 Documentation 2017-08-19 10:09:41 +02:00
Gwendal Roué cae1f97032 Update documentation now that TableMapping deletion methods have moved to MutablePersistable 2017-08-18 18:40:57 +02:00
Gwendal Roué 20419834a6 Sequence.Iterator.Element -> Sequence.Element 2017-08-18 18:10:56 +02:00
Gwendal Roué 5dabc2a20b CHANGELOG.md 2017-08-18 18:09:28 +02:00
Gwendal Roué c700f5fc68 Move TableMapping deletion methods to MutablePersistable (prevent TableMapping from being able to modify the database) 2017-08-18 17:15:10 +02:00
Gwendal Roué 0b71cf86f2 Less GRDB 2.0 TODO 2017-08-18 16:49:12 +02:00
Gwendal Roué 96159bd09c RowConvertible.fetchCursor(_:keys:) returns a non-optional cursor. 2017-08-18 16:48:06 +02:00
Gwendal Roué bcff802ccb CHANGELOG.md 2017-08-18 16:29:18 +02:00
Gwendal Roué 376d295853 Replace TableMapping.selectsRowID with TableMapping.databaseSelection 2017-08-18 16:27:24 +02:00
Gwendal Roué 0030ad1804 CHANGELOG.md 2017-08-18 14:57:55 +02:00
Gwendal Roué 4ec3e0f7d8 Drop deprecated TableMapping.primaryKeyRowComparator(_:) 2017-08-18 14:30:28 +02:00
Gwendal Roué e36219e408 Thanks @bfad 2017-08-18 14:22:15 +02:00
Gwendal Roué 8f8f53a697 Fix CocoaPods tests by bumping .swift-version 2017-08-18 14:22:15 +02:00
Gwendal Roué 567292c72f Fix SPM test target
Thanks to @aciidb0mb3r: https://bugs.swift.org/browse/SR-5697?focusedCommentId=27793&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-27793
2017-08-18 14:22:15 +02:00
Gwendal Roué b744f73a76 Restore test target in Package.swift, for swift test 2017-08-18 14:22:15 +02:00
Gwendal Roué da440a5e16 Swift 4 + SPM
- Upgrade Tests/SPM package layout and format to version 4, and have `make test_install_SPM` succeed
- Update .gitignore in order to ignore Package.resolved instead of Package.pins
2017-08-18 14:22:15 +02:00
Brad Lindsay 017af1d5c3 Update Package.swift for version 4 tooling 2017-08-18 14:22:14 +02:00
Gwendal Roué 1f5d75d8e9 Fix a compiler error in Xcode 9 beta 5 (and improve tests for DatabaseValue conformance to Equatable) 2017-08-18 14:22:14 +02:00
Gwendal Roué 8b80abc701 TODO.md 2017-08-18 14:22:14 +02:00
Gwendal Roué dc75ca4caf SE-0166 2017-08-18 14:22:14 +02:00
Gwendal Roué d7d4c0a54d Formatting 2017-08-18 14:22:14 +02:00
Gwendal Roué 823b094b60 SE-0168 2017-08-18 14:22:14 +02:00
Gwendal Roué 06a6c982aa SE-0148 2017-08-18 14:22:14 +02:00
Gwendal Roué 1d15ef01f9 Update Travis CI to use Xcode 9 2017-08-18 14:20:35 +02:00
Gwendal Roué f72ffcbb43 SE-0165 2017-08-18 14:20:35 +02:00
Gwendal Roué e0f2305cd9 SE-0104 2017-08-18 14:20:35 +02:00
Gwendal Roué 210939d2c1 SE-0169 2017-08-18 14:20:35 +02:00
Gwendal Roué 2fd071d90e NSLocalizedDescriptionKey 2017-08-18 14:20:35 +02:00
Gwendal Roué badec62cdd SE-0110 2017-08-18 14:20:35 +02:00
Gwendal Roué 895cda4de7 Xcode 9 beta 3 project updates 2017-08-18 14:20:35 +02:00
Gwendal Roué 21fdc9f350 v1.3.0 2017-08-18 13:13:24 +02:00
Gwendal Roué 398c0ef687 Documentation 2017-08-18 12:25:22 +02:00
Gwendal Roué 3b0a9aef3c No more SQLite 3.20.0 TODO 2017-08-18 08:52:48 +02:00
Gwendal Roué 48ec0916bf Use SQLITE_PREPARE_PERSISTENT flag for cached statements 2017-08-18 08:52:23 +02:00
Gwendal Roué 10af87a7d0 SQLite 3.20.0 2017-08-18 08:35:02 +02:00
Gwendal Roué 96e7996f37 SQLite 3.20.0 TODO 2017-08-03 10:19:52 +02:00
Gwendal Roué 0f7af931a9 SQLite 3.20.0 TODO 2017-08-03 10:16:17 +02:00
Gwendal Roué cfd2d80b78 Fix typo 2017-07-30 15:22:13 +02:00
Gwendal Roué 0386c01aa9 CHANGELOG 2017-07-29 14:36:02 +02:00
Gwendal Roué 2c39c91ac6 CHANGELOG 2017-07-29 13:01:49 +02:00
Gwendal Roué 0eb51e3e8b Int8, Int16, UInt, UInt8, UInt16, UInt32, UInt64 adopt DatabaseValueConvertible and StatementColumnConvertible 2017-07-29 12:58:35 +02:00
Gwendal Roué bb931e9da7 FTS5.api(_:) can now throw an error 2017-07-21 18:34:19 +02:00
Gwendal Roué 7b2e672496 Cleanup 2017-07-21 17:59:04 +02:00
Gwendal Roué cdc6370ee5 Restore column ordering in filter(db, keys: [["a": ..., "b": ...], ...]) removed in 2b2e92c810 2017-07-21 13:45:24 +02:00
Gwendal Roué cc762e4e1d TODO 2017-07-21 12:20:32 +02:00
Gwendal Roué ed525bd1d8 Cleanup 2017-07-21 12:15:35 +02:00
Gwendal Roué 2b2e92c810 Cleanup 2017-07-21 12:13:03 +02:00
Gwendal Roué 44d31ead76 Implement deleteAll(_:keys:), deleteOne(_🔑) on top of the Query Interface 2017-07-21 11:19:24 +02:00
Gwendal Roué ec163e94eb Implement fetchCursor(_:keys:), fetchAll(_:keys:), and fetchOne(_🔑) on top of the Query Interface 2017-07-21 09:13:20 +02:00
Gwendal Roué ec2ac33fec TODO.md 2017-07-21 07:58:25 +02:00
Gwendal Roué 20bda2af26 v1.2.2 2017-07-20 19:30:39 +02:00
Gwendal Roué 7a49f6293d CHANGELOG.md 2017-07-20 17:50:14 +02:00
Gwendal Roué 81b21010f1 Fix memory leak with Configuration.trace 2017-07-20 17:47:11 +02:00
Gwendal Roué 2526e0a2f7 Fix links to reference documentation 2017-07-19 19:40:19 +02:00
Gwendal Roué af1e8470c9 v1.2.1 2017-07-19 09:38:25 +02:00
Gwendal Roué dfd9da68a7 CHANGELOG 2017-07-19 08:32:21 +02:00
Gwendal Roué 5e702234f4 Upgrade SQLite to v3.19.3 2017-07-19 08:31:32 +02:00
Gwendal Roué 9020dcca9a CHANGELOG 2017-07-19 08:28:02 +02:00
Gwendal Roué 930a4e4c1d Improve implementation comments in DatabasePool.readFromCurrentState 2017-07-19 08:22:23 +02:00
Gwendal Roué 4db77f96b7 Improve implementation comments in DatabasePool.readFromCurrentState 2017-07-18 16:34:50 +02:00
Gwendal Roué cc12c046b9 func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) bugfix 2017-07-18 09:00:49 +02:00
Gwendal Roué f5c63e0997 Remove unused method 2017-07-18 07:48:43 +02:00
Gwendal Roué 29a26800b7 Cleanup 2017-07-17 20:20:20 +02:00
Gwendal Roué bc5eeb3b3a expr == DatabaseValue.null is converted to expr IS NULL. 2017-07-17 20:19:19 +02:00
Gwendal Roué 40d02518b0 Cleanup 2017-07-17 15:33:09 +02:00
Gwendal Roué a2556edc69 Use sqlite3_get_autocommit
This function knows whether the database is currently inside a
transaction or not, and provides robust rollback error handling.
2017-07-17 15:33:01 +02:00
Gwendal Roué 111970fda9 Tests for public protocols and open classes
The goal of those tests is to prevent breaking changes as the one that happened in v1.2, where the DatabaseReader protocol was added a new method without any default implementation.
2017-07-13 16:53:01 +02:00
Gwendal Roué ebeb7bc969 v1.2 2017-07-13 13:17:58 +02:00
Gwendal Roué 6ccac5f69c CHANGELOG.md 2017-07-13 13:00:19 +02:00
Gwendal Roué cc41b8b259 Fix Pool bug introduced in 2add1c68ea
I think this is the bug behind this failed test suite: https://travis-ci.org/groue/GRDB.swift/jobs/253093331

In 2add1c68ea Pool has started relying on *indexes* inside its inner array of items. Those indexes weren't reliable enough: this commit brings back independence from indexes by making the Item type a class again.
2017-07-13 12:17:03 +02:00
Gwendal Roué db1a3456b7 Cleanup 2017-07-13 12:12:56 +02:00
Gwendal Roué 1b9305c073 Less TODO 2017-07-13 11:24:41 +02:00
Gwendal Roué a33814ef40 Documentation for unsafe concurrency APIs 2017-07-13 11:10:02 +02:00
Gwendal Roué 581bc9f27c Support for partial records whose encode(to:) method does not provide values for all table columns 2017-07-13 11:03:23 +02:00
Gwendal Roué 40cff0053f TODO.md 2017-07-13 09:58:42 +02:00
Gwendal Roué cc33b12b0d DatabaseReader.unsafeReentrantRead 2017-07-13 09:11:21 +02:00
Gwendal Roué 2add1c68ea Raise a fatal error when DatabasePool is used in a reentrant way 2017-07-12 20:07:05 +02:00
Gwendal Roué 380b6676a6 Statement.sql trims white space and semicolon 2017-07-12 08:45:56 +02:00
Gwendal Roué f133a36477 TODO.md 2017-07-07 17:13:25 +02:00
Gwendal Roué 5f2d6f8e2f Table creation API enhancements 2017-07-01 16:44:33 +02:00
Gwendal Roué a72c207ec5 v1.1 2017-07-01 12:04:27 +02:00
Gwendal Roué ae3c28dee1 Add missing CSQLite import 2017-07-01 11:39:52 +02:00
Gwendal Roué bd919e5209 DatabaseAggregate (fixes #236) 2017-07-01 11:39:52 +02:00
Gwendal Roué d1697756e9 Remove compiler warning 2017-06-30 07:47:14 +02:00
Gwendal Roué 83c3745165 Documentation 2017-06-30 07:47:14 +02:00
Gwendal Roué 56a4a964b7 QueryInterfaceRequest.order() clears the isReversed flag 2017-06-30 07:47:13 +02:00
Gwendal Roué c9a02faf08 Refactor AdaptedTypedRequest around AdaptedRequest 2017-06-30 07:47:13 +02:00
Gwendal Roué e59388738e FetchedRecordsController: don't assume constant row layout when comparing records 2017-06-30 07:47:13 +02:00
Gwendal Roué c8368d98eb Refactor FetchedRecordsController so that it stops using deprecated TableMapping.primaryKeyRowComparator 2017-06-30 07:47:13 +02:00
Gwendal Roué d12dad2e34 Deprecate TableMapping.primaryKeyRowComparator 2017-06-30 07:47:13 +02:00
Gwendal Roué 1ee8c73562 Fix typo 2017-06-30 03:57:36 +02:00
Gwendal Roué ad8de84257 Update Makefile for Xcode 9 beta 2 2017-06-22 19:34:11 +02:00
Gwendal Roué 48398b4913 v1.0 2017-06-20 07:54:19 +02:00
Gwendal Roué d719fe4612 Bump requirements to Xcode8.3+ / Swift 3.1 2017-06-20 07:54:19 +02:00
Gwendal Roué 034a30b444 CHANGELOG.md 2017-06-20 07:54:19 +02:00
Gwendal Roué 9609e2ac4c Database.foreignKeys(on:) 2017-06-20 07:54:19 +02:00
Gwendal Roué 66c2b72a28 Database.afterNextTransactionCommit(_:): document that the closure runs in a protected dispatch queue 2017-06-20 07:54:19 +02:00
Gwendal Roué da48b0880e CHANGELOG.md 2017-06-20 07:54:19 +02:00
Gwendal Roué 4134b1549a CHANGELOG.md 2017-06-20 07:54:19 +02:00
Gwendal Roué 7265b2535b CHANGELOG.md 2017-06-20 07:54:19 +02:00
Gwendal Roué bb638377ac CHANGELOG.md 2017-06-20 07:54:19 +02:00
Gwendal Roué 466113fc4a 🎉 2017-06-20 07:54:19 +02:00
Gwendal Roué 31aea350cb Rename Database.afterCommit(_:) to Database.afterNextTransactionCommit(_:) 2017-06-20 07:54:19 +02:00
Gwendal Roué 56869577d4 Documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué ed3c597a92 Documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué cbb607b6b0 SQLSpecificExpressible.collating(_:) inline documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué 7f64abe820 Identify experimental features in the inline documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué b43dc1ba37 Less TODO 2017-06-20 07:54:19 +02:00
Gwendal Roué 59962e5e88 Identify experimental features in the inline documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué 8eabcecb69 Fix TransactionObservationExtent.nextTransaction 2017-06-20 07:54:19 +02:00
Gwendal Roué a3ad726111 Cleanup 2017-06-20 07:54:19 +02:00
Gwendal Roué a46b4edb0a Replace experimental badge image with searchable text 2017-06-20 07:54:19 +02:00
Gwendal Roué 7059fe3815 TODO.md 2017-06-20 07:54:19 +02:00
Gwendal Roué 780f1afe91 Replace CLLocationCoordinate2DMake(_:_:) with CLLocationCoordinate2D(latitude:longitude:) 2017-06-20 07:54:19 +02:00
Gwendal Roué 2459b4e56f Foster columns gathered in an enum 2017-06-20 07:54:19 +02:00
Gwendal Roué f750cee594 Documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué 1c3824f4b9 Don't retain weak transaction observers 2017-06-20 07:54:19 +02:00
Gwendal Roué 5ba1fa856d Documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué f40a685ac9 Update performance tests for FMDB 2.7.2 2017-06-20 07:54:19 +02:00
Gwendal Roué bf3b6577d5 Deployment target of performance tests is macOS 10.12 2017-06-20 07:54:19 +02:00
Gwendal Roué 7b0659332b Realm 2.8.2 2017-06-20 07:54:19 +02:00
Gwendal Roué 19812cb015 SQLite.swift 0.11.3, FMDB 2.7.2 2017-06-20 07:54:19 +02:00
Gwendal Roué b283c80776 Documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué 49838c67ee Typo 2017-06-20 07:54:19 +02:00
Gwendal Roué 4a40bddd82 Better Database.afterCommit(_:) documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué 208b7860aa Better Database.afterCommit(_:) documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué 05e7c9470b Better Database.afterCommit(_:) documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué 2f79d5f805 Database.afterCommit(_:) 2017-06-20 07:54:19 +02:00
Gwendal Roué 1f120a04f9 CHANGELOG.md 2017-06-20 07:54:19 +02:00
Gwendal Roué 90a46f6556 Introduce TransactionObservationExtent 2017-06-20 07:54:19 +02:00
Gwendal Roué 4dff14a02a README: note about "Pure Transaction Observers", and warning about "Recursive Commits" 2017-06-20 07:54:19 +02:00
Gwendal Roué d9a9acb616 README: Introduction to Database Changes Observation 2017-06-20 07:54:19 +02:00
Gwendal Roué 8ea215931e Refactor Request
Rename TypedRequest's associated type from `Fetched` to `RowConverter`, because if TypedRequest needs a type that can decode rows, the type of the decoded rows does not need to be identical to the decoder type.

Introduce AdaptedRequest and AdaptedTypedRequest as results of Request.adapted(_:) and TypedRequest.adapted(_:), instead of the generic AnyRequest and AnyTypedRequest.
2017-06-20 07:54:19 +02:00
Gwendal Roué 6caed6aacc DatabaseMigrator documentation 2017-06-20 07:54:19 +02:00
Gwendal Roué 0c192fcb57 DatabaseMigrator.migrate(_:upTo:) 2017-06-20 07:54:19 +02:00
Gwendal Roué 3e819a5051 TODO.md 2017-06-20 07:54:19 +02:00
Gwendal Roué b31983cc3a TODO: write regression tests for #156 and #157 2017-06-20 07:54:19 +02:00
Gwendal Roué e24cb1783c Change default transaction kind to deferred (the SQLite default). 2017-06-20 07:54:19 +02:00
Gwendal Roué a913aba018 Replace persistentDictionary with encode(to:) 2017-06-20 07:54:19 +02:00
Gwendal Roué 35d34ab524 Remove obsolete documentation of QueryInterfaceRequest.contains(_:) 2017-06-20 07:54:19 +02:00
Gwendal Roué 604cf6b522 Remove QueryInterfaceRequest.contains(_:) 2017-06-20 07:54:19 +02:00
Gwendal Roué e987695732 Remove obsolete documentation of QueryInterfaceRequest.exists() 2017-06-20 07:54:19 +02:00
Gwendal Roué 09f37a86ad Fix link of experimental badges 2017-06-20 07:54:19 +02:00
Gwendal Roué ff32f99610 Better experimental description 2017-06-20 07:54:19 +02:00
Gwendal Roué 4cd099ef30 Fix link of experimental badges 2017-06-20 07:54:19 +02:00
Gwendal Roué 54d3b0eabc Flag Request.adapted(_:) as experimental 2017-06-20 07:54:19 +02:00
Gwendal Roué b3d731b040 Remove QueryInterfaceRequest.exists() 2017-06-20 07:54:19 +02:00
Gwendal Roué 6629ec48a3 Flag SQLExpressionFunction, SQLFunctionName, SQLExpressionUnary, SQLExpressionBinary, SQLExpressionFunction, QueryInterfaceRequest.exists() as experimental 2017-06-20 07:54:19 +02:00
Gwendal Roué 19c273771d Flag row adapters as experimental 2017-06-20 07:54:19 +02:00
Gwendal Roué e7b6919bc1 Experimental badge and FAQ (with workaround https://github.com/isaacs/github/issues/316) 2017-06-20 07:54:19 +02:00
Gwendal Roué 60e6c7d250 Remove DatabaseCoder 2017-06-20 07:54:19 +02:00
Gwendal Roué 4feeb0e608 Help Xcode 9 beta 1 users in the README (completes #230) 2017-06-09 06:53:20 +02:00
Gwendal Roué b3243efdf5 Update Makefile for Xcode 8.3.3 2017-06-09 06:44:26 +02:00
Gwendal Roué 60a23bb280 More Xcode-9 fixes 2017-06-09 06:44:26 +02:00
Gwendal Roué 973f38727d More Xcode-9 fixes 2017-06-09 06:44:26 +02:00
David Hart deaac5808d Make the bug-fix conditional to continue building on 3.1 2017-06-09 06:44:26 +02:00
David Hart 22dc01610e Fix compilation with Xcode 9 in compatibilty mode 2017-06-09 06:44:26 +02:00
Gwendal Roué fe702d8fea The magic command that helps finding unwanted git tags 2017-06-01 10:02:59 +02:00
Gwendal Roué 10e669423f Use the dbValue identifier for variables of type DatabaseValue 2017-06-01 08:35:14 +02:00
Gwendal Roué fbf146657e CHANGELOG for SQLite 3.19.2 2017-05-28 15:48:46 +02:00
Gwendal Roué 8667fab206 v0.110.0 2017-05-28 14:29:41 +02:00
Gwendal Roué e974cd4b33 Fix make test_SPM by backporting 7adfb3c233fc3fdeacbb3933d7d13b4c2a3a2eed and using the default Swift compiler unless TOOLCHAIN is defined 2017-05-28 14:02:13 +02:00
Gwendal Roué 43c96803be CHANGELOG: announce removal of deprecation warning for sqlite3_trace 2017-05-28 13:32:17 +02:00
Gwendal Roué 70b42a5633 CHANGELOG: announce Travis-CI integration 2017-05-28 13:24:21 +02:00
Gwendal Roué 9f989f7706 CHANGELOG: announce SQLCipher v3.4.1 2017-05-28 13:20:27 +02:00
swiftlyfalling 4d976ef803 Add Travis-CI build status badge to README.md 2017-05-28 13:16:47 +02:00
Gwendal Roué 02257fd78f Update SQLite version in documentation 2017-05-28 13:15:41 +02:00
Gwendal Roué 929c8f49a6 Upgrade SQLite to v3.19.2 2017-05-28 13:15:41 +02:00
Gwendal Roué a6ec38c805 Upgrade SQLite to v3.19.1 2017-05-28 13:15:41 +02:00
Gwendal Roué e5ec8ea3b2 Update SQLite version in documentation 2017-05-28 13:15:41 +02:00
Gwendal Roué 36ac5a2802 CHANGELOG for SQLite 3.19.0 2017-05-28 13:15:41 +02:00
Gwendal Roué b5beff5030 Fix SelectStatementTests.testSelectionInfo SPM test 2017-05-28 13:15:41 +02:00
Gwendal Roué d1d1a5da77 Improve SelectionInfo for SQLite 3.19.0 2017-05-28 13:15:41 +02:00
Gwendal Roué 713d58612e SQLite 3.19.0 wants authorizer callbacks to be prepared from NULL inputs 2017-05-28 13:15:41 +02:00
Gwendal Roué bd0990deb4 Upgrade SQLite to v3.19.0 2017-05-28 13:15:41 +02:00
Gwendal Roué 35e8d9c12b Update SQLCipher version in documentation 2017-05-28 11:40:26 +02:00
Gwendal Roué 1fb7f9ff5b Disable query tracing inside EncryptionTests.testExportPlainTextDatabaseToEncryptedDatabase (workaround https://github.com/sqlcipher/sqlcipher/issues/216) 2017-05-28 11:40:26 +02:00
Gwendal Roué 7eecb059e6 Disable EncryptionTests.testExportPlainTextDatabaseToEncryptedDatabase until https://github.com/sqlcipher/sqlcipher/issues/216 is fixed 2017-05-28 11:40:26 +02:00
Gwendal Roué ba8375adb1 Upgrade SQLCipher to v3.4.1 2017-05-28 11:40:26 +02:00
Gwendal Roué 2ef547c461 Fix flaky busy handler tests 2017-05-27 15:04:27 +02:00
Gwendal Roué a34784ca73 TODO: Fix flaky ConcurrencyTests.testReaderInDeferredTransactionDuringDefaultTransaction 2017-05-25 23:02:31 +02:00
Gwendal Roué 5594d46c2d Makefile cleanup 2017-05-25 19:57:51 +02:00
Gwendal Roué dc7a1e3f41 Delete Package.pins files in clean and distclean Makefile targets 2017-05-25 19:57:46 +02:00
Gwendal Roué 68732487f9 Ignore Package.pins files 2017-05-25 19:57:41 +02:00
Gwendal Roué 5ea1d4376d Remove quotes around "GRDB [SPM] (Xcode 8.3, macOS 10.12)" TID in .travis.yml 2017-05-25 19:57:36 +02:00
Gwendal Roué 9cb8b205c5 Rewrite tests that check that closing a connection does not break unclosed statements (this should fix #216, for good this time!) 2017-05-25 19:25:47 +02:00
Gwendal Roué a35c453423 Fix flaky test ConcurrencyTests.testBusyCallback 2017-05-25 18:54:02 +02:00
Gwendal Roué e7f91d7c25 TODO: fix flaky test ConcurrencyTests.testBusyCallback 2017-05-25 18:43:21 +02:00
Gwendal Roué 4886f43463 Rewrite tests that check that closing a connection does not break unclosed statements (this should fix #216) 2017-05-25 18:39:38 +02:00
Gwendal Roué 929c8ac2b5 GRDB has no longer iterators, but cursors 2017-05-25 18:23:14 +02:00
Gwendal Roué 1438934aa6 Extract deployment targets in dedicated xcconfig files. 2017-05-25 17:13:45 +02:00
Gwendal Roué ec65335fcd Use sqlite3_trace_v2 when available (addresses #100) 2017-05-25 17:13:04 +02:00
Gwendal Roué 39d31dbd11 Merge pull request #218 from swiftlyfalling/travis_add_spm_test
Add `make test_SPM` to .travis.yml
2017-05-25 13:53:26 +02:00
swiftlyfalling 6c5be7a169 Minor tweaks 2017-05-24 11:15:59 -04:00
swiftlyfalling b45894fd51 Add test_SPM to travis.yml 2017-05-24 11:13:32 -04:00
swiftlyfalling a660b4e5c4 Merge remote-tracking branch 'groue/master' 2017-05-24 11:04:43 -04:00
Gwendal Roué e11c88cf05 Merge pull request #215 from swiftlyfalling/travis-ci-xcode-82-fix
Makefile Fix: Xcode 8.2 max-iOS builds
2017-05-24 07:53:25 +02:00
swiftlyfalling 40f930f08a Fix Xcode 8.2 max-iOS builds
- Fixes errant “fancy quotes”
2017-05-23 16:57:15 -04:00
swiftlyfalling 0c55e7819d Merge remote-tracking branch 'groue/master' 2017-05-23 16:54:04 -04:00
Gwendal Roué 3c17ee941f Documentation 2017-05-23 11:44:43 +02:00
Gwendal Roué 5a67ca0411 Foster asRequest(of:) 2017-05-23 11:38:17 +02:00
Gwendal Roué 63d04a6707 TODO: upgrade SQLCipher 2017-05-23 08:17:31 +02:00
Gwendal Roué 676a116cda Merge pull request #213 from swiftlyfalling/travis-ci-integration
Continuous Integration (w/ Travis CI)
2017-05-23 07:45:43 +02:00
Gwendal Roué 55435fd324 v0.109.0 2017-05-22 19:58:48 +02:00
Gwendal Roué 612f8059b8 Documentation 2017-05-22 19:58:01 +02:00
Gwendal Roué ffd16f7639 Backport some Makefile improvements from @zmeyc's pr_linux branch 2017-05-22 19:56:57 +02:00
swiftlyfalling 528860161e Add Travis-CI support 2017-05-22 13:24:22 -04:00
swiftlyfalling 1fe6094da5 Remove + ignore .ruby-version to avoid conflicts with Travis-CI
If the .ruby-version file is present and contains a version of Ruby
greater than Travis-CI supports, it will break the Travis-CI builds.
2017-05-22 13:23:07 -04:00
swiftlyfalling 399c51b1ee Merge remote-tracking branch 'groue/master' 2017-05-22 13:18:05 -04:00
Gwendal Roué 55e4abd534 Rename USING_SQLCIPHER to GRDBCIPHER and USING_CUSTOMSQLITE to GRDBCUSTOMSQLITE 2017-05-22 19:15:10 +02:00
Gwendal Roué e9d02f441b More links to RxGRDB 2017-05-22 19:00:24 +02:00
Gwendal Roué f858bcbe5b Rename Request.fetching(_:) to Request.asRequest(of:) 2017-05-22 18:55:51 +02:00
Gwendal Roué cd107711a9 Rename Request.bound(to:) to Request.fetching(_:) 2017-05-22 18:37:46 +02:00
Gwendal Roué ce4c20b112 Replace DatabaseWriter.availableDatabaseConnection with unsafeReentrantWrite() 2017-05-22 18:10:19 +02:00
Gwendal Roué 0b8ba1ccfa Merge branch 'master' of github.com:groue/GRDB.swift 2017-05-22 14:21:29 +02:00
Gwendal Roué c72c97fd53 TODO.md 2017-05-22 13:54:33 +02:00
Gwendal Roué 1e12068e64 DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo) now returns an non-optional boolean. 2017-05-22 13:53:59 +02:00
Gwendal Roué 1799fe1ff9 Consistently crash for all failed conversions from DatabaseValue 2017-05-22 13:51:39 +02:00
Gwendal Roué ae5175c5b4 CHANGELOG.md 2017-05-17 20:01:28 +02:00
Gwendal Roué 86d5b0b23d Update ReleaseProcess.md 2017-05-17 14:41:43 +02:00
Gwendal Roué 341044356f v0.108.0 2017-05-17 14:27:53 +02:00
Gwendal Roué 5eb7a62062 Add @sroddy to the thanks section 2017-05-17 14:25:09 +02:00
Gwendal Roué 74f96c0766 CHANGELOG.md 2017-05-17 14:24:03 +02:00
Gwendal Roué 49b62cb27a Merge pull request #212 from BendingSpoons/feature/CocoaPods-SQLCipher
SQLCipher support with Cocoapods
2017-05-17 14:20:05 +02:00
Gwendal Roué 798588c54b Documentation for GRDBCipher installation via CocoaPods 2017-05-17 14:19:31 +02:00
Gwendal Roué f1a9cdaa8e Restore GRDB.swift.podspec, introduce GRDBCipher.podspec 2017-05-17 13:27:03 +02:00
Stefano Rodriguez c66c0a11b6 Add Cocoapods checks for SQLCipher subspec 2017-05-17 01:29:28 +02:00
Stefano Rodriguez b1cdd1360b Update README.md 2017-05-17 01:17:10 +02:00
Stefano Rodriguez 7c8b48e08a Fix Podspec 2017-05-15 01:08:33 +02:00
Stefano Rodriguez 64df5c6b41 Update README.md 2017-05-13 22:54:56 +02:00
Stefano Rodriguez a5c1361dc9 Add Support for SQLCipher in CocoaPods 2017-05-13 22:49:14 +02:00
Gwendal Roué 798b1a7d2e Tests for DatabaseEventKind.impacts(_ selectionInfo: SelectStatement.SelectionInfo) and triggers. 2017-05-10 13:35:55 +02:00
Gwendal Roué e484e4c6de Tests for DatabaseEventKind.impacts(_ selectionInfo: SelectStatement.SelectionInfo) and foreign keys. 2017-05-10 13:26:57 +02:00
Gwendal Roué 31299a529a TODO.md 2017-05-10 10:27:53 +02:00
Gwendal Roué 53ac681d49 TODO.md 2017-05-09 10:16:18 +02:00
Gwendal Roué 828ef48441 Database.setupErrorLog() rewrite 2017-05-08 13:27:51 +02:00
Gwendal Roué 63e8742fb1 TODO.md 2017-05-05 13:27:46 +02:00
Gwendal Roué 192a958fdc Fix manual installation git checkout command 2017-05-05 13:26:58 +02:00
Gwendal Roué f606e633da Drop RowConvertible.awakeFromFetch 2017-05-05 13:20:37 +02:00
Gwendal Roué e2d2b031a5 Bump Ruby version for jazzy 2017-05-05 10:16:30 +02:00
Gwendal Roué c203a972ff v0.107.0 2017-05-05 08:23:17 +02:00
Gwendal Roué 44df1aa0bd Update GRDBOSXPerformanceTests for Swift 3.1 2017-05-05 08:16:06 +02:00
Gwendal Roué d010587f44 README.md: more direct links to DemoApps/GRDBDemoiOS 2017-05-05 08:05:49 +02:00
Gwendal Roué 840525c11a Improve DemoApps/GRDBDemoiOS/Database.swift 2017-05-05 08:05:28 +02:00
Gwendal Roué a0881d851c Drop attempt to have Carthage build SQLCipher (undo changes for #41) 2017-05-04 22:50:03 +02:00
Gwendal Roué ac00e05a72 CHANGELOG.md 2017-05-04 20:21:45 +02:00
Gwendal Roué 4938568ea7 Refactor statement cache, allow SQLRequest to use cached statements 2017-05-04 20:11:45 +02:00
Gwendal Roué cb4c07a5fb TODO.md 2017-05-04 18:05:49 +02:00
Gwendal Roué 4edd76341e There are two statement caches: one for statements generated by the user, and one for the statements generated by GRDB. Those are separated so that GRDB has no opportunity to inadvertently modify the arguments of user statements. 2017-05-04 18:05:36 +02:00
Gwendal Roué bb8aee8965 TODO.md 2017-05-04 17:17:36 +02:00
Gwendal Roué 5d97d2d680 TODO.md 2017-05-02 10:16:50 +02:00
Gwendal Roué 3eb2646cad More SPM tests 2017-04-23 19:04:28 +02:00
Gwendal Roué 96c3dadb7b Tests/README.md 2017-04-23 18:38:17 +02:00
Gwendal Roué 4d9a238c27 Merge pull request #208 from groue/SPMTests
Support for Swift Package Manager tests
2017-04-23 16:40:53 +02:00
Gwendal Roué a475cfa340 Tests organization 2017-04-23 16:37:59 +02:00
Gwendal Roué e54cec9123 Move tests to Swift Package Manager test target 2017-04-23 15:47:16 +02:00
Gwendal Roué 3edad29501 Documentation: Database.logError is now available through SPM (#207) 2017-04-22 19:27:20 +02:00
Gwendal Roué 392a004bd1 Add @zmeyc to the thanks section 2017-04-22 19:20:53 +02:00
Gwendal Roué 7f8ec17511 Merge pull request #207 from zmeyc/pr_spm_logging
Enable logging when using SPM
2017-04-22 19:17:53 +02:00
Gwendal Roué d9e6fd3b89 Bump CSQLite dependency to 0.2 2017-04-22 19:17:33 +02:00
Andrey Fidrya 6cf59838a6 Enable logging when using SPM 2017-04-22 20:04:09 +03:00
Gwendal Roué 3efa60ce8a Merge pull request #206 from groue/ErrorLoggingCallback
Error logging callback
2017-04-22 18:27:37 +02:00
Gwendal Roué 7a90cd2562 Database.logError documentation 2017-04-22 17:58:19 +02:00
Gwendal Roué 4cdbe4f0f4 Use Database.logError in GRDBDemoiOS 2017-04-22 17:57:56 +02:00
Gwendal Roué 595408b351 Rename logErrorFunction into logError 2017-04-22 17:57:33 +02:00
Gwendal Roué 4ee1fd9f65 Database.logErrorFunction for GRDBCipher and GRDBCustomSQLite 2017-04-22 17:26:16 +02:00
Gwendal Roué f16f4d557a Database.logErrorFunction for CocoaPods 2017-04-22 16:51:22 +02:00
Gwendal Roué 27314d1af3 No Database.logErrorFunction for SPM 2017-04-22 16:35:12 +02:00
Gwendal Roué 4f14fb0ccd Support for SQLITE_CONFIG_LOG via Database.logErrorFunction 2017-04-22 15:11:01 +02:00
Gwendal Roué 9b2a8f847f Remove some useless availability checks in tests 2017-04-22 15:04:47 +02:00
Gwendal Roué dae4ae1c6b Reduce internal coupling 2017-04-22 11:12:43 +02:00
Gwendal Roué c8023adff1 Cleanup 2017-04-20 14:49:08 +02:00
Gwendal Roué c34ac0f17b Cleanup 2017-04-20 14:37:06 +02:00
Gwendal Roué 2222a1bfe2 doc: Fix links to Github in jazzy-generated doc 2017-04-14 15:59:06 +02:00
Gwendal Roué 3134809c22 minor 2017-04-13 13:51:46 +02:00
Gwendal Roué 203e8c41ce Better test_install_SPM 2017-04-12 14:39:53 +02:00
Gwendal Roué 5804c044d5 make test_install_SPM 2017-04-12 14:24:11 +02:00
Gwendal Roué 80c378df21 v0.106.1 2017-04-12 13:16:39 +02:00
Gwendal Roué 0f3bc5922d Documentation about Swift Package Manager 2017-04-12 12:54:23 +02:00
Gwendal Roué 1810edfa6e Sample SPM executable 2017-04-11 13:58:41 +02:00
Gwendal Roué 362b8d3243 0.106.0 2017-04-11 13:50:28 +02:00
Gwendal Roué b06f76512d Merge pull request #202 from zmeyc/pr_spm1
SPM support
2017-04-11 13:37:23 +02:00
Gwendal Roué 6c2b421b57 Add test_framework_SPM target to Makefile 2017-04-11 13:33:36 +02:00
Gwendal Roué 63b3b4225a Rename package to GRDB, and rename SQLite module to CSQLite 2017-04-11 13:22:26 +02:00
Gwendal Roué 5b7ad40163 [whitespace] 2017-04-11 11:05:49 +02:00
Andrey Fidrya 1751fb38e5 SPM support 2017-04-08 21:32:58 +03:00
Gwendal Roué 184a2bcf18 Typo 2017-04-06 14:19:40 +02:00
Gwendal Roué 57fce9d20f Link to http://github.com/RxSwiftCommunity/RxGRDB 2017-04-06 14:18:54 +02:00
Gwendal Roué d354157c0e v0.105.0 2017-04-06 13:07:03 +02:00
Gwendal Roué de78e065cb CHANGELOG.md 2017-04-06 11:40:01 +02:00
Gwendal Roué 17a49b5d8c New public property: DatabaseWriter.availableDatabaseConnection. This new API opens the door to reentrant uses of the database, a much needed tool for RxGRDB. 2017-04-06 11:02:49 +02:00
Gwendal Roué 6c6bbf6294 Fix failing test for SELECT COUNT(*) FROM table observation 2017-04-06 10:35:41 +02:00
Gwendal Roué 72f04367d9 TODO.md 2017-04-05 11:41:19 +02:00
Gwendal Roué 7395305f87 Failing test for SELECT COUNT(*) FROM table observation 2017-04-05 10:45:37 +02:00
Gwendal Roué 1c62a665c7 TODO.md 2017-04-03 14:21:54 +02:00
Gwendal Roué 518919aeee Merge pull request #194 from groue/modulemapRefactor
Xcode 8.3 support
2017-04-03 14:19:39 +02:00
Gwendal Roué da798b3748 v0.104.0 2017-04-03 14:14:00 +02:00
Gwendal Roué 441e936d88 ReleaseProcess.md 2017-04-03 14:12:24 +02:00
Gwendal Roué 23def44101 Stop requiring that Xcode is located at /Applications/Xcode.app. Add a word about Carthage, and leave the door open. 2017-04-03 14:02:39 +02:00
Gwendal Roué 35fafdb476 CHANGELOG.md 2017-04-03 13:47:12 +02:00
Gwendal Roué 0e20e6a0bb Update manual installation instructions for WatchOS 2017-04-03 13:40:38 +02:00
Gwendal Roué 04654a5c85 Functional GRDBDemoWatchOS 2017-04-03 13:37:36 +02:00
Gwendal Roué e17c4e5271 GRDBDemoWatchOS 2017-04-03 13:10:24 +02:00
Gwendal Roué 4d79b35c47 Share GRDBOSXPerformanceTests scheme 2017-04-03 13:10:08 +02:00
Gwendal Roué 26aeb7dcbd New public function: TableMapping.primaryKeyRowComparator. This new API exposes record comparison abilities that were reserved to FetchedRecordsController, and open a better support for GRDB reactive extensions. 2017-04-02 17:27:25 +02:00
Gwendal Roué 7bc3582525 SelectStatement.SelectionInfo.description 2017-04-02 14:18:48 +02:00
Gwendal Roué 1ad00e1102 Custom SQLite 3.18.0 2017-04-01 19:54:38 +02:00
Gwendal Roué 311ad6b940 New public APIs: SelectStatement.selectionInfo, DatabaseEventKind.impacts(_:). Those new APIs expose database observation abilities that were reserved to FetchedRecordsController, and open a better support for GRDB reactive extensions. 2017-04-01 16:01:55 +02:00
Gwendal Roué c65f3289a3 TODO.md 2017-04-01 15:06:48 +02:00
Gwendal Roué cfeaf2f376 TODO.md 2017-04-01 15:04:59 +02:00
Gwendal Roué 8434e856f4 Update documentation about access to the raw SQLite C API since it is now embedded right into the GRDB module. 2017-04-01 14:59:25 +02:00
Gwendal Roué 35a700027c TODO.md 2017-04-01 14:40:14 +02:00
Gwendal Roué 2196158f58 Run GRDBDemoiOS in Release configuration 2017-04-01 14:13:38 +02:00
Gwendal Roué 56d5ca180a Update ReleaseProcess.md 2017-04-01 14:02:07 +02:00
Gwendal Roué 60326b8f65 Update ReleaseProcess.md 2017-04-01 14:01:46 +02:00
Gwendal Roué 363943583d Update ReleaseProcess.md 2017-04-01 14:01:19 +02:00
Gwendal Roué 4348889865 Drop mention of Carthage support from documentation 2017-04-01 14:00:05 +02:00
Gwendal Roué 50e50e82e1 Makefile cleanup and documentation 2017-04-01 13:38:00 +02:00
Gwendal Roué fd30f16364 Stop testing Carthage (see https://github.com/Carthage/Carthage/issues/1867) 2017-04-01 08:49:05 +02:00
Gwendal Roué 21879db549 Bootstrap GRDBCustom / GRDBCipher tests 2017-03-31 18:18:38 +02:00
Gwendal Roué 313b9d64f6 Bootstrap GRDBCustom / GRDBCipher tests 2017-03-31 13:44:37 +02:00
Gwendal Roué 87be97a38d Some tests require submodules 2017-03-31 13:27:56 +02:00
Gwendal Roué 4f5054d792 Share more tested schemes 2017-03-31 13:27:35 +02:00
Gwendal Roué 51545c4db0 Share tested schemes + test GRCBCipheriOS installation (addresses #193) 2017-03-31 13:23:08 +02:00
Gwendal Roué 98fb48eb1d Makefile adaptation for Xcode 8.1 (test up to iOS 10.1) 2017-03-31 09:22:05 +02:00
Gwendal Roué fa2817ab52 GRDBCipher test app 2017-03-31 08:53:37 +02:00
Gwendal Roué 2a35601ff4 make test checks iOS 8.1 2017-03-31 08:32:03 +02:00
Gwendal Roué ed70058a1f ReleaseProcess.md 2017-03-31 08:14:42 +02:00
Gwendal Roué 79a1b65547 ReleaseProcess.md 2017-03-31 08:01:18 +02:00
Gwendal Roué cccddd8455 make test checks manual install, pod lint, and carthage build 2017-03-31 07:54:49 +02:00
Gwendal Roué 9a4d9f7f1f make test 2017-03-31 06:19:34 +02:00
Gwendal Roué c532f40b7d CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE, CLANG_WARN_DOCUMENTATION_COMMENTS = YES 2017-03-31 06:07:29 +02:00
Gwendal Roué d7e68c340c Disable fragile test DatabasePoolBackupTests.testConcurrentWriteDuringBackup 2017-03-31 05:59:40 +02:00
Gwendal Roué 42a985112a Drop watchOS demo app 2017-03-30 22:47:53 +02:00
Gwendal Roué 16a653ed9d Fix product name of test targets (and restore GRDBCipheriOS tests) 2017-03-30 21:59:33 +02:00
Gwendal Roué 91f18323be Merge branch 'master' of github.com:groue/GRDB.swift into modulemapRefactor
Conflicts:
	.gitignore
2017-03-30 20:12:55 +02:00
Gwendal Roué 09bbb50e1f README.md 2017-03-28 08:36:52 +02:00
Gwendal Roué a4eebfeeb2 Documentation: more explicit dbQueue.inDatabase wrapping in key chapters (addresses #189 from @pumplerod) 2017-03-28 08:33:52 +02:00
Gwendal Roué 62d19c9d11 Xcode8.3 WIP 2017-03-28 08:02:08 +02:00
Gwendal Roué 07142b3052 TODO.md 2017-03-27 09:45:58 +02:00
Gwendal Roué a304bc0eed README.md 2017-03-27 09:42:22 +02:00
Gwendal Roué 857b7e53d9 v0.103.0 2017-03-26 18:39:16 +02:00
Gwendal Roué 2987bb129c CocoaPods test application 2017-03-26 18:32:50 +02:00
Gwendal Roué 8da9ad696b Fix signing of GRDBDemoWatchOS 2017-03-26 18:00:33 +02:00
Gwendal Roué 8720d6937a Remove inaccurate documentation for int64EqualDouble(_:_:): Swift standard library does not aim at providing this function. 2017-03-26 17:55:30 +02:00
Gwendal Roué 9262834ffb Fix the test project for Carthage installation of GRDB on iOS 2017-03-26 17:55:24 +02:00
Gwendal Roué a41b1a5a2d Remove the test project for the no longer supported installation of GRDBCipher via Carthage 2017-03-26 17:55:18 +02:00
Gwendal Roué 1e362fdd53 Prefer write { $0... } over write { db in db... } for one liners 2017-03-26 17:55:06 +02:00
Gwendal Roué 8dfe166944 CocoaPods test 2017-03-26 16:32:35 +02:00
Gwendal Roué 8d0feea2c2 Cocoapods support 2017-03-26 16:28:44 +02:00
Gwendal Roué 47d9f5920f Cocoapods support 2017-03-26 16:24:18 +02:00
Gwendal Roué 25eca4146c Cocoapods support 2017-03-26 16:15:24 +02:00
Gwendal Roué 61938601fd SDK-relative sqlite3.h 2017-03-26 16:04:41 +02:00
Gwendal Roué 61d114f297 Remove inaccurate documentation for int64EqualDouble(_:_:): Swift standard library does not aim at providing this function. 2017-03-26 15:38:37 +02:00
Gwendal Roué eddebfbba5 Prefer write { $0... } over write { db in db... } for one liners 2017-03-26 15:38:03 +02:00
Gwendal Roué 323d828eb7 Fix the test project for Carthage installation of GRDB on iOS 2017-03-26 15:37:46 +02:00
Gwendal Roué bb763f7315 Remove the test project for the no longer supported installation of GRDBCipher via Carthage 2017-03-26 15:37:39 +02:00
Gwendal Roué b1d93112da Embed a copy of sqlite3.h in order to work around my inability at importing <sqlite3.h> from all targeted SDKs (addresses #166, #170) 2017-03-26 15:37:31 +02:00
Gwendal Roué 56bd3513a3 Fix FTS3 pattern test so that it compiles when support for FTS5 is available 2017-03-26 15:14:18 +02:00
Gwendal Roué ddcf26058b CHANGELOG.md 2017-03-26 15:10:47 +02:00
Gwendal Roué ba4ee3f1fc Bugfix 2017-03-26 15:09:05 +02:00
Gwendal Roué dedfd5cd33 Document that extended result codes are not always available (#171, #180) 2017-03-26 15:07:04 +02:00
Gwendal Roué b5296f4206 Remove warning from documentation now that availability checks for FTS3Pattern(matchingAnyTokenIn:), FTS3Pattern(matchingAllTokensIn:), FTS3Pattern(matchingPhrase:) have been added 2017-03-26 14:52:22 +02:00
Gwendal Roué e2e2c58d9f Add availability checks for FTS3Pattern(matchingAnyTokenIn:), FTS3Pattern(matchingAllTokensIn:), FTS3Pattern(matchingPhrase:) 2017-03-26 14:51:11 +02:00
Gwendal Roué 7a90b9ce23 Add availability checks for FTS3 unicode61 tokenizer, FTS4 unindexed columns, and partial indexes. 2017-03-26 14:41:15 +02:00
Gwendal Roué ae0928e686 TODO.md 2017-03-26 13:58:26 +02:00
Gwendal Roué b815ad7a8c Apply SQLCipher advice from https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688 2017-03-26 13:53:39 +02:00
Gwendal Roué 06cca9033a TODO.md 2017-03-26 13:33:46 +02:00
Gwendal Roué 5302364139 [format] 2017-03-26 13:33:39 +02:00
Gwendal Roué 78b7fc6169 Workaround PRAGMA table_info bug: check against SQLite version instead of build options 2017-03-26 13:32:01 +02:00
Gwendal Roué b159c30cf1 SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 (iOS 8.2+ and OS X 10.10+) 2017-03-26 13:17:59 +02:00
Gwendal Roué 5c7712bf6c PRAGMA query_only was added in SQLite 3.8.0 (iOS 8.2+ and OS X 10.10+) 2017-03-26 13:17:25 +02:00
Gwendal Roué e64b766599 Expose withoutRowID table creation option for custom SQLite builds and SQLCipher. 2017-03-26 12:48:21 +02:00
Gwendal Roué 89a852286c Reading list 2017-03-26 11:48:13 +02:00
Gwendal Roué 1e312cfbb1 TODO.md 2017-03-25 16:56:11 +01:00
Gwendal Roué 8d4522227c Replace all assertNoError and try! with throwing tests 2017-03-25 16:31:54 +01:00
Gwendal Roué eee39a7c0b Improve unexpected error reporting 2017-03-25 14:15:04 +01:00
Gwendal Roué bd58c18bb0 Simplify cursor step failure steps 2017-03-25 14:14:42 +01:00
Gwendal Roué 685b3a4f21 SQLite 3.17.0 has a big FTS5 bug: don't ship it. 2017-03-25 14:13:36 +01:00
Gwendal Roué 4e82a482d1 DatabaseCursor: test preservation of custom error codes 2017-03-25 14:12:47 +01:00
Gwendal Roué 1214e28563 Remove the "DatabaseReader.read does not prevent a queue from writing." sentence from the documentation: it is no longer true 2017-03-24 20:18:54 +01:00
Gwendal Roué 9170ed6e3a CHANGELOG.md 2017-03-24 20:12:21 +01:00
Gwendal Roué f2bb8bb8af Remove DatabaseValue.value() 2017-03-24 20:05:02 +01:00
Gwendal Roué 24d74698ef TODO.md 2017-03-24 18:39:49 +01:00
Gwendal Roué ba615c15cb Documentation, and remove DatabaseQueue.writeInTransaction 2017-03-24 18:39:14 +01:00
Gwendal Roué 88f206e7f5 New DatabaseReader.read() guarantee: database modifications are prevented 2017-03-24 09:18:24 +01:00
Gwendal Roué 511740ccd7 Warn against slow compilation in the documentation of Persistable.persistentDictionary, and strip down the documentation of the Record class hoping readers will check detailed protocol documentations (addresses #188) 2017-03-23 08:00:46 +01:00
Gwendal Roué 7a2fab1126 Stop relying on CocoaDocs since http://blog.cocoapods.org/CocoaDocs-Documentation-Sunsetting/ 2017-03-19 15:56:38 +01:00
Gwendal Roué fd435f0941 make doc with Jazzy 2017-03-19 15:49:53 +01:00
Gwendal Roué ffd5a8b321 gh-pages consistency 2017-03-19 15:49:39 +01:00
Gwendal Roué 5454e43bc4 Use Int(exactly:) and Int32(exactly:) initializers 2017-03-18 17:00:06 +01:00
Gwendal Roué a94fd2d127 TODO.md 2017-03-18 13:52:45 +01:00
Gwendal Roué 14c53c5e3e Have DatabasePool implementation better expose the write method and its readerPool as its fundamentals. 2017-03-17 09:06:13 +01:00
Gwendal Roué b25648eea1 Have DatabaseQueue implementation better expose inDatabase as its fundamental method. 2017-03-17 09:05:42 +01:00
Gwendal Roué 10d0d162b5 Performance tests against Realm 2.4.3, SQLite.swift 0.11.2 2017-03-09 17:25:35 +01:00
Gwendal Roué e5b2be4346 README.md 2017-03-07 11:14:29 +01:00
Gwendal Roué 4cea442b59 README.md 2017-03-07 11:11:02 +01:00
Gwendal Roué 532f682fc7 Typo 2017-03-07 11:10:14 +01:00
Gwendal Roué c2cd689c32 README.md 2017-03-07 11:09:00 +01:00
Gwendal Roué c3e986eb56 Document that database pools require mastery of database transactions 2017-03-04 18:19:02 +01:00
Gwendal Roué d91f4c244f Documentation 2017-03-04 18:11:25 +01:00
Gwendal Roué 22b768963f Typo 2017-03-04 18:05:54 +01:00
Gwendal Roué 57354cd1ef README.md 2017-03-04 18:00:14 +01:00
Gwendal Roué c74cc40d5c CHANGELOG.md 2017-03-04 07:22:33 +01:00
Gwendal Roué b867a74b6b CHANGELOG.md 2017-03-03 08:15:31 +01:00
Gwendal Roué 7a10486492 DatabaseError conversion to NSError preserves extended result code 2017-03-03 08:14:36 +01:00
Gwendal Roué f36b833654 CHANGELOG.md 2017-03-02 13:47:53 +01:00
Gwendal Roué ef9206088e v0.102.0 2017-03-02 13:39:09 +01:00
Gwendal Roué e141b26411 Remove done TODOs 2017-03-02 13:38:41 +01:00
Gwendal Roué 1f4da13060 Add ReleaseProcess.md to project, for quick access 2017-03-02 13:38:29 +01:00
Gwendal Roué 4ec85e2f25 Merge pull request #181 from groue/RequestFetchCount
Let all requests count, introduce Request.fetchCount()
2017-03-02 13:01:23 +01:00
Gwendal Roué 842831d729 Merge branch 'master' into RequestFetchCount 2017-03-02 13:01:13 +01:00
Gwendal Roué 39a0b5672b Merge pull request #180 from groue/Issue171
Activate extended result codes, and expose result codes as Swift constants
2017-03-02 12:59:27 +01:00
Gwendal Roué 2729892676 Merge branch 'master' into Issue171 2017-03-02 12:58:42 +01:00
Gwendal Roué 50318354a6 Merge branch 'master' into RequestFetchCount 2017-03-02 12:56:57 +01:00
Gwendal Roué 77593c8031 Fix RequestTests.swift so that it tests the Request protocol, not the concrete type that adopts it. 2017-03-02 10:54:27 +01:00
Gwendal Roué 3bfb9adb99 Document how to query external content tables (addresses #178) 2017-03-02 08:42:19 +01:00
Gwendal Roué deebf289de Rename DatabaseMigrator.registerMigrationWithDisabledForeignKeyChecks to registerMigrationWithDeferredForeignKeyCheck 2017-03-02 08:29:45 +01:00
Gwendal Roué d4e777900c #171: less TODO 2017-03-02 08:24:21 +01:00
Gwendal Roué 1b44683cfe #171: cleanup 2017-03-02 08:21:29 +01:00
Gwendal Roué 0ff53f0bd7 #171: CHANGELOG 2017-03-02 08:03:01 +01:00
Gwendal Roué a5cbf08a76 Documentation 2017-03-02 08:01:43 +01:00
Gwendal Roué 023fa8afc9 #171: Missing upgrades to the new ResultCode APIs 2017-03-02 07:57:02 +01:00
Gwendal Roué a721748de1 #171: fix-it for DatabaseError.code 2017-03-02 07:56:48 +01:00
Gwendal Roué ad112285e6 Wording 2017-03-01 14:41:34 +01:00
Gwendal Roué fe05ac9753 #171: Missing upgrades to the new ResultCode APIs 2017-03-01 14:21:14 +01:00
Gwendal Roué b873162a6f #171: Preserve some extended result code that were lost 2017-03-01 14:19:48 +01:00
Gwendal Roué 846604cce5 Merge branch 'master' into Issue171 2017-03-01 14:12:31 +01:00
Gwendal Roué b1ea970f62 #171: ResultCode tests 2017-03-01 13:57:51 +01:00
Gwendal Roué 5bcfb7f488 #171: ~= ResultCode operator 2017-03-01 13:27:19 +01:00
Gwendal Roué 1908f1b4f6 #171: Documentation 2017-03-01 13:03:54 +01:00
Gwendal Roué b0bf8e81aa Better CHANGELOG 2017-03-01 10:10:18 +01:00
Gwendal Roué 4866ba0c84 Typo 2017-03-01 09:14:45 +01:00
Gwendal Roué 8dadf42504 #171: CHANGELOG 2017-03-01 09:13:57 +01:00
Gwendal Roué fc18b15106 #171: Apply @hartbit's suggestion of having two DatabaseError properties: resultCode and extendedResultCode 2017-03-01 09:05:06 +01:00
Gwendal Roué 9b4e55be28 Documentation for Request.fetchCount() (https://github.com/groue/GRDB.swift/issues/176#issuecomment-282783884) 2017-03-01 08:24:43 +01:00
Gwendal Roué 8a4686984a Tests for Request.fetchCount() (https://github.com/groue/GRDB.swift/issues/176#issuecomment-282783884) 2017-03-01 08:06:54 +01:00
Gwendal Roué 42ebffc4fc Keep Request.fetchCount() simple (https://github.com/groue/GRDB.swift/issues/176#issuecomment-282783884) 2017-03-01 07:56:17 +01:00
Gwendal Roué 2d2c596f75 Add Request.fetchCount(). Implements https://github.com/groue/GRDB.swift/issues/176#issuecomment-282783884 2017-03-01 05:32:52 +01:00
Gwendal Roué fa464b489d TODO 2017-02-28 04:35:18 +01:00
Gwendal Roué b531504912 TODOs for #171, #172, #176, #178 2017-02-28 03:19:23 +01:00
Gwendal Roué e4a346995b #171: rename ResultCode.code into ResultCode.resultCode (@hartbit's suggestion) 2017-02-26 17:24:44 +01:00
Gwendal Roué f0d1f2387d #171: always use extended result codes 2017-02-26 15:49:14 +01:00
Gwendal Roué 7eb592df79 #171: introduce ResultCode 2017-02-26 15:36:21 +01:00
Gwendal Roué a704c0ad35 Add @hartbit to the thanks section 2017-02-25 17:07:11 +01:00
Gwendal Roué acf4077878 Merge pull request #174 from hartbit/fix-record-persistenceconflictpolicy
Fix Record's persistenceConflictPolicy
2017-02-25 15:43:56 +01:00
David Hart ba50771007 add tests 2017-02-22 23:02:44 +01:00
David Hart 898db8b7d4 fix Record getting the default implementation of persistenceConflictPolicy 2017-02-22 19:33:22 +01:00
Gwendal Roué d452a00592 Warning against FTS3Pattern initializers before iOS8.2 and macOS 10.10 2017-02-01 14:13:39 +01:00
Gwendal Roué 4ab8fb359b Restore some tests that were avoided because of linker errors (all we needed was to set deployment targets on test targets) 2017-02-01 13:48:34 +01:00
Gwendal Roué 29e6082663 Fix registerMigrationWithDisabledForeignKeyChecks for legacy sqlite 2017-02-01 13:36:20 +01:00
Gwendal Roué 7c6197b1fc TODO: don't use fts3tokenize before SQLite 3.7.17 2017-02-01 13:31:36 +01:00
Gwendal Roué 1e0e40912b GRDBiOS tests on iOS8.1 2017-02-01 13:28:08 +01:00
Gwendal Roué ff84638df8 Documentation 2017-01-31 09:06:45 +01:00
Gwendal Roué 90dee9c171 Documentation 2017-01-30 09:08:27 +01:00
Gwendal Roué 53873c7864 Rewrite the "How do I close a database connection?" FAQ 2017-01-26 06:20:48 +01:00
Gwendal Roué f60a9708b2 Link to the Xcode8.3beta branch 2017-01-25 18:20:34 +01:00
Gwendal Roué 84497bfba7 TODO.md 2017-01-24 08:53:14 +01:00
Gwendal Roué 4dfd672c04 Compound unique keys: preserve index ordering in generated SQL queries 2017-01-22 16:51:02 +01:00
Gwendal Roué d8b64aa2f4 Use sqlite3_close_v2 in GRDBCipher and GRDBCustomSQLite 2017-01-22 16:04:10 +01:00
Gwendal Roué 4968100420 Expose DatabaseMigrator.registerMigrationWithDisabledForeignKeyChecks to GRDBCipher and GRDBCustomSQLite 2017-01-22 14:37:14 +01:00
Gwendal Roué b52687f356 Documentation 2017-01-21 07:51:42 +01:00
Gwendal Roué 71d4565aa5 Typo 2017-01-20 18:12:19 +01:00
Gwendal Roué 42ff295092 v0.101.1 2017-01-20 14:03:26 +01:00
Gwendal Roué f0758e2a6c Darn 2017-01-20 14:02:27 +01:00
Gwendal Roué 33e93ea156 v0.101.0 2017-01-20 13:53:54 +01:00
Gwendal Roué 9f212184fd FetchedRecordsController.allowBackgroundChangesTracking(in:) 2017-01-20 12:16:14 +01:00
Gwendal Roué 1c16d4bd3f Merge branch 'BackgroundFetchedRecordsController' of github.com:groue/GRDB.swift 2017-01-20 12:07:19 +01:00
Gwendal Roué 0008ffc735 TransactionObserver: update documentation about database event filtering 2017-01-20 11:13:57 +01:00
Gwendal Roué e5dce929bb Data Protection documentation 2017-01-20 09:12:22 +01:00
Gwendal Roué 40bcf96c2b Data Protection documentation 2017-01-20 08:54:23 +01:00
Gwendal Roué 519d4470e3 Drop Configuration.fileAttributes 2017-01-20 08:22:46 +01:00
Gwendal Roué cdf18b5480 README 2017-01-19 17:12:00 +01:00
Gwendal Roué dbe4965438 DatabaseEventKind.tableName 2017-01-19 10:12:30 +01:00
Gwendal Roué 899b9b07dd Merge branch 'master' of github.com:groue/GRDB.swift into BackgroundFetchedRecordsController 2017-01-19 10:10:38 +01:00
Gwendal Roué 54d8a03e87 README 2017-01-19 08:56:34 +01:00
Gwendal Roué 052ad87da0 README 2017-01-19 07:56:02 +01:00
Gwendal Roué 2a515b1d8d README 2017-01-19 07:55:20 +01:00
Gwendal Roué dad48df039 TODO 2017-01-18 16:05:49 +01:00
Gwendal Roué ee798df57d Documentation 2017-01-18 15:54:13 +01:00
Gwendal Roué eed21b8f8f Typo 2017-01-18 15:48:24 +01:00
Gwendal Roué 29938f5703 Documentation 2017-01-18 15:47:45 +01:00
Gwendal Roué 52bcf97d73 TODO.md 2017-01-18 15:02:06 +01:00
Gwendal Roué 9934184f5f README 2017-01-18 08:51:48 +01:00
Gwendal Roué fdf33cbf81 Experimental: FetchedRecordsController.allowBackgroundTracking 2017-01-17 15:01:14 +01:00
Gwendal Roué 34458bc86e README 2017-01-17 09:08:52 +01:00
Gwendal Roué 9b061b3aa7 README 2017-01-17 09:06:34 +01:00
Gwendal Roué 2fa6acef1c README 2017-01-17 09:01:48 +01:00
Gwendal Roué 3afb1f145a README 2017-01-17 08:54:01 +01:00
Gwendal Roué b03b75d125 README 2017-01-17 08:53:17 +01:00
Gwendal Roué b9756f0bdc README 2017-01-17 08:39:52 +01:00
Gwendal Roué c3234cb79f README 2017-01-17 08:33:51 +01:00
Gwendal Roué 828ab97837 README 2017-01-17 08:32:26 +01:00
Gwendal Roué ac66510f32 README organization 2017-01-17 08:31:27 +01:00
Gwendal Roué 599397b6f7 Typo 2017-01-17 08:30:42 +01:00
Gwendal Roué e230f5d358 Introduction 2017-01-17 08:29:36 +01:00
Gwendal Roué 91486f1b70 TODO.md 2017-01-12 08:04:01 +01:00
Gwendal Roué 95e6de8654 Time to jump into 2017 2017-01-10 14:19:41 +01:00
Gwendal Roué 784baaec46 v0.100.0 2017-01-10 13:58:27 +01:00
Gwendal Roué 6adaca568f Copyright (C) 2017 Gwendal Roué 2017-01-10 13:53:13 +01:00
Gwendal Roué bcdcceb809 Cleanup 2017-01-10 13:38:51 +01:00
Gwendal Roué de3d075ff2 Updated documentation for #160 2017-01-10 13:33:37 +01:00
Gwendal Roué c5f3aa21b3 FetchedRecordsController documentation 2017-01-10 13:05:17 +01:00
Gwendal Roué 9831b0e3d4 FetchedRecordsController.setRequest() uses TypedRequest 2017-01-10 08:23:09 +01:00
Gwendal Roué 24a8df801f Upgrade SQLite to v3.16.2 2017-01-10 08:16:00 +01:00
Gwendal Roué e0cfd404a1 Update GRDBDemoiOS 2017-01-10 08:03:21 +01:00
Gwendal Roué 0e62c3455b GRDBiOS tests: enable code coverage 2017-01-10 07:59:56 +01:00
Gwendal Roué 9cd5a7926a TODO: upgrade SQLite to v3.16.2 2017-01-06 18:54:00 +01:00
Gwendal Roué 8e4995c8d9 Upgrade SQLite to v3.16.1 2017-01-06 08:51:25 +01:00
Gwendal Roué ca5fc1e8fc Documentation 2017-01-06 08:43:16 +01:00
Gwendal Roué 14dca4667a Simplify FetchedRecordsController callbacks API 2017-01-06 08:40:09 +01:00
Gwendal Roué ebff14adac Cleanup 2017-01-06 08:24:50 +01:00
Gwendal Roué 51f02ed46e Move TableMapping.primaryKeyFunction and primaryKeyRowComparator into TableMapping.swift 2017-01-06 08:19:07 +01:00
Gwendal Roué 03740d0918 Remove FetchedRecordsController compareRecordsByPrimaryKey initializer option 2017-01-06 08:16:57 +01:00
Gwendal Roué c83a16e22e FetchedRecordsController initialisers use TypedRequest 2017-01-06 08:12:14 +01:00
Gwendal Roué e1bf662884 TODO post #160 2017-01-04 06:53:57 +01:00
Gwendal Roué d866bc9044 Row adopts Hashable 2017-01-04 06:52:57 +01:00
Gwendal Roué fd0e4c20ee CHANGELOG.md 2017-01-04 06:47:53 +01:00
Gwendal Roué 55ca0a80b6 Restore test that one can change the set of columns tracked by a fetched records controller 2017-01-04 06:43:17 +01:00
Gwendal Roué eeaf3dc2cf Merge branch 'fetched_records_events_platforms' of https://github.com/reTXT/GRDB.swift 2017-01-04 06:32:18 +01:00
Gwendal Roué 467b948349 Another diff algorithm to look at 2017-01-03 16:40:47 +01:00
Kevin Wooten f368af3d02 Support “TableViewEvent” on all all platforms
* TableViewEvent features of FetchedRecordsController supported on all platforms
* Renamed TableViewEvent to FetchedRecordsChangeEvent
* Renamed TableViewChange to FetchedRecordsChange
2016-12-30 00:30:23 -07:00
Gwendal Roué 0f34ee7d16 Revert "DatabaseError.code is now Database.ResultCode"
This reverts commit 968942f128.
2016-12-29 13:32:29 +01:00
Gwendal Roué 2fe89fc41b Documentation 2016-12-28 13:05:29 +01:00
Gwendal Roué 968942f128 DatabaseError.code is now Database.ResultCode 2016-12-28 11:55:47 +01:00
Gwendal Roué b5fae096a9 Typo 2016-12-23 07:28:48 +01:00
Gwendal Roué 5cad9a1071 Documentation 2016-12-23 07:28:22 +01:00
Gwendal Roué f4a350c3d0 Typo 2016-12-23 07:22:11 +01:00
Gwendal Roué 89885ed4d9 Document the scope of DatabaseWriter DatabaseReader (#159) 2016-12-23 07:18:39 +01:00
Gwendal Roué 612878d3b1 v0.99.2 2016-12-22 08:30:45 +01:00
Gwendal Roué 65d0bb6a90 TODO.md 2016-12-22 08:29:07 +01:00
Gwendal Roué 484b440816 Database.cachedSelectStatement() no longer returns a statement that can not be reused because it has already failed. 2016-12-21 18:59:23 +01:00
Gwendal Roué 92d78515c4 Failing test for cached select statements that have failed 2016-12-21 18:53:55 +01:00
Gwendal Roué 341bedd7ca Failing test for cached select statements that have failed 2016-12-21 18:46:01 +01:00
Gwendal Roué e9f54f1841 TODO.md 2016-12-21 17:52:58 +01:00
Gwendal Roué 4c4af5f1fc TODO.md 2016-12-21 09:11:23 +01:00
Gwendal Roué 2558cd9356 v0.99.1 2016-12-21 06:06:18 +01:00
Gwendal Roué 4670026c92 Fix #157 for virtual tables 2016-12-21 06:06:12 +01:00
Gwendal Roué 302b9c2ac5 Fix #156 and #157 2016-12-21 05:44:19 +01:00
Gwendal Roué 000f1d02c3 Fix #156? 2016-12-20 19:17:12 +01:00
Gwendal Roué 63ce8429f2 TODO.md 2016-12-20 17:45:59 +01:00
Gwendal Roué 61993c4a50 CHANGELOG.md 2016-12-20 06:19:20 +01:00
Gwendal Roué c248efc9fe v0.99.0 2016-12-20 06:17:43 +01:00
Gwendal Roué ec64ca2865 Documentation & Changelog 2016-12-20 06:15:03 +01:00
Gwendal Roué d4fe7467b6 truncate optimization TODO 2016-12-20 06:14:41 +01:00
Gwendal Roué e8a229103a Fix #156 2016-12-20 06:01:28 +01:00
Gwendal Roué e6cdab37b0 TODO.md 2016-12-19 10:12:56 +01:00
Gwendal Roué 26c88ffaec TODO.md 2016-12-18 14:48:20 +01:00
Gwendal Roué abf1c144c5 TODO.md 2016-12-16 19:58:13 +01:00
Gwendal Roué c4e04d6e07 Tests for FetchedRecordsController error handling 2016-12-16 19:46:46 +01:00
Gwendal Roué ed4826a67f FetchedRecordsController error handling 2016-12-16 19:46:12 +01:00
Gwendal Roué dee2df9e45 TODO.md 2016-12-16 18:45:40 +01:00
Gwendal Roué acabd11d40 CHANGELOG.md 2016-12-16 14:21:47 +01:00
Gwendal Roué 8adea6ba1e TODO.md 2016-12-16 14:20:50 +01:00
Gwendal Roué c36be55c2f FetchedRecordsController error handling WIP 2016-12-16 09:09:50 +01:00
Gwendal Roué 5355555568 Typo 2016-12-16 07:42:34 +01:00
431 changed files with 44509 additions and 37784 deletions

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
source 'https://rubygems.org'
gem 'xcpretty'
gem 'xcpretty-travis-formatter'
+12
View File
@@ -99,3 +99,15 @@ xcuserdata
# GRDBCustomSQLite USER configuration files
SQLiteCustom/GRDBCustomSQLite-USER.h
SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
# CocoaPods test
Podfile.lock
Pods
# SPM
.build
Package.resolved
Tests/SPM/Packages
# Ruby
.ruby-version
+1 -1
View File
@@ -1 +1 @@
3.0
4.0
+151
View File
@@ -0,0 +1,151 @@
language: objective-c
xcode_project: GRDB.xcodeproj
# Disable the default Travis-CI submodule logic
# The various make commands ensure that the appropriate submodules are retrieved
git:
submodules: false
jobs:
include:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 9)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBOSX (Xcode 9, macOS 10.12)
script: make test_framework_GRDBOSX
# Test GRDBWatchOS (Xcode 9)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBWatchOS (Xcode 9, watchOS)
script: make test_framework_GRDBWatchOS
# Test GRDBiOS (Xcode 9, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBiOS (Xcode 9, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
# Test GRDBiOS (Xcode 9, iOS <MINIMUM VERSION>))
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBiOS (Xcode 9, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 9, macOS 10.12)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDB [SPM] (Xcode 9, macOS 10.12)
script: make test_SPM
###########################################
## Test GRDB (Custom SQLite)
# Test GRDBCustomSQLiteOSX (Xcode 9)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteOSX (Xcode 9, macOS 10.12)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MINIMUM VERSION>))
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test GRDB (SQLCipher)
# Test GRDBCipherOSX (Xcode 9)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCipherOSX (Xcode 9, macOS 10.12)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 9, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCipheriOS (Xcode 9, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9, iOS <MINIMUM VERSION>))
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=GRDBCipheriOS (Xcode 9, iOS <MIN>)
script: make test_framework_GRDBCipheriOS_minTarget
###########################################
## Test Installation Methods
# Manual Install
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=Manual Install
script: make test_install_manual
# Manual Install (GRDBCipher)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9
env:
- TID=Manual Install (GRDBCipher)
script: make test_install_GRDBCipher
# Cocoapods Lint
- stage: Test Installation
osx_image: xcode9
install:
- gem install cocoapods # Since Travis is not always on latest version
env:
- TID=Cocoapods
script: make test_CocoaPodsLint
# SPM Install
- stage: Test Installation
osx_image: xcode9
env:
- TID=SPM
script: make test_install_SPM
## The following doesn’t work, as `make test_CarthageBuild` does not yet work.
## Carthage Build
#- stage: Carthage
# osx_image: xcode9
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
# script: make test_CarthageBuild
+983 -12
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,18 @@
{
"images" : [
{
"idiom" : "watch",
"screenWidth" : "{130,145}",
"scale" : "2x"
},
{
"idiom" : "watch",
"screenWidth" : "{146,165}",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,28 @@
{
"assets" : [
{
"idiom" : "watch",
"filename" : "Circular.imageset",
"role" : "circular"
},
{
"idiom" : "watch",
"filename" : "Extra Large.imageset",
"role" : "extra-large"
},
{
"idiom" : "watch",
"filename" : "Modular.imageset",
"role" : "modular"
},
{
"idiom" : "watch",
"filename" : "Utilitarian.imageset",
"role" : "utilitarian"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,18 @@
{
"images" : [
{
"idiom" : "watch",
"screenWidth" : "{130,145}",
"scale" : "2x"
},
{
"idiom" : "watch",
"screenWidth" : "{146,165}",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,18 @@
{
"images" : [
{
"idiom" : "watch",
"screenWidth" : "{130,145}",
"scale" : "2x"
},
{
"idiom" : "watch",
"screenWidth" : "{146,165}",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,18 @@
{
"images" : [
{
"idiom" : "watch",
"screenWidth" : "{130,145}",
"scale" : "2x"
},
{
"idiom" : "watch",
"screenWidth" : "{146,165}",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -1 +0,0 @@
Did you know that git does not support storing empty directories?
@@ -1,39 +0,0 @@
import GRDB
import WatchKit
// The shared database queue
var dbQueue: DatabaseQueue!
func setupDatabase() {
// Connect to the database
// See https://github.com/groue/GRDB.swift/#database-connections
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
dbQueue = try! DatabaseQueue(path: databasePath)
// Use DatabaseMigrator to setup the database
// See https://github.com/groue/GRDB.swift/#migrations
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
// Compare person names in a localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/#unicode
try db.create(table: "persons") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
}
}
migrator.registerMigration("addPersons") { db in
// Populate the persons table with random data
for _ in 0..<8 {
try Person(name: Person.randomName()).insert(db)
}
}
try! migrator.migrate(dbQueue)
}
@@ -3,6 +3,40 @@ import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
setupDatabase()
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillResignActive() {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
backgroundTask.setTaskCompleted()
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// Be sure to complete the connectivity task once you’re done.
connectivityTask.setTaskCompleted()
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
urlSessionTask.setTaskCompleted()
default:
// make sure to complete unhandled task types
task.setTaskCompleted()
}
}
}
}
@@ -18,8 +18,6 @@
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSExtension</key>
@@ -27,7 +25,7 @@
<key>NSExtensionAttributes</key>
<dict>
<key>WKAppBundleIdentifier</key>
<string>GRDB.GRDBDemoiOS.watchkitapp</string>
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.watchkit</string>
@@ -1,25 +1,16 @@
import WatchKit
import Foundation
import GRDB
import SQLite3
class InterfaceController: WKInterfaceController {
@IBOutlet var table: WKInterfaceTable!
@IBOutlet var versionLabel: WKInterfaceLabel!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
let persons = try! dbQueue.inDatabase { db in
try Person.order(Column("name")).fetchAll(db)
}
table.setNumberOfRows(persons.count, withRowType: "Person")
for (i, person) in persons.enumerated() {
let row = table.rowController(at: i) as! PersonRowController
row.nameLabel.setText(person.name)
}
let sqliteVersion = String(cString: sqlite3_libversion(), encoding: .utf8)
versionLabel.setText(sqliteVersion)
}
}
class PersonRowController: NSObject {
@IBOutlet var nameLabel: WKInterfaceLabel!
}
@@ -1,8 +1,12 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder.WatchKit.Storyboard" version="3.0" toolsVersion="10117" systemVersion="15G31" targetRuntime="watchKit" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="AgC-eL-Hgc">
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder.WatchKit.Storyboard" version="3.0" toolsVersion="12118" systemVersion="16E195" targetRuntime="watchKit" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="AgC-eL-Hgc">
<device id="watch38" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBWatchKitPlugin" version="10032"/>
<deployment identifier="watchOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12086"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBWatchKitPlugin" version="12029"/>
</dependencies>
<scenes>
<!--Interface Controller-->
@@ -10,23 +14,15 @@
<objects>
<controller id="AgC-eL-Hgc" customClass="InterfaceController" customModule="GRDBDemoWatchOS" customModuleProvider="target">
<items>
<table alignment="left" id="as6-ga-ksx">
<group width="1" alignment="left" verticalAlignment="center" layout="vertical" id="tkk-aG-QQF">
<items>
<tableRow identifier="Person" selectable="NO" id="0Rj-aC-A4i" customClass="PersonRowController" customModule="GRDBDemoWatchOS_Extension">
<group key="rootItem" width="1" alignment="left" id="Ohb-zN-5mC">
<items>
<label alignment="left" verticalAlignment="center" text="Label" id="jSM-Ni-30q"/>
</items>
</group>
<connections>
<outlet property="nameLabel" destination="jSM-Ni-30q" id="qRo-7r-tXk"/>
</connections>
</tableRow>
<label alignment="center" text="SQLite version" id="dGA-xX-x8V"/>
<label alignment="center" text="Label" id="whi-N6-h8U"/>
</items>
</table>
</group>
</items>
<connections>
<outlet property="table" destination="as6-ga-ksx" id="Zqf-oi-mIm"/>
<outlet property="versionLabel" destination="whi-N6-h8U" id="5xN-Gj-yNt"/>
</connections>
</controller>
</objects>
@@ -18,8 +18,6 @@
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>UISupportedInterfaceOrientations</key>
@@ -28,7 +26,7 @@
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>WKCompanionAppBundleIdentifier</key>
<string>GRDB.GRDBDemoiOS</string>
<string>com.github.groue.GRDBDemoiOS</string>
<key>WKWatchKitApp</key>
<true/>
</dict>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,141 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
BuildableName = "GRDBDemoiOS.app"
BlueprintName = "GRDBDemoiOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FCA1E926430002582E0"
BuildableName = "GRDBDemoWatchOS Extension.appex"
BlueprintName = "GRDBDemoWatchOS Extension"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</RemoteRunnable>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</RemoteRunnable>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
BuildableName = "GRDBDemoiOS.app"
BlueprintName = "GRDBDemoiOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
BuildableName = "GRDBDemoiOS.app"
BlueprintName = "GRDBDemoiOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
BuildableName = "GRDBDemoiOS.app"
BlueprintName = "GRDBDemoiOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
BuildableName = "GRDBDemoiOS.app"
BlueprintName = "GRDBDemoiOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -1,5 +1,15 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
@@ -32,6 +42,16 @@
"filename" : "Icon-60@3x.png",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
@@ -40,14 +40,17 @@ func setupDatabase(_ application: UIApplication) throws {
t.column("score", .integer).notNull()
}
}
migrator.registerMigration("addPersons") { db in
// Populate the persons table with random data
for _ in 0..<8 {
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
}
}
// // Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
try migrator.migrate(dbQueue)
}
@@ -18,8 +18,6 @@
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
@@ -18,17 +18,16 @@ class Person: Record {
}
required init(row: Row) {
id = row.value(named: "id")
name = row.value(named: "name")
score = row.value(named: "score")
id = row["id"]
name = row["name"]
score = row["score"]
super.init(row: row)
}
override var persistentDictionary: [String : DatabaseValueConvertible?] {
return [
"id": id,
"name": name,
"score": score]
override func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["name"] = name
container["score"] = score
}
override func didInsert(with rowID: Int64, for column: String?) {
@@ -12,14 +12,13 @@ class PersonsViewController: UITableViewController {
editButtonItem
]
let request = personsSortedByScore
personsController = try! FetchedRecordsController(dbQueue, request: request, compareRecordsByPrimaryKey: true)
personsController = try! FetchedRecordsController(dbQueue, request: personsSortedByScore)
personsController.trackChanges(
recordsWillChange: { [unowned self] _ in
willChange: { [unowned self] _ in
self.tableView.beginUpdates()
},
tableViewEvent: { [unowned self] (controller, record, event) in
switch event {
onChange: { [unowned self] (controller, record, change) in
switch change {
case .insertion(let indexPath):
self.tableView.insertRows(at: [indexPath], with: .fade)
@@ -44,7 +43,7 @@ class PersonsViewController: UITableViewController {
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
}
},
recordsDidChange: { [unowned self] _ in
didChange: { [unowned self] _ in
self.tableView.endUpdates()
})
try! personsController.performFetch()
+4 -4
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.15.2](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.20.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).
@@ -11,11 +11,11 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
**To install GRDB with a custom SQLite build:**
1. Clone the GRDB.swift git repository, checkout the latest tagged version, and download SQLite sources:
1. Clone the GRDB git repository, checkout the latest tagged version, and download SQLite sources:
```sh
cd [GRDB.swift directory]
git checkout v0.98.0
cd [GRDB directory]
git checkout v2.0
git submodule update --init SQLiteCustom/src
````
+21 -31
View File
@@ -12,8 +12,8 @@ This guide is a step-by-step tour of GRDB extensibility, around a few topics:
```swift
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
while let row = try rows.next() {
let name: String = row.value(named: "name")
let color: UIColor = row.value(named: "color") // <-- New! UIColor as value
let name: String = row["name"]
let color: UIColor = row["color"] // <-- New! UIColor as value
}
```
@@ -93,8 +93,8 @@ Well, you will be able to use UIColor like all other [value types](../../../#val
```swift
let rows = try Row.fetchCursor(db, "SELECT * FROM clothes")
while let row = try rows.next() {
let name: String = row.value(named: "name")
let color: UIColor = row.value(named: "color")
let name: String = row["name"]
let color: UIColor = row["color"]
}
```
@@ -112,13 +112,14 @@ Well, you will be able to use UIColor like all other [value types](../../../#val
var color: UIColor
required init(row: Row) {
name = row.value(named: "name")
color = row.value(named: "color")
name = row["name"]
color = row["color"]
super.init(row: row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["name": name, "color": color]
override func encode(to container: inout PersistenceContainer) {
container["name"] = name
container["color"] = color
}
}
```
@@ -208,6 +209,8 @@ Whenever you import a SQL feature to Swift, you'll have to decide: should you pr
### 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
@@ -273,6 +276,8 @@ You may want to compare it to another protocol, SQLExpressible, which will be de
### 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
@@ -390,6 +395,8 @@ For an example of use, see the [Add a new kind of SQLite expression](#add-a-new-
#### 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
@@ -415,6 +422,8 @@ extension SQLUnaryOperator {
#### 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
@@ -439,6 +448,8 @@ extension SQLBinaryOperator {
#### SQLExpressionFunction
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
SQLExpressionFunction builds an SQL function call:
```swift
@@ -473,15 +484,6 @@ Build a `value IN (...)` expression from any sequence of [values](../../../#valu
![1,2,3].contains(Column("id"))
```
The most general way to generate an `IN` operator is from any value that adopts the [SQLCollection](http://cocoadocs.org/docsets/GRDB.swift/0.98.0/Protocols/SQLCollection.html) protocol, like the [query interface requests](../../../#requests):
```swift
let request = Person.select(Column("id"))
// SQLExpression: in IN (SELECT id FROM persons)
request.contains(Column("id"))
```
#### The BETWEEN Operator
@@ -493,21 +495,9 @@ Build a `value BETWEEN min AND max` expression from Swift ranges:
```
#### The EXISTS Operator
Build a `EXISTS(...)` expression from any value that adopts the [SQLSelectQuery](http://cocoadocs.org/docsets/GRDB.swift/0.98.0/Protocols/SQLSelectQuery.html) protocol, like the [query interface requests](../../../#requests):
```swift
let request = Person.all()
// SQLExpression: EXISTS(SELECT * FROM persons)
request.exists()
```
#### The COUNT Function
Build a `COUNT(...)` expression from the [count](http://cocoadocs.org/docsets/GRDB.swift/0.98.0/Functions.html) and [count(distinct:)](http://cocoadocs.org/docsets/GRDB.swift/0.98.0/Functions.html) functions:
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.0/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.0/Functions.html) functions:
```swift
// SQLExpression: COUNT(email)
@@ -598,4 +588,4 @@ You may want to compare it to another protocol, SQLSpecificExpressible, which ha
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://cocoadocs.org/docsets/GRDB.swift/0.98.0/Protocols/SQLExpression.html) protocol.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/SQLExpression.html) protocol.
+9 -11
View File
@@ -6,29 +6,27 @@ Release Process
To release a new GRDB version:
- Tests
- Run GRDBOX tests
- Run GRDBCipherOSX tests
- Run GRDBCustomSQLiteOSX tests
- Run GRDBiOS tests
- Run GRDBCipheriOS tests
- Run GRDBCustomSQLiteiOS tests
- Build and run GRDBDemoiOS
- Build and run GRDBDemoWatchOS
- `make test`
- Build and run GRDBDemoiOS in Release configuration on a device
- Archive GRDBDemoiOS
- Check for performance regression with GRDBOSXPerformanceTests
- `rm -rf Carthage; carthage build --no-skip-current`
- `pod lib lint --allow-warnings`
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in README.md and Documentation/CustomSQLiteBuilds.md
- Update GRDB version number and release date in:
- Makefile
- CHANGELOG.md
- Documentation/CustomSQLiteBuilds.md
- Documentation/ExtendingGRDB.md
- GRDB.swift.podspec
- GRDBCipher.podspec
- README.md
- Support/Info.plist
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master branch
- Push to the Swift3 branch
- `pod trunk push --allow-warnings`
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- `pod trunk push --allow-warnings GRDBCipher.podspec`
- `make doc`, and update index.html in the `gh-pages` branch
- Update http://github.com/groue/GRDBDemo
- Update http://github.com/groue/WWDCCompanion
+2 -2
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '0.98.0'
s.version = '2.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
@@ -13,7 +13,7 @@ Pod::Spec.new do |s|
s.osx.deployment_target = '10.9'
s.watchos.deployment_target = '2.0'
s.source_files = 'GRDB/**/*.{h,swift}'
s.source_files = 'GRDB/**/*.swift', 'Support/*.h'
s.module_map = 'Support/module.modulemap'
s.framework = 'Foundation'
s.library = 'sqlite3'
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "560FC5191CB003810014AA8E"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipherOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "560FC55D1CB00B880014AA8E"
BuildableName = "GRDBCipherOSXTests.xctest"
BlueprintName = "GRDBCipherOSXTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "567156191CB16729007DC145"
BuildableName = "GRDBCipherOSXEncryptedTests.xctest"
BlueprintName = "GRDBCipherOSXEncryptedTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "560FC5191CB003810014AA8E"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipherOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "560FC5191CB003810014AA8E"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipherOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "560FC5191CB003810014AA8E"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipherOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipheriOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56AFCA2B1CB1AA9900F48B96"
BuildableName = "GRDBCipheriOSTests.xctest"
BlueprintName = "GRDBCipheriOSTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56AFCA841CB1ABC800F48B96"
BuildableName = "GRDBCipheriOSEncryptedTests.xctest"
BlueprintName = "GRDBCipheriOSEncryptedTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipheriOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipheriOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
BuildableName = "GRDBCipher.framework"
BlueprintName = "GRDBCipheriOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA809A1CFB2F6F003DC1BA"
BuildableName = "GRDBCustomSQLiteOSXTests.xctest"
BlueprintName = "GRDBCustomSQLiteOSXTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteOSX"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA80401CFB2AD7003DC1BA"
BuildableName = "GRDBCustomSQLiteiOSTests.xctest"
BlueprintName = "GRDBCustomSQLiteiOSTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
BuildableName = "GRDBCustomSQLite.framework"
BlueprintName = "GRDBCustomSQLiteiOS"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0810"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -29,7 +29,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
BuildableName = "GRDBTests.xctest"
BuildableName = "GRDBOSXTests.xctest"
BlueprintName = "GRDBOSXTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
@@ -48,7 +48,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
BuildableName = "GRDBTests.xctest"
BuildableName = "GRDBOSXTests.xctest"
BlueprintName = "GRDBOSXTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
</BuildAction>
<TestAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56439B2D1F4CA1DC0066043F"
BuildableName = "GRDBOSXPerformanceComparisonTests.xctest"
BlueprintName = "GRDBOSXPerformanceComparisonTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
</BuildAction>
<TestAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "560C97CF1C0E22D300BF8471"
BuildableName = "GRDBOSXPerformanceTests.xctest"
BlueprintName = "GRDBOSXPerformanceTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0810"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0810"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,14 +26,15 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56E5D7D21B4D3FEE00430942"
BuildableName = "GRDBTests.xctest"
BuildableName = "GRDBiOSTests.xctest"
BlueprintName = "GRDBiOSTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
+1 -1
View File
@@ -24,7 +24,7 @@
location = "group:GRDB.xcodeproj">
</FileRef>
<FileRef
location = "group:Tests/GRDBProfiling/GRDBProfiling.xcodeproj">
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
</FileRef>
<FileRef
location = "group:DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj">
+8 -37
View File
@@ -1,21 +1,8 @@
import Foundation
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Configuration for a DatabaseQueue or DatabasePool.
@@ -49,29 +36,12 @@ public struct Configuration {
#endif
// MARK: - File Attributes
/// The file attributes that should be applied to the database files (see
/// `NSFileMnager.setAttributes(_,ofItemAtPath:)`).
///
/// SQLite will create [temporary files](https://www.sqlite.org/tempfiles.html)
/// when it needs them.
///
/// In WAL mode (see DatabasePool), SQLite will also eventually create
/// `-shm` and `-wal` files.
///
/// GRDB will apply file attributes to all those files.
///
/// Default: nil
public var fileAttributes: [FileAttributeKey: Any]? = nil
// MARK: - Transactions
/// The default kind of transaction.
///
/// Default: Immediate
public var defaultTransactionKind: Database.TransactionKind = .immediate
/// Default: deferred
public var defaultTransactionKind: Database.TransactionKind = .deferred
// MARK: - Concurrency
@@ -101,7 +71,8 @@ public struct Configuration {
var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())?
var SQLiteConnectionDidClose: (() -> ())?
var SQLiteOpenFlags: Int32 {
return threadingMode.SQLiteOpenFlags | (readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE))
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
return threadingMode.SQLiteOpenFlags | readWriteFlags
}
}
+23 -11
View File
@@ -3,8 +3,7 @@ extension Array {
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let strings = try Array(cursor) // ["foo", "bar"]
public init<C : Cursor>(_ cursor: C) throws where C.Element == Element {
// TODO: cursors should have an underestimatedCount
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
while let element = try cursor.next() {
append(element)
@@ -12,6 +11,19 @@ extension Array {
}
}
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'")
/// let strings = try Set(cursor) // ["foo"]
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
while let element = try cursor.next() {
insert(element)
}
}
}
/// A type that supplies the values of some external resource, one at a time.
///
/// ## Overview
@@ -64,7 +76,7 @@ public protocol Cursor : class {
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 {
public init<C: Cursor>(_ base: C) where C.Element == Element {
element = base.next
}
@@ -138,13 +150,13 @@ extension Cursor {
/// 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>>> {
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> {
return flatMap { try IteratorCursor(transform($0)) }
}
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult : Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
return map(transform).joined()
}
@@ -211,7 +223,7 @@ extension Cursor where Element: Sequence {
/// }
/// // Prints: "0: foo"
/// // Prints: "1: bar"
public final class EnumeratedCursor<Base : Cursor> : Cursor {
public final class EnumeratedCursor<Base: Cursor> : Cursor {
init(_ base: Base) {
self.index = 0
self.base = base
@@ -231,7 +243,7 @@ public final class EnumeratedCursor<Base : Cursor> : Cursor {
/// A cursor whose elements consist of the elements of some base cursor that
/// also satisfy a given predicate.
public final class FilterCursor<Base : Cursor> : Cursor {
public final class FilterCursor<Base: Cursor> : Cursor {
init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) {
self.base = base
self.isIncluded = isIncluded
@@ -283,7 +295,7 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
/// transform function returning Element.
///
/// See Cursor.map(_:)
public final class MapCursor<Base : Cursor, Element> : Cursor {
public final class MapCursor<Base: Cursor, Element> : Cursor {
init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) {
self.base = base
self.transform = transform
@@ -301,7 +313,7 @@ public final class MapCursor<Base : Cursor, Element> : Cursor {
}
/// A Cursor whose elements are those of a sequence iterator.
public final class IteratorCursor<Base : IteratorProtocol> : Cursor {
public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
/// Creates a cursor from a sequence iterator.
public init(_ base: Base) {
@@ -309,7 +321,7 @@ public final class IteratorCursor<Base : IteratorProtocol> : Cursor {
}
/// Creates a cursor from a sequence.
public init<S : Sequence>(_ s: S) where S.Iterator == Base {
public init<S: Sequence>(_ s: S) where S.Iterator == Base {
self.base = s.makeIterator()
}
@@ -326,7 +338,7 @@ 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>> {
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Self.Iterator>, SegmentOfResult>> {
return IteratorCursor(self).flatMap(transform)
}
}
+794 -428
View File
File diff suppressed because it is too large. Load diff
+198 -23
View File
@@ -1,28 +1,195 @@
import Foundation
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
/// A result code limited to the least significant 8 bits of the receiver.
/// See https://www.sqlite.org/rescode.html for more information.
///
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
public var primaryResultCode: ResultCode {
return ResultCode(rawValue: rawValue & 0xFF)
}
var isPrimary: Bool {
return self == primaryResultCode
}
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)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
} else {
return "\(rawValue)"
}
#endif
}
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/// Returns true if the code on the left matches the code on the right.
///
/// Primary result codes match themselves and their extended result codes,
/// while extended result codes match only themselves:
///
/// switch error.extendedResultCode {
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
/// case .SQLITE_CONSTRAINT: // any other constraint error
/// default: // any other database error
/// }
public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool {
if pattern.isPrimary {
return pattern == code.primaryResultCode
} else {
return pattern == code
}
}
// Primary Result codes
// https://www.sqlite.org/rescode.html#primary_result_code_list
public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result
public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database
public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite
public static let SQLITE_PERM = ResultCode(rawValue: 3) // Access permission denied
public static let SQLITE_ABORT = ResultCode(rawValue: 4) // Callback routine requested an abort
public static let SQLITE_BUSY = ResultCode(rawValue: 5) // The database file is locked
public static let SQLITE_LOCKED = ResultCode(rawValue: 6) // A table in the database is locked
public static let SQLITE_NOMEM = ResultCode(rawValue: 7) // A malloc() failed
public static let SQLITE_READONLY = ResultCode(rawValue: 8) // Attempt to write a readonly database
public static let SQLITE_INTERRUPT = ResultCode(rawValue: 9) // Operation terminated by sqlite3_interrupt()
public static let SQLITE_IOERR = ResultCode(rawValue: 10) // Some kind of disk I/O error occurred
public static let SQLITE_CORRUPT = ResultCode(rawValue: 11) // The database disk image is malformed
public static let SQLITE_NOTFOUND = ResultCode(rawValue: 12) // Unknown opcode in sqlite3_file_control()
public static let SQLITE_FULL = ResultCode(rawValue: 13) // Insertion failed because database is full
public static let SQLITE_CANTOPEN = ResultCode(rawValue: 14) // Unable to open the database file
public static let SQLITE_PROTOCOL = ResultCode(rawValue: 15) // Database lock protocol error
public static let SQLITE_EMPTY = ResultCode(rawValue: 16) // Database is empty
public static let SQLITE_SCHEMA = ResultCode(rawValue: 17) // The database schema changed
public static let SQLITE_TOOBIG = ResultCode(rawValue: 18) // String or BLOB exceeds size limit
public static let SQLITE_CONSTRAINT = ResultCode(rawValue: 19) // Abort due to constraint violation
public static let SQLITE_MISMATCH = ResultCode(rawValue: 20) // Data type mismatch
public static let SQLITE_MISUSE = ResultCode(rawValue: 21) // Library used incorrectly
public static let SQLITE_NOLFS = ResultCode(rawValue: 22) // Uses OS features not supported on host
public static let SQLITE_AUTH = ResultCode(rawValue: 23) // Authorization denied
public static let SQLITE_FORMAT = ResultCode(rawValue: 24) // Auxiliary database format error
public static let SQLITE_RANGE = ResultCode(rawValue: 25) // 2nd parameter to sqlite3_bind out of range
public static let SQLITE_NOTADB = ResultCode(rawValue: 26) // File opened that is not a database file
public static let SQLITE_NOTICE = ResultCode(rawValue: 27) // Notifications from sqlite3_log()
public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log()
public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready
public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing
// Extended Result Code
// https://www.sqlite.org/rescode.html#extended_result_code_list
public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8)))
public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8)))
public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8)))
public static let SQLITE_IOERR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (4<<8)))
public static let SQLITE_IOERR_DIR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (5<<8)))
public static let SQLITE_IOERR_TRUNCATE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (6<<8)))
public static let SQLITE_IOERR_FSTAT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (7<<8)))
public static let SQLITE_IOERR_UNLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (8<<8)))
public static let SQLITE_IOERR_RDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (9<<8)))
public static let SQLITE_IOERR_DELETE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (10<<8)))
public static let SQLITE_IOERR_BLOCKED = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (11<<8)))
public static let SQLITE_IOERR_NOMEM = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (12<<8)))
public static let SQLITE_IOERR_ACCESS = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (13<<8)))
public static let SQLITE_IOERR_CHECKRESERVEDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (14<<8)))
public static let SQLITE_IOERR_LOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (15<<8)))
public static let SQLITE_IOERR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (16<<8)))
public static let SQLITE_IOERR_DIR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (17<<8)))
public static let SQLITE_IOERR_SHMOPEN = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (18<<8)))
public static let SQLITE_IOERR_SHMSIZE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (19<<8)))
public static let SQLITE_IOERR_SHMLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (20<<8)))
public static let SQLITE_IOERR_SHMMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (21<<8)))
public static let SQLITE_IOERR_SEEK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (22<<8)))
public static let SQLITE_IOERR_DELETE_NOENT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (23<<8)))
public static let SQLITE_IOERR_MMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (24<<8)))
public static let SQLITE_IOERR_GETTEMPPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (25<<8)))
public static let SQLITE_IOERR_CONVPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (26<<8)))
public static let SQLITE_IOERR_VNODE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (27<<8)))
public static let SQLITE_IOERR_AUTH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (28<<8)))
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (1<<8)))
public static let SQLITE_BUSY_RECOVERY = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (1<<8)))
public static let SQLITE_BUSY_SNAPSHOT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (2<<8)))
public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (1<<8)))
public static let SQLITE_CANTOPEN_ISDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (2<<8)))
public static let SQLITE_CANTOPEN_FULLPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (3<<8)))
public static let SQLITE_CANTOPEN_CONVPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (4<<8)))
public static let SQLITE_CORRUPT_VTAB = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (1<<8)))
public static let SQLITE_READONLY_RECOVERY = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (1<<8)))
public static let SQLITE_READONLY_CANTLOCK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (2<<8)))
public static let SQLITE_READONLY_ROLLBACK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (3<<8)))
public static let SQLITE_READONLY_DBMOVED = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (4<<8)))
public static let SQLITE_ABORT_ROLLBACK = ResultCode(rawValue: (SQLITE_ABORT.rawValue | (2<<8)))
public static let SQLITE_CONSTRAINT_CHECK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (1<<8)))
public static let SQLITE_CONSTRAINT_COMMITHOOK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (2<<8)))
public static let SQLITE_CONSTRAINT_FOREIGNKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (3<<8)))
public static let SQLITE_CONSTRAINT_FUNCTION = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (4<<8)))
public static let SQLITE_CONSTRAINT_NOTNULL = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (5<<8)))
public static let SQLITE_CONSTRAINT_PRIMARYKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (6<<8)))
public static let SQLITE_CONSTRAINT_TRIGGER = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (7<<8)))
public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (8<<8)))
public static let SQLITE_CONSTRAINT_VTAB = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (9<<8)))
public static let SQLITE_CONSTRAINT_ROWID = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (10<<8)))
public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (1<<8)))
public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (2<<8)))
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
}
/// DatabaseError wraps an SQLite error.
public struct DatabaseError : Error {
/// The SQLite error code (see https://www.sqlite.org/c3ref/c_abort.html).
public let code: Int32
/// The SQLite error code (see
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
///
/// do {
/// ...
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
/// // A constraint error
/// }
///
/// This property returns a "primary result code", that is to say the least
/// significant 8 bits of any SQLite result code. See
/// https://www.sqlite.org/rescode.html for more information.
///
/// See also `extendedResultCode`.
public var resultCode: ResultCode {
return extendedResultCode.primaryResultCode
}
/// The SQLite extended error code (see
/// https://www.sqlite.org/rescode.html#extended_result_code_list).
///
/// do {
/// ...
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
/// // A foreign key constraint error
/// }
///
/// See also `resultCode`.
public let extendedResultCode: ResultCode
/// The SQLite error message.
public let message: String?
@@ -30,13 +197,21 @@ public struct DatabaseError : Error {
/// The SQL query that yielded the error (if relevant).
public let sql: String?
public init(code: Int32 = SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.code = code
/// Creates a Database Error
public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.extendedResultCode = resultCode
self.message = message
self.sql = sql
self.arguments = arguments
}
/// Creates a Database Error with a raw Int32 result code.
///
/// This initializer is not public because library user is not supposed to
/// be exposed to raw result codes.
init(resultCode: Int32, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
}
// MARK: Not public
@@ -48,7 +223,7 @@ public struct DatabaseError : Error {
extension DatabaseError: CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
var description = "SQLite error \(code)"
var description = "SQLite error \(resultCode.rawValue)"
if let sql = sql {
description += " with statement `\(sql)`"
}
@@ -71,7 +246,7 @@ extension DatabaseError : CustomNSError {
/// NSError bridging: the error code within the given domain.
public var errorCode: Int {
return Int(code)
return Int(extendedResultCode.rawValue)
}
/// NSError bridging: the user-info dictionary.
+371
View File
@@ -0,0 +1,371 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// An SQL function or aggregate.
public final class DatabaseFunction {
public let name: String
let argumentCount: Int32?
let pure: Bool
private let kind: Kind
private var nArg: Int32 { return argumentCount ?? -1 }
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
/// Returns an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
/// }
/// db.add(function: fn)
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
///
/// - parameters:
/// - name: The function name.
/// - argumentCount: The number of arguments of the function. If
/// omitted, or nil, the function accepts any number of arguments.
/// - pure: Whether the function is "pure", which means that its results
/// only depends on its inputs. When a function is pure, SQLite has
/// the opportunity to perform additional optimizations. Default value
/// is false.
/// - function: A function that takes an array of DatabaseValue
/// arguments, and returns an optional DatabaseValueConvertible such
/// as Int, String, NSDate, etc. The array is guaranteed to have
/// exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
self.name = name
self.argumentCount = argumentCount
self.pure = pure
self.kind = .function{ (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
return try function(arguments)
}
}
/// Returns an SQL aggregate function.
///
/// struct MySum : DatabaseAggregate {
/// var sum: Int = 0
///
/// mutating func step(_ dbValues: [DatabaseValue]) {
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
/// sum += int
/// }
/// }
///
/// func finalize() -> DatabaseValueConvertible? {
/// return sum
/// }
/// }
///
/// let dbQueue = DatabaseQueue()
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.inDatabase { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
/// }
///
/// - parameters:
/// - name: The function name.
/// - argumentCount: The number of arguments of the aggregate. If
/// omitted, or nil, the aggregate accepts any number of arguments.
/// - pure: Whether the aggregate is "pure", which means that its
/// results only depends on its inputs. When an aggregate is pure,
/// SQLite has the opportunity to perform additional optimizations.
/// Default value is false.
/// - aggregate: A type that implements the DatabaseAggregate protocol.
/// For each step of the aggregation, its `step` method is called with
/// an array of DatabaseValue arguments. The array is guaranteed to
/// have exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) {
self.name = name
self.argumentCount = argumentCount
self.pure = pure
self.kind = .aggregate { return Aggregate() }
}
/// Calls sqlite3_create_function_v2
/// See https://sqlite.org/c3ref/create_function.html
func install(in db: Database) {
// Retain the function definition
let definition = kind.definition
let definitionP = Unmanaged.passRetained(definition).toOpaque()
let code = sqlite3_create_function_v2(
db.sqliteConnection,
name,
nArg,
eTextRep,
definitionP,
kind.xFunc,
kind.xStep,
kind.xFinal,
{ definitionP in
// Release the function definition
Unmanaged<AnyObject>.fromOpaque(definitionP!).release()
})
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
}
}
/// Calls sqlite3_create_function_v2
/// See https://sqlite.org/c3ref/create_function.html
func uninstall(in db: Database) {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
name,
nArg,
eTextRep,
nil, nil, nil, nil, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
}
}
/// The way to compute the result of a function.
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
private class FunctionDefinition {
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
self.compute = compute
}
}
/// The way to start an aggregate.
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
private class AggregateDefinition {
let makeAggregate: () -> DatabaseAggregate
init(makeAggregate: @escaping () -> DatabaseAggregate) {
self.makeAggregate = makeAggregate
}
}
/// The current state of an aggregate, storable in SQLite
private class AggregateContext {
var aggregate: DatabaseAggregate
var hasErrored = false
init(aggregate: DatabaseAggregate) {
self.aggregate = aggregate
}
}
/// A function kind: an "SQL function" or an "aggregate".
/// See http://sqlite.org/capi3ref.html#sqlite3_create_function
private enum Kind {
/// A regular function: SELECT f(1)
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(() -> DatabaseAggregate)
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var definition: AnyObject {
switch self {
case .function(let compute):
return FunctionDefinition(compute: compute)
case .aggregate(let makeAggregate):
return AggregateDefinition(makeAggregate: makeAggregate)
}
}
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
guard case .function = self else { return nil }
return { (sqliteContext, argc, argv) in
let definition = Unmanaged<FunctionDefinition>.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue()
do {
try DatabaseFunction.report(
result: definition.compute(argc, argv),
in: sqliteContext)
} catch {
DatabaseFunction.report(error: error, in: sqliteContext)
}
}
}
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
guard case .aggregate = self else { return nil }
return { (sqliteContext, argc, argv) in
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
let aggregateContext = aggregateContextU.takeUnretainedValue()
assert(!aggregateContext.hasErrored)
do {
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
try aggregateContext.aggregate.step(arguments)
} catch {
aggregateContext.hasErrored = true
DatabaseFunction.report(error: error, in: sqliteContext)
}
}
}
/// Feeds the `xFinal` parameter of sqlite3_create_function_v2
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var xFinal: (@convention(c) (OpaquePointer?) -> Void)? {
guard case .aggregate = self else { return nil }
return { (sqliteContext) in
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
let aggregateContext = aggregateContextU.takeUnretainedValue()
aggregateContextU.release()
guard !aggregateContext.hasErrored else {
return
}
do {
try DatabaseFunction.report(
result: aggregateContext.aggregate.finalize(),
in: sqliteContext)
} catch {
DatabaseFunction.report(error: error, in: sqliteContext)
}
}
}
}
/// Helper function that extracts the current state of an aggregate from an
/// sqlite function execution context.
///
/// The result must be released when the aggregate concludes.
///
/// See https://sqlite.org/c3ref/context.html
/// See https://sqlite.org/c3ref/aggregate_context.html
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
// The current aggregate buffer
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride)
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
// Buffer contains non-null pointer: load aggregate context
let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
return aggregateContextP.pointee
} else {
// Buffer contains null pointer: create aggregate context...
let aggregate = Unmanaged<AggregateDefinition>.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
.makeAggregate()
let aggregateContext = AggregateContext(aggregate: aggregate)
// retain and store in SQLite's buffer
let aggregateContextU = Unmanaged.passRetained(aggregateContext)
var aggregateContextP = aggregateContextU.toOpaque()
withUnsafeBytes(of: &aggregateContextP) {
aggregateContextBufferP.copyBytes(from: $0)
}
return aggregateContextU
}
}
private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) {
switch result?.databaseValue.storage ?? .null {
case .null:
sqlite3_result_null(sqliteContext)
case .int64(let int64):
sqlite3_result_int64(sqliteContext, int64)
case .double(let double):
sqlite3_result_double(sqliteContext, double)
case .string(let string):
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
data.withUnsafeBytes { bytes in
sqlite3_result_blob(sqliteContext, bytes, Int32(data.count), SQLITE_TRANSIENT)
}
}
}
private static func report(error: Error, in sqliteContext: OpaquePointer?) {
if let error = error as? DatabaseError {
if let message = error.message {
sqlite3_result_error(sqliteContext, message, -1)
}
sqlite3_result_error_code(sqliteContext, error.extendedResultCode.rawValue)
} else {
sqlite3_result_error(sqliteContext, "\(error)", -1)
}
}
}
extension DatabaseFunction : Hashable {
/// The hash value
public var hashValue: Int {
return name.hashValue ^ nArg.hashValue
}
/// Two functions are equal if they share the same name and arity.
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
}
}
/// The protocol for custom SQLite aggregates.
///
/// For example:
///
/// struct MySum : DatabaseAggregate {
/// var sum: Int = 0
///
/// mutating func step(_ dbValues: [DatabaseValue]) {
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
/// sum += int
/// }
/// }
///
/// func finalize() -> DatabaseValueConvertible? {
/// return sum
/// }
/// }
///
/// let dbQueue = DatabaseQueue()
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.inDatabase { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
/// }
public protocol DatabaseAggregate {
/// Creates an aggregate.
init()
/// This method is called at each step of the aggregation.
///
/// The dbValues argument contains as many values as given to the SQL
/// aggregate function.
///
/// -- One value
/// SELECT maxLength(name) FROM players
///
/// -- Two values
/// SELECT maxFullNameLength(firstName, lastName) FROM players
///
/// This method is never called after the finalize() method has been called.
mutating func step(_ dbValues: [DatabaseValue]) throws
/// Returns the final result
func finalize() throws -> DatabaseValueConvertible?
}
+171 -101
View File
@@ -1,23 +1,9 @@
import Foundation
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if os(iOS)
import UIKit
#endif
@@ -41,9 +27,6 @@ public final class DatabasePool {
public init(path: String, configuration: Configuration = Configuration()) throws {
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
// Database Store
store = try DatabaseStore(path: path, attributes: configuration.fileAttributes)
// Writer and readers share the same database schema cache
let sharedSchemaCache = SharedDatabaseSchemaCache()
@@ -79,10 +62,8 @@ public final class DatabasePool {
// Readers
readerConfig = configuration
readerConfig.readonly = true
readerConfig.defaultTransactionKind = .deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections.
readerPool = Pool<SerializedDatabase>(maximumCount: configuration.maximumReaderCount)
readerPool.makeElement = { [unowned self] in
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
let reader = try SerializedDatabase(
path: path,
configuration: self.readerConfig,
@@ -98,7 +79,7 @@ public final class DatabasePool {
}
return reader
}
})
}
#if os(iOS)
@@ -116,7 +97,7 @@ public final class DatabasePool {
/// The path to the database.
public var path: String {
return store.path
return writer.path
}
@@ -130,13 +111,13 @@ public final class DatabasePool {
///
/// - parameter kind: The checkpoint mode (default passive)
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws {
try writer.sync { db in
try write { db in
// TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and
// check whether we need a busy handler on writer and/or readers
// when kind is not .Passive.
let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil)
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: db.lastErrorMessage, sql: nil)
throw DatabaseError(resultCode: code, message: db.lastErrorMessage, sql: nil)
}
}
}
@@ -151,16 +132,10 @@ public final class DatabasePool {
/// See also setupMemoryManagement(application:)
public func releaseMemory() {
// TODO: test that this method blocks the current thread until all database accesses are completed.
writer.sync { db in
db.releaseMemory()
}
write { $0.releaseMemory() }
readerPool.forEach { reader in
reader.sync { db in
db.releaseMemory()
}
reader.sync { $0.releaseMemory() }
}
readerPool.clear()
}
@@ -212,13 +187,12 @@ public final class DatabasePool {
// MARK: - Not public
let store: DatabaseStore // Not private for tests that require syncing with the store
fileprivate let writer: SerializedDatabase
fileprivate var readerConfig: Configuration
fileprivate let readerPool: Pool<SerializedDatabase>
private let writer: SerializedDatabase
private var readerConfig: Configuration
private var readerPool: Pool<SerializedDatabase>! = nil // var and nil-initialized so that we can use `self` when creating readerPool in DatabasePool.init()
fileprivate var functions = Set<DatabaseFunction>()
fileprivate var collations = Set<DatabaseCollation>()
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
}
@@ -231,9 +205,7 @@ public final class DatabasePool {
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try readerPool.clear(andThen: {
try writer.sync { db in
try db.change(passphrase: passphrase)
}
try write { try $0.change(passphrase: passphrase) }
readerConfig.passphrase = passphrase
})
}
@@ -251,8 +223,8 @@ extension DatabasePool : DatabaseReader {
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result. The block is wrapped in a deferred transaction.
///
/// let persons = try dbPool.read { db in
/// try Person.fetchAll(...)
/// let players = try dbPool.read { db in
/// try Player.fetchAll(...)
/// }
///
/// The block is completely isolated. Eventual concurrent database updates
@@ -276,11 +248,12 @@ extension DatabasePool : DatabaseReader {
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
public func read<T>(_ block: (Database) throws -> T) throws -> T {
// The block isolation comes from the DEFERRED transaction.
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
return try readerPool.get { reader in
try reader.sync { db in
var result: T? = nil
// The block isolation comes from the DEFERRED transaction.
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
try db.inTransaction(.deferred) {
result = try block(db)
return .commit
@@ -317,21 +290,78 @@ extension DatabasePool : DatabaseReader {
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
return try readerPool.get { reader in
try reader.sync { db in
try block(db)
try reader.sync(block)
}
}
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
/// The block argument is not isolated: eventual concurrent database updates
/// are visible inside the block:
///
/// try dbPool.unsafeReentrantRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// Cursor iteration is safe, though:
///
/// try dbPool.unsafeReentrantRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync(block)
} else {
return try readerPool.get { reader in
try reader.sync(block)
}
}
}
/// Returns a reader that can be used from the current dispatch queue,
/// if any.
private var currentReader: SerializedDatabase? {
var readers: [SerializedDatabase] = []
readerPool.forEach { reader in
// We can't check for reader.onValidQueue here because
// Pool.forEach() runs its closure argument in some arbitrary
// dispatch queue. We thus extract the reader so that we can query
// it below.
readers.append(reader)
}
// Now the readers array contains some readers. The pool readers may
// already be different, because some other thread may have started
// a new read, for example.
//
// This doesn't matter: the reader we are looking for is already on
// its own dispatch queue. If it exists, is still in use, thus still
// in the pool, and thus still relevant for our check:
return readers.first { $0.onValidQueue }
}
// MARK: - Functions
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
/// let dbv = databaseValues.first!
/// guard let int = dbv.value() as Int? else {
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
@@ -342,15 +372,19 @@ extension DatabasePool : DatabaseReader {
/// }
public func add(function: DatabaseFunction) {
functions.update(with: function)
writer.sync { db in db.add(function: function) }
readerPool.forEach { $0.sync { db in db.add(function: function) } }
write { $0.add(function: function) }
readerPool.forEach { reader in
reader.sync { $0.add(function: function) }
}
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
functions.remove(function)
writer.sync { db in db.remove(function: function) }
readerPool.forEach { $0.sync { db in db.remove(function: function) } }
write { $0.remove(function: function) }
readerPool.forEach { reader in
reader.sync { $0.remove(function: function) }
}
}
@@ -367,15 +401,19 @@ extension DatabasePool : DatabaseReader {
/// }
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
writer.sync { db in db.add(collation: collation) }
readerPool.forEach { $0.sync { db in db.add(collation: collation) } }
write { $0.add(collation: collation) }
readerPool.forEach { reader in
reader.sync { $0.add(collation: collation) }
}
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
collations.remove(collation)
writer.sync { db in db.remove(collation: collation) }
readerPool.forEach { $0.sync { db in db.remove(collation: collation) } }
write { $0.remove(collation: collation) }
readerPool.forEach { reader in
reader.sync { $0.remove(collation: collation) }
}
}
}
@@ -449,13 +487,29 @@ extension DatabasePool : DatabaseWriter {
/// - throws: The error thrown by the block, or any error establishing the
/// transaction.
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
try writer.sync { db in
try write { db in
try db.inTransaction(kind) {
try block(db)
}
}
}
/// Synchronously executes an update block in a protected dispatch queue,
/// and returns its result.
///
/// Eventual concurrent database updates are postponed until the block
/// has executed.
///
/// try dbPool.unsafeReentrantWrite { db in
/// try db.execute(...)
/// }
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.reentrantSync(block)
}
// MARK: - Reading from Database
@@ -469,12 +523,12 @@ extension DatabasePool : DatabaseWriter {
/// database updates are *not visible* inside the block.
///
/// try dbPool.write { db in
/// try db.execute("DELETE FROM persons")
/// try db.execute("DELETE FROM players")
/// try dbPool.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// try db.execute("INSERT INTO persons ...")
/// try db.execute("INSERT INTO players ...")
/// }
///
/// This method blocks the current thread until the isolation guarantee has
@@ -484,48 +538,64 @@ extension DatabasePool : DatabaseWriter {
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
// https://www.sqlite.org/isolation.html
//
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
// > transaction starts, that reader continues to see an unchanging
// > "snapshot" of the database file as it existed at the moment in time
// > when the read transaction started. Any write transactions that
// > commit while the read transaction is active are still invisible to
// > the read transaction, because the reader is seeing a snapshot of
// > database file from a prior moment in time.
//
// That's exactly what we need. But what does "when read transaction
// starts" mean?
//
// http://www.sqlite.org/lang_transaction.html
//
// > Deferred [transaction] means that no locks are acquired on the
// > database until the database is first accessed. [...] Locks are not
// > acquired until the first read or write operation. [...] Because the
// > acquisition of locks is deferred until they are needed, it is
// > possible that another thread or process could create a separate
// > transaction and write to the database after the BEGIN on the
// > current thread has executed.
//
// Now that's precise enough: SQLite defers "snapshot isolation" until
// the first SELECT:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// UPDATE ... (1)
// Here the change (1) is visible
// SELECT ...
// UPDATE ... (2)
// Here the change (2) is not visible
//
// The readFromCurrentState method says that no change should be visible
// at all. We thus have to perform a select that establishes the
// snapshot isolation before we release the writer queue:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// SELECT anything
// UPDATE ...
// Here the change is not visible by GRDB user
// This method must be called from the writing dispatch queue:
writer.preconditionValidQueue()
// The semaphore that blocks the writing dispatch queue until snapshot
// isolation has been established:
let semaphore = DispatchSemaphore(value: 0)
var readError: Error? = nil
try readerPool.get { reader in
reader.async { db in
// https://www.sqlite.org/isolation.html
//
// > In WAL mode, SQLite exhibits "snapshot isolation". When a
// > read transaction starts, that reader continues to see an
// > unchanging "snapshot" of the database file as it existed at
// > the moment in time when the read transaction started.
// > Any write transactions that commit while the read
// > transaction is active are still invisible to the read
// > transaction, because the reader is seeing a snapshot of
// > database file from a prior moment in time.
//
// This documentation is NOT accurate. SQLite actually defers
// isolation until the first SELECT:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// UPDATE ... (1)
// Here the change (1) is visible
// SELECT ...
// UPDATE ... (2)
// Here the change (2) is not visible
//
// This is not the guarantee expected by this method: no change
// at all should be visible.
//
// Workaround: perform an initial read before releasing the
// writer queue:
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
// SELECT anything -- the work around
// UPDATE ...
// Here the change is not visible by GRDB user
do {
try db.beginTransaction(.deferred)
assert(db.isInsideTransaction)
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").fetchCursor().next() // doesn't work with cached statement
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
} catch {
readError = error
semaphore.signal() // Release the writer queue and rethrow error
+103 -52
View File
@@ -20,7 +20,6 @@ public final class DatabaseQueue {
/// - configuration: A configuration.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public init(path: String, configuration: Configuration = Configuration()) throws {
store = try DatabaseStore(path: path, attributes: configuration.fileAttributes)
serializedDatabase = try SerializedDatabase(
path: path,
configuration: configuration,
@@ -35,7 +34,6 @@ public final class DatabaseQueue {
///
/// - parameter configuration: A configuration.
public init(configuration: Configuration = Configuration()) {
store = nil
// Assume SQLite always succeeds creating an in-memory database
serializedDatabase = try! SerializedDatabase(
path: ":memory:",
@@ -61,9 +59,9 @@ public final class DatabaseQueue {
return serializedDatabase.configuration
}
/// The path to the database file; nil for in-memory databases.
public var path: String! {
return store?.path
/// The path to the database file; it is ":memory:" for in-memory databases.
public var path: String {
return serializedDatabase.path
}
@@ -72,8 +70,8 @@ public final class DatabaseQueue {
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// let persons = try dbQueue.inDatabase { db in
/// try Person.fetchAll(...)
/// let players = try dbQueue.inDatabase { db in
/// try Player.fetchAll(...)
/// }
///
/// This method is *not* reentrant.
@@ -107,7 +105,7 @@ public final class DatabaseQueue {
/// .commit or .rollback.
/// - throws: The error thrown by the block.
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
try serializedDatabase.sync { db in
try inDatabase { db in
try db.inTransaction(kind) {
try block(db)
}
@@ -123,9 +121,7 @@ public final class DatabaseQueue {
///
/// See also setupMemoryManagement(application:)
public func releaseMemory() {
serializedDatabase.sync { db in
db.releaseMemory()
}
inDatabase { $0.releaseMemory() }
}
@@ -175,8 +171,6 @@ public final class DatabaseQueue {
// MARK: - Not public
private let store: DatabaseStore?
// https://www.sqlite.org/isolation.html
//
@@ -195,7 +189,7 @@ public final class DatabaseQueue {
// > behavior is undefined.
//
// This is why we use a serialized database:
fileprivate var serializedDatabase: SerializedDatabase
private var serializedDatabase: SerializedDatabase
}
@@ -207,9 +201,7 @@ public final class DatabaseQueue {
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try serializedDatabase.sync { db in
try db.change(passphrase: passphrase)
}
try inDatabase { try $0.change(passphrase: passphrase) }
}
}
#endif
@@ -222,18 +214,51 @@ extension DatabaseQueue : DatabaseReader {
// MARK: - DatabaseReader Protocol Adoption
/// Alias for inDatabase
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
/// This method is part of the DatabaseReader protocol adoption.
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(...)
/// }
///
/// This method is *not* reentrant.
///
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
/// resultCode is `SQLITE_READONLY`.
///
/// - 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)
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return try inDatabase { try readOnly($0, block) }
#else
if #available(iOS 8.2, OSX 10.10, *) {
return try inDatabase { try readOnly($0, block) }
} else {
return try inDatabase(block)
}
#endif
}
/// Alias for inDatabase
///
/// This method is part of the DatabaseReader protocol adoption.
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
return try inDatabase(block)
}
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// try dbQueue.unsafeReentrantRead { db in
/// try db.execute(...)
/// }
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try serializedDatabase.reentrantSync(block)
}
@@ -241,9 +266,8 @@ extension DatabaseQueue : DatabaseReader {
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
/// let dbv = databaseValues.first!
/// guard let int = dbv.value() as Int? else {
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
@@ -253,16 +277,12 @@ extension DatabaseQueue : DatabaseReader {
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
serializedDatabase.sync { db in
db.add(function: function)
}
inDatabase { $0.add(function: function) }
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
serializedDatabase.sync { db in
db.remove(function: function)
}
inDatabase { $0.remove(function: function) }
}
@@ -278,16 +298,12 @@ extension DatabaseQueue : DatabaseReader {
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func add(collation: DatabaseCollation) {
serializedDatabase.sync { db in
db.add(collation: collation)
}
inDatabase { $0.add(collation: collation) }
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
serializedDatabase.sync { db in
db.remove(collation: collation)
}
inDatabase { $0.remove(collation: collation) }
}
}
@@ -299,25 +315,60 @@ extension DatabaseQueue : DatabaseWriter {
// MARK: - DatabaseWriter Protocol Adoption
/// Alias for inDatabase
///
/// This method is part of the DatabaseWriter protocol adoption.
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
/// Alias for inTransaction
///
/// This method is part of the DatabaseWriter protocol adoption.
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
try inTransaction(kind, block)
}
/// Synchronously executes *block*.
///
/// This method is part of the DatabaseWriter protocol adoption, and must
/// be called from the protected database dispatch queue.
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
/// resultCode is `SQLITE_READONLY`.
///
/// This method must be called from the protected database dispatch queue.
/// See `DatabaseWriter.readFromCurrentState`.
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
serializedDatabase.execute(block)
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
serializedDatabase.execute { readOnly($0, block) }
#else
if #available(iOS 8.2, OSX 10.10, *) {
serializedDatabase.execute { readOnly($0, block) }
} else {
serializedDatabase.execute(block)
}
#endif
}
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
/// try dbQueue.unsafeReentrantWrite { db in
/// try db.execute(...)
/// }
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.reentrantSync(block)
}
}
// Wraps the block between two `PRAGMA query_only` statements.
//
// This method is unsafe because the two calls to `PRAGMA query_only` are
// not guaranteed to be serialized (some other thread could mess with this).
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
if db.configuration.readonly {
return try block(db)
} else {
try! db.execute("PRAGMA query_only = 1") // Assume can't fail
let result = try block(db)
try! db.execute("PRAGMA query_only = 0") // Assume can't fail
return result
}
}
+97 -26
View File
@@ -1,19 +1,7 @@
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// The protocol for all types that can fetch values from a database.
@@ -38,8 +26,8 @@ public protocol DatabaseReader : class {
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
///
/// The block argument is isolated. Eventual concurrent database updates are
/// not visible inside the block:
/// Guarantee 1: the block argument is isolated. Eventual concurrent
/// database updates are not visible inside the block:
///
/// try reader.read { db in
/// // Those two values are guaranteed to be equal, even if the
@@ -53,6 +41,10 @@ public protocol DatabaseReader : class {
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
/// and SQLCipher, attempts to write in the database throw a DatabaseError
/// whose resultCode is `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
@@ -61,6 +53,8 @@ public protocol DatabaseReader : class {
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
///
/// The two guarantees of the safe `read` method are lifted:
///
/// The block argument is not isolated: eventual concurrent database updates
/// are visible inside the block:
///
@@ -71,7 +65,7 @@ public protocol DatabaseReader : class {
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// Cursor iteration is safe, though:
/// Cursor iterations are isolated, though:
///
/// try reader.unsafeRead { db in
/// // No concurrent update can mess with this iteration:
@@ -79,19 +73,55 @@ public protocol DatabaseReader : class {
/// while let row = try rows.next() { ... }
/// }
///
/// The block argument is not prevented from writing (DatabaseQueue, in
/// particular, will accept database modifications in `unsafeRead`).
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
/// Synchronously executes a block that takes a database connection, and
/// returns its result.
///
/// The two guarantees of the safe `read` method are lifted:
///
/// The block argument is not isolated: eventual concurrent database updates
/// are visible inside the block:
///
/// try reader.unsafeReentrantRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// Cursor iterations are isolated, though:
///
/// try reader.unsafeReentrantRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
/// The block argument is not prevented from writing (DatabaseQueue, in
/// particular, will accept database modifications in `unsafeReentrantRead`).
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
// MARK: - Functions
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
/// let dbv = databaseValues.first!
/// guard let int = dbv.value() as Int? else {
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
@@ -141,10 +171,10 @@ extension DatabaseReader {
try read { dbFrom in
try writer.write { dbDest in
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
throw DatabaseError(code: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
}
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError(code: SQLITE_ERROR)
throw DatabaseError(resultCode: .SQLITE_ERROR)
}
afterBackupInit?()
@@ -158,7 +188,7 @@ extension DatabaseReader {
case SQLITE_OK:
afterBackupStep?()
case let code:
throw DatabaseError(code: code, message: dbDest.lastErrorMessage)
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
}
}
} catch {
@@ -170,7 +200,7 @@ extension DatabaseReader {
case SQLITE_OK:
break
case let code:
throw DatabaseError(code: code, message: dbDest.lastErrorMessage)
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
}
dbDest.clearSchemaCache()
@@ -178,3 +208,44 @@ extension DatabaseReader {
}
}
}
/// A type-erased DatabaseReader
///
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
/// underlying database reader.
public final class AnyDatabaseReader : DatabaseReader {
private let base: DatabaseReader
/// Creates a database reader that wraps a base database reader.
public init(_ base: DatabaseReader) {
self.base = base
}
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
public func add(function: DatabaseFunction) {
base.add(function: function)
}
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
}
+52 -31
View File
@@ -7,50 +7,63 @@
protocol DatabaseSchemaCache {
mutating func clear()
func primaryKey(_ tableName: String) -> PrimaryKeyInfo??
mutating func set(primaryKey: PrimaryKeyInfo?, for tableName: String)
func primaryKey(_ table: String) -> PrimaryKeyInfo?
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
func columns(in tableName: String) -> [ColumnInfo]?
mutating func set(columns: [ColumnInfo], forTableName tableName: String)
func columns(in table: String) -> [ColumnInfo]?
mutating func set(columns: [ColumnInfo], forTable table: String)
func indexes(on tableName: String) -> [IndexInfo]?
mutating func set(indexes: [IndexInfo], forTableName tableName: String)
func indexes(on table: String) -> [IndexInfo]?
mutating func set(indexes: [IndexInfo], forTable table: String)
func foreignKeys(on table: String) -> [ForeignKeyInfo]?
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String)
}
/// A thread-unsafe database schema cache
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
private var primaryKeys: [String: PrimaryKeyInfo?] = [:]
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
private var columns: [String: [ColumnInfo]] = [:]
private var indexes: [String: [IndexInfo]] = [:]
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
func clear() {
primaryKeys = [:]
columns = [:]
indexes = [:]
foreignKeys = [:]
}
func primaryKey(_ tableName: String) -> PrimaryKeyInfo?? {
return primaryKeys[tableName]
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return primaryKeys[table]
}
func set(primaryKey: PrimaryKeyInfo?, for tableName: String) {
primaryKeys[tableName] = primaryKey
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
primaryKeys[table] = primaryKey
}
func columns(in tableName: String) -> [ColumnInfo]? {
return columns[tableName]
func columns(in table: String) -> [ColumnInfo]? {
return columns[table]
}
func set(columns: [ColumnInfo], forTableName tableName: String) {
self.columns[tableName] = columns
func set(columns: [ColumnInfo], forTable table: String) {
self.columns[table] = columns
}
func indexes(on tableName: String) -> [IndexInfo]? {
return indexes[tableName]
func indexes(on table: String) -> [IndexInfo]? {
return indexes[table]
}
func set(indexes: [IndexInfo], forTableName tableName: String) {
self.indexes[tableName] = indexes
func set(indexes: [IndexInfo], forTable table: String) {
self.indexes[table] = indexes
}
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
return foreignKeys[table]
}
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
self.foreignKeys[table] = foreignKeys
}
}
@@ -62,27 +75,35 @@ final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
cache.write { $0.clear() }
}
func primaryKey(_ tableName: String) -> PrimaryKeyInfo?? {
return cache.read { $0.primaryKey(tableName) }
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return cache.read { $0.primaryKey(table) }
}
func set(primaryKey: PrimaryKeyInfo?, for tableName: String) {
cache.write { $0.set(primaryKey: primaryKey, for: tableName) }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
}
func columns(in tableName: String) -> [ColumnInfo]? {
return cache.read { $0.columns(in: tableName) }
func columns(in table: String) -> [ColumnInfo]? {
return cache.read { $0.columns(in: table) }
}
func set(columns: [ColumnInfo], forTableName tableName: String) {
cache.write { $0.set(columns: columns, forTableName: tableName) }
func set(columns: [ColumnInfo], forTable table: String) {
cache.write { $0.set(columns: columns, forTable: table) }
}
func indexes(on tableName: String) -> [IndexInfo]? {
return cache.read { $0.indexes(on: tableName) }
func indexes(on table: String) -> [IndexInfo]? {
return cache.read { $0.indexes(on: table) }
}
func set(indexes: [IndexInfo], forTableName tableName: String) {
cache.write { $0.set(indexes: indexes, forTableName: tableName) }
func set(indexes: [IndexInfo], forTable table: String) {
cache.write { $0.set(indexes: indexes, forTable: table) }
}
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
return cache.read { $0.foreignKeys(on: table) }
}
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
cache.write { $0.set(foreignKeys: foreignKeys, forTable: table) }
}
}
-87
View File
@@ -1,87 +0,0 @@
import Foundation
/// DatabaseStore is responsible for applying Configuration.fileAttributes to
/// all database files (db.sqlite, db.sqlite-wal, db.sqlite-shm,
/// db.sqlite-journal, etc.)
class DatabaseStore {
let path: String
private let source: DispatchSourceFileSystemObject?
private let queue: DispatchQueue?
init(path: String, attributes: [FileAttributeKey: Any]?) throws {
self.path = path
guard let attributes = attributes else {
self.queue = nil
self.source = nil
return
}
let databaseFileName = (path as NSString).lastPathComponent
let directoryPath = (path as NSString).deletingLastPathComponent
// Apply file attributes on existing files
try DatabaseStore.setFileAttributes(
directoryPath: directoryPath,
databaseFileName: databaseFileName,
attributes: attributes)
// We use a dispatch_source to monitor the contents of the database file
// parent directory, and apply file attributes.
//
// This require a file descriptor on the directory.
let directoryDescriptor = open(directoryPath, O_EVTONLY)
guard directoryDescriptor != -1 else {
// Let FileManager throw a nice NSError
try FileManager.default.contentsOfDirectory(atPath: directoryPath)
// Come on, FileManager... OK just throw something that is somewhat relevant
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
let queue = DispatchQueue(label: "GRDB.DatabaseStore")
let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: Int32(directoryDescriptor), eventMask: [.write], queue: queue)
self.queue = queue
self.source = source
// Configure dispatch source
source.setEventHandler {
// Directory has been modified: apply file attributes on unprocessed files
// TODO: handle error and don't crash
try! DatabaseStore.setFileAttributes(
directoryPath: directoryPath,
databaseFileName: databaseFileName,
attributes: attributes)
}
source.setCancelHandler {
close(directoryDescriptor)
}
source.resume()
}
deinit {
if let source = source {
source.cancel()
}
}
private static func setFileAttributes(directoryPath: String, databaseFileName: String, attributes: [FileAttributeKey: Any]) throws {
let fm = FileManager.default
// TODO: handle symbolic links:
//
// According to https://www.sqlite.org/changes.html
// > 2016-01-06 (3.10.0)
// > On unix, if a symlink to a database file is opened, then the
// > corresponding journal files are based on the actual filename,
// > not the symlink name.
let fileNames = try fm.contentsOfDirectory(atPath: directoryPath).filter({ $0.hasPrefix(databaseFileName) })
for fileName in fileNames {
do {
try fm.setAttributes(attributes, ofItemAtPath: (directoryPath as NSString).appendingPathComponent(fileName))
} catch let error as NSError {
guard error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError else {
throw error
}
}
}
}
}
+186 -104
View File
@@ -1,21 +1,8 @@
import Foundation
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - DatabaseValue
@@ -26,7 +13,7 @@ import Foundation
public struct DatabaseValue {
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
public enum Storage {
public enum Storage : Equatable {
/// The NULL storage class.
case null
@@ -41,6 +28,38 @@ public struct DatabaseValue {
/// The BLOB storage class, wrapping Data.
case blob(Data)
/// Returns Int64, Double, String, Data or nil.
public var value: DatabaseValueConvertible? {
switch self {
case .null:
return nil
case .int64(let int64):
return int64
case .double(let double):
return double
case .string(let string):
return string
case .blob(let data):
return data
}
}
/// Return true if the storages are identical.
///
/// Unlike DatabaseValue equality that considers the integer 1 to be
/// equal to the 1.0 double (as SQLite does), int64 and double storages
/// are never equal.
public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool {
switch (lhs, rhs) {
case (.null, .null): return true
case (.int64(let lhs), .int64(let rhs)): return lhs == rhs
case (.double(let lhs), .double(let rhs)): return lhs == rhs
case (.string(let lhs), .string(let rhs)): return lhs == rhs
case (.blob(let lhs), .blob(let rhs)): return lhs == rhs
default: return false
}
}
}
/// The SQLite storage
@@ -72,64 +91,10 @@ public struct DatabaseValue {
}
}
/// Returns Int64, Double, String, Data or nil.
public func value() -> DatabaseValueConvertible? {
switch storage {
case .null:
return nil
case .int64(let int64):
return int64
case .double(let double):
return double
case .string(let string):
return string
case .blob(let data):
return data
}
}
/// Returns the value, converted to the requested type.
///
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
/// value is converted to the requested type `Value`. Should this conversion
/// fail, a fatal error is raised.
///
/// If this fatal error is unacceptable to you, use
/// DatabaseValueConvertible.fromDatabaseValue() method.
///
/// - returns: An optional *Value*.
public func value<Value: DatabaseValueConvertible>() -> Value? {
if let value = Value.fromDatabaseValue(self) {
return value
}
guard isNull else {
// Programmer error
fatalError("could not convert database value \(self) to \(Value.self)")
}
return nil
}
/// Returns the value, converted to the requested type.
///
/// This method crashes if the SQLite value is NULL, or if the SQLite value
/// can not be converted to `Value`.
///
/// - returns: A *Value*.
public func value<Value: DatabaseValueConvertible>() -> Value {
guard let value = Value.fromDatabaseValue(self) else {
// Programmer error
fatalError("could not convert database value \(self) to \(Value.self)")
}
return value
}
// MARK: - Not Public
init(storage: Storage) {
// This initializer is not public because Storage is not a safe type:
// one can create a Storage of zero-length Data, which is invalid
// because SQLite can't store zero-length blobs.
self.storage = storage
}
@@ -145,9 +110,12 @@ public struct DatabaseValue {
case SQLITE_TEXT:
storage = .string(String(cString: sqlite3_value_text(sqliteValue)!))
case SQLITE_BLOB:
let bytes = unsafeBitCast(sqlite3_value_blob(sqliteValue), to: UnsafePointer<UInt8>.self)
let count = Int(sqlite3_value_bytes(sqliteValue))
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
if let bytes = sqlite3_value_blob(sqliteValue) {
let count = Int(sqlite3_value_bytes(sqliteValue))
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
} else {
storage = .blob(Data())
}
case let type:
// Assume a GRDB bug: there is no point throwing any error.
fatalError("Unexpected SQLite value type: \(type)")
@@ -166,9 +134,12 @@ public struct DatabaseValue {
case SQLITE_TEXT:
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, Int32(index))))
case SQLITE_BLOB:
let bytes = unsafeBitCast(sqlite3_column_blob(sqliteStatement, Int32(index)), to: UnsafePointer<UInt8>.self)
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
} else {
storage = .blob(Data())
}
case let type:
// Assume a GRDB bug: there is no point throwing any error.
fatalError("Unexpected SQLite column type: \(type)")
@@ -209,7 +180,12 @@ extension DatabaseValue : Hashable {
/// not lose information:
///
/// 1.databaseValue == 1.0.databaseValue // true
public static func ==(lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
///
/// For a comparison that distinguishes integer and doubles, compare
/// storages instead:
///
/// 1.databaseValue.storage == 1.0.databaseValue.storage // false
public static func == (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
switch (lhs.storage, rhs.storage) {
case (.null, .null):
return true
@@ -218,9 +194,9 @@ extension DatabaseValue : Hashable {
case (.double(let lhs), .double(let rhs)):
return lhs == rhs
case (.int64(let lhs), .double(let rhs)):
return int64EqualDouble(lhs, rhs)
return Int64(exactly: rhs) == lhs
case (.double(let lhs), .int64(let rhs)):
return int64EqualDouble(rhs, lhs)
return rhs == Int64(exactly: lhs)
case (.string(let lhs), .string(let rhs)):
return lhs == rhs
case (.blob(let lhs), .blob(let rhs)):
@@ -231,21 +207,87 @@ extension DatabaseValue : Hashable {
}
}
/// Returns true if i and d hold exactly the same value, and if converting one
/// type to the other does not lose any information.
private func int64EqualDouble(_ i: Int64, _ d: Double) -> Bool {
// TODO: wait for https://github.com/apple/swift-evolution/blob/master/proposals/0080-failable-numeric-initializers.md
// Bug: https://bugs.swift.org/browse/SR-1491
//
// For current implementation, see http://stackoverflow.com/questions/33719132/how-to-test-for-lossless-double-integer-conversion/33784296#33784296
return (d >= Double(Int64.min))
&& (d < Double(Int64.max))
&& (round(d) == d)
&& (i == Int64(d))
// MARK: - Lossless conversions
extension DatabaseValue {
/// Converts the database value to the type T.
///
/// let dbValue = "foo".databaseValue
/// let string = dbValue.losslessConvert() as String // "foo"
///
/// Conversion is successful if and only if T.fromDatabaseValue returns a
/// non-nil value.
///
/// This method crashes with a fatal error when conversion fails.
///
/// let dbValue = "foo".databaseValue
/// let int = dbValue.losslessConvert() as Int // fatalError
///
/// - parameters:
/// - sql: Optional SQL statement that enhances the eventual
/// conversion error
/// - arguments: Optional statement arguments that enhances the eventual
/// conversion error
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T : DatabaseValueConvertible {
if let value = T.fromDatabaseValue(self) {
return value
}
// Failed conversion: this is data loss, a programmer error.
var error = "could not convert database value \(self) to \(T.self)"
if let sql = sql {
error += " with statement `\(sql)`"
}
if let arguments = arguments, !arguments.isEmpty {
error += " arguments \(arguments)"
}
fatalError(error)
}
/// Converts the database value to the type Optional<T>.
///
/// let dbValue = "foo".databaseValue
/// let string = dbValue.losslessConvert() as String? // "foo"
/// let null = DatabaseValue.null.losslessConvert() as String? // nil
///
/// Conversion is successful if and only if T.fromDatabaseValue returns a
/// non-nil value.
///
/// This method crashes with a fatal error when conversion fails.
///
/// let dbValue = "foo".databaseValue
/// let int = dbValue.losslessConvert() as Int? // fatalError
///
/// - parameters:
/// - sql: Optional SQL statement that enhances the eventual
/// conversion error
/// - arguments: Optional statement arguments that enhances the eventual
/// conversion error
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T : DatabaseValueConvertible {
// Use fromDatabaseValue first: this allows DatabaseValue to convert NULL to .null.
if let value = T.fromDatabaseValue(self) {
return value
}
if isNull {
// Failed conversion from null: ok
return nil
} else {
// Failed conversion from a non-null database value: this is data
// loss, a programmer error.
var error = "could not convert database value \(self) to \(T.self)"
if let sql = sql {
error += " with statement `\(sql)`"
}
if let arguments = arguments, !arguments.isEmpty {
error += " arguments \(arguments)"
}
fatalError(error)
}
}
}
// MARK: - DatabaseValueConvertible
// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression
/// DatabaseValue adopts DatabaseValueConvertible.
extension DatabaseValue : DatabaseValueConvertible {
@@ -254,24 +296,64 @@ extension DatabaseValue : DatabaseValueConvertible {
return self
}
/// Returns `databaseValue`
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseValue? {
return databaseValue
/// Returns the database value
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseValue? {
return dbValue
}
}
extension DatabaseValue : SQLExpressible {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// See SQLExpression.sqlExpression
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var sqlExpression: SQLExpression {
return self
}
}
/// DatabaseValue adopts SQLExpression.
extension DatabaseValue : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
// fast path for NULL
if isNull {
return "NULL"
}
if arguments != nil {
arguments!.values.append(self)
return "?"
} else {
// Correctness above all: use SQLite to quote the value.
// Assume that the Quote function always succeeds
return DatabaseQueue().inDatabase { try! String.fetchOne($0, "SELECT QUOTE(?)", arguments: [self])! }
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var negated: SQLExpression {
switch storage {
case .null:
// SELECT NOT NULL -- NULL
return DatabaseValue.null
case .int64(let int64):
return (int64 == 0).sqlExpression
case .double(let double):
return (double == 0.0).sqlExpression
case .string:
// We can't assume all strings are true, and return false:
//
// SELECT NOT '1' -- 0 (because '1' is turned into the integer 1, which is negated into 0)
// SELECT NOT '0' -- 1 (because '0' is turned into the integer 0, which is negated into 1)
return SQLExpressionNot(self)
case .blob:
// We can't assume all blobs are true, and return false:
//
// SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', then into integer 1, which is negated into 0)
// SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', then into integer 0, which is negated into 1)
return SQLExpressionNot(self)
}
}
}
// MARK: - CustomStringConvertible
+111 -100
View File
@@ -1,37 +1,9 @@
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - SQLExpressible
/// The protocol for all types that can be turned into an SQL expression.
///
/// It is adopted by protocols like DatabaseValueConvertible, and types
/// like Column.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public protocol SQLExpressible {
/// Returns an SQLExpression
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
var sqlExpression: SQLExpression { get }
}
// MARK: - DatabaseValueConvertible
/// Types that adopt DatabaseValueConvertible can be initialized from
@@ -40,12 +12,12 @@ public protocol SQLExpressible {
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String?
///
@@ -54,37 +26,106 @@ public protocol DatabaseValueConvertible : SQLExpressible {
/// 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?
/// Returns a value initialized from *dbValue*, if possible.
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
}
// SQLExpressible adoption
extension DatabaseValueConvertible {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// See SQLExpression.sqlExpression
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var sqlExpression: SQLExpression {
return databaseValue
}
}
/// A cursor of database values extracted from a single column.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM links")
/// while let url = urls.next() { // URL
/// print(url)
/// }
/// }
public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
}
public func next() throws -> Value? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
return dbValue.losslessConvert() as Value
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
/// A cursor of optional database values extracted from a single column.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM links")
/// while let url = urls.next() { // URL?
/// print(url)
/// }
/// }
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
}
public func next() throws -> Value?? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
return dbValue.losslessConvert() as Value?
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// cursors, arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String
///
@@ -97,7 +138,7 @@ extension DatabaseValueConvertible {
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
/// let names = try String.fetchCursor(statement) // Cursor of String
/// while let name = try names.next() { // String
/// ...
/// }
@@ -113,17 +154,8 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
// Reuse a single mutable row for performance
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
return statement.fetchCursor(arguments: arguments) { () -> Self in
let dbv: DatabaseValue = row.value(atIndex: 0)
if let value = Self.fromDatabaseValue(dbv) {
return value
} else {
throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Self.self)", sql: statement.sql, arguments: arguments)
}
}
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of values fetched from a prepared statement.
@@ -156,18 +188,8 @@ extension DatabaseValueConvertible {
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
// Reuse a single mutable row for performance
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
let cursor = statement.fetchCursor(arguments: arguments) { () -> Self? in
let dbv: DatabaseValue = row.value(atIndex: 0)
if let value = Self.fromDatabaseValue(dbv) {
return value
} else if dbv.isNull {
return nil
} else {
throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Self.self)", sql: statement.sql, arguments: arguments)
}
}
// fetchOne returns nil if there is no row, or if there is a row with a null value
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
return try cursor.next() ?? nil
}
}
@@ -179,8 +201,8 @@ extension DatabaseValueConvertible {
/// Returns a cursor over values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
/// let request = Player.select(nameColumn)
/// let names = try String.fetchCursor(db, request) // Cursor of String
/// for let name = try names.next() { // String
/// ...
/// }
@@ -195,7 +217,7 @@ extension DatabaseValueConvertible {
/// - request: A fetch request.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
@@ -203,7 +225,7 @@ extension DatabaseValueConvertible {
/// Returns an array of values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let request = Player.select(nameColumn)
/// let names = try String.fetchAll(db, request) // [String]
///
/// - parameter db: A database connection.
@@ -219,7 +241,7 @@ extension DatabaseValueConvertible {
/// extracted from the first row.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let request = Player.select(nameColumn)
/// let name = try String.fetchOne(db, request) // String?
///
/// - parameter db: A database connection.
@@ -236,7 +258,7 @@ extension DatabaseValueConvertible {
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String>
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
/// while let name = try name.next() { // String
/// ...
/// }
@@ -253,7 +275,7 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
@@ -295,11 +317,11 @@ extension DatabaseValueConvertible {
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
///
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String?>
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try Optional<String>.fetchCursor(statement, arguments:...) // DatabaseCursor<String?>
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
@@ -310,7 +332,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try Optional<String>.fetchCursor(statement) // DatabaseCursor<String?>
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
@@ -326,19 +348,8 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
// Reuse a single mutable row for performance
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
return statement.fetchCursor(arguments: arguments) { () -> Wrapped? in
let dbv: DatabaseValue = row.value(atIndex: 0)
if let value = Wrapped.fromDatabaseValue(dbv) {
return value
} else if dbv.isNull {
return nil
} else {
throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Wrapped.self)", sql: statement.sql, arguments: arguments)
}
}
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of optional values fetched from a prepared statement.
@@ -364,8 +375,8 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns a cursor over optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = try Optional<String>.fetchCursor(db, request) // DatabaseCursor<String?>
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
@@ -380,7 +391,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - requet: A fetch request.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Wrapped?> {
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
@@ -388,7 +399,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns an array of optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
///
/// - parameter db: A database connection.
@@ -405,7 +416,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns a cursor over optional values fetched from an SQL query.
///
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String?>
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
@@ -422,7 +433,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
+78 -20
View File
@@ -26,7 +26,16 @@ public protocol DatabaseWriter : DatabaseReader {
/// This method is *not* reentrant.
func write<T>(_ block: (Database) throws -> T) rethrows -> T
/// Synchronously executes a block that takes a database connection, and
/// returns its result.
///
/// Eventual concurrent database updates are postponed until the block
/// has executed.
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
// MARK: - Reading from Database
/// Synchronously or asynchronously executes a read-only block that takes a
@@ -44,12 +53,12 @@ public protocol DatabaseWriter : DatabaseReader {
/// state is the last committed state.
///
/// try writer.write { db in
/// try db.execute("DELETE FROM persons")
/// try db.execute("DELETE FROM players")
/// try writer.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// try db.execute("INSERT INTO persons ...")
/// try db.execute("INSERT INTO players ...")
/// }
///
/// - When this method is called inside an uncommitted transation, the
@@ -62,12 +71,12 @@ public protocol DatabaseWriter : DatabaseReader {
/// the database in its last committed state.
///
/// try dbPool.write { db in
/// try db.execute("DELETE FROM persons")
/// try db.execute("DELETE FROM players")
/// db.inTransaction {
/// try db.execute("INSERT INTO persons ...")
/// try db.execute("INSERT INTO players ...")
/// try dbPool.readFromCurrentState { db in
/// // Zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// return .commit
/// }
@@ -79,12 +88,12 @@ public protocol DatabaseWriter : DatabaseReader {
/// is run after the select.
///
/// try dbQueue.write { db in
/// try db.execute("DELETE FROM persons")
/// try db.execute("DELETE FROM players")
/// db.inTransaction {
/// try db.execute("INSERT INTO persons ...")
/// try db.execute("INSERT INTO players ...")
/// try dbQueue.readFromCurrentState { db in
/// // One
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
/// }
/// return .commit
/// }
@@ -101,20 +110,69 @@ extension DatabaseWriter {
/// Add a transaction observer, so that it gets notified of
/// database changes.
///
/// The transaction observer is weakly referenced: it is not retained, and
/// stops getting notifications after it is deallocated.
///
/// - parameter transactionObserver: A transaction observer.
public func add(transactionObserver: TransactionObserver) {
write { db in
db.add(transactionObserver: transactionObserver)
}
/// - parameter extent: The duration of the observation. The default is
/// the observer lifetime (observation lasts until observer
/// is deallocated).
public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) {
write { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
/// Remove a transaction observer.
public func remove(transactionObserver: TransactionObserver) {
write { db in
db.remove(transactionObserver: transactionObserver)
}
write { $0.remove(transactionObserver: transactionObserver) }
}
}
/// A type-erased DatabaseWriter
///
/// Instances of AnyDatabaseWriter forward their methods to an arbitrary
/// underlying database writer.
public final class AnyDatabaseWriter : DatabaseWriter {
private let base: DatabaseWriter
/// Creates a database writer that wraps a base database writer.
public init(_ base: DatabaseWriter) {
self.base = base
}
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
public func add(function: DatabaseFunction) {
base.add(function: function)
}
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.write(block)
}
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.unsafeReentrantWrite(block)
}
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
try base.readFromCurrentState(block)
}
}
+236 -94
View File
@@ -1,47 +1,100 @@
/// The protocol for all types that define a way to fetch values from
/// a database.
/// The protocol for all types that define a way to fetch database rows.
///
/// Requests can feed the fetching methods of any fetchable type (Row,
/// value, record):
///
/// let request: Request = ...
/// try Row.fetchCursor(db, request) // DatabaseCursor<Row>
/// try Row.fetchCursor(db, request) // RowCursor
/// try String.fetchAll(db, request) // [String]
/// try Person.fetchOne(db, request) // Person?
/// try Player.fetchOne(db, request) // Player?
public protocol Request {
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
/// The number of rows fetched by the request.
///
/// Default implementation builds a naive SQL query based on the statement
/// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
///
/// Adopting types can refine this countRequest method and return more
/// efficient SQL.
///
/// - parameter db: A database connection.
func fetchCount(_ db: Database) throws -> Int
}
extension Request {
/// Returns a TypedRequest bound to type T.
/// The number of rows fetched by the request.
///
/// This default implementation builds a naive SQL query based on the
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
let (statement, _) = try prepare(db)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
}
}
extension Request {
/// Returns a request bound to type T.
///
/// The returned request can fetch if the type T is fetchable (Row,
/// value, record).
///
/// let minHeight = Person
/// .select(min(heightColumn))
/// .bound(to: Double.self) // <--
/// // Int?
/// let maxScore = Player
/// .select(max(scoreColumn))
/// .asRequest(of: Int.self) // <--
/// .fetchOne(db)
///
/// - parameter type: The fetched type T
/// - returns: A typed request bound to type T.
public func bound<T>(to type: T.Type) -> AnyTypedRequest<T> {
public func asRequest<T>(of type: T.Type) -> AnyTypedRequest<T> {
return AnyTypedRequest { try self.prepare($0) }
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an adapted request.
public func adapted(_ makeAdapter: @escaping (Database) throws -> RowAdapter) -> AnyRequest {
return AnyRequest { db in
let (statement, adapter) = try self.prepare(db)
if let adapter = adapter {
return try (statement, ChainedAdapter(first: adapter, second: makeAdapter(db)))
} else {
return try (statement, makeAdapter(db))
}
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self> {
return AdaptedRequest(self, adapter)
}
}
/// An adapted request.
public struct AdaptedRequest<Base: Request> : Request {
/// 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) {
self.base = base
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.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let (statement, baseAdapter) = try base.prepare(db)
if let baseAdapter = baseAdapter {
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
} else {
return try (statement, adapter(db))
}
}
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
return try base.fetchCount(db)
}
private let base: Base
private let adapter: (Database) throws -> RowAdapter
}
/// A type-erased Request.
@@ -62,6 +115,8 @@ public struct AnyRequest : Request {
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
}
@@ -74,18 +129,50 @@ public struct SQLRequest : Request {
/// Creates a new request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM persons")
/// let request = SQLRequest("SELECT * FROM persons WHERE id = ?", arguments: [1])
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) {
/// let request = SQLRequest("SELECT * FROM players")
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .user : nil)
}
/// Creates a new request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM players")
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - statementCacheName: Optional statement cache name.
/// - returns: A SQLRequest
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache statementCacheName: Database.StatementCacheName?) {
self.sql = sql
self.arguments = arguments
self.adapter = adapter
self.statementCacheName = statementCacheName
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement = try db.makeSelectStatement(sql)
let statement: SelectStatement
if let statementCacheName = statementCacheName {
statement = try db.selectStatement(sql, fromCache: statementCacheName)
} else {
statement = try db.makeSelectStatement(sql)
}
if let arguments = arguments {
try statement.setArgumentsWithValidation(arguments)
}
@@ -95,48 +182,74 @@ public struct SQLRequest : Request {
private let sql: String
private let arguments: StatementArguments?
private let adapter: RowAdapter?
private let statementCacheName: Database.StatementCacheName?
}
/// The protocol for all types that define a way to fetch values from
/// a database, with an attached type.
/// The protocol for requests that know how to decode database rows.
///
/// Typed requests can fetch if their associated type Fetched is fetchable
/// (Row, value, record)
/// Typed requests can fetch if their associated type RowDecoder is able to
/// decode rows (Row, value, record)
///
/// let request: ... // Some TypedRequest that fetches Person
/// try request.fetchCursor(db) // DatabaseCursor<Person>
/// try request.fetchAll(db) // [Person]
/// try request.fetchOne(db) // Person?
/// struct Player: RowConvertible { ... }
/// let request: ... // Some TypedRequest that fetches Player
/// try request.fetchCursor(db) // Cursor of Player
/// try request.fetchAll(db) // [Player]
/// try request.fetchOne(db) // Player?
public protocol TypedRequest : Request {
/// The fetched type
associatedtype Fetched
/// The type that can convert raw database rows to fetched values
associatedtype RowDecoder
}
extension TypedRequest {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an adapted typed request.
public func adapted(_ makeAdapter: @escaping (Database) throws -> RowAdapter) -> AnyTypedRequest<Fetched> {
return AnyTypedRequest { db in
let (statement, adapter) = try self.prepare(db)
if let adapter = adapter {
return try (statement, ChainedAdapter(first: adapter, second: makeAdapter(db)))
} else {
return try (statement, makeAdapter(db))
}
}
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self> {
return AdaptedTypedRequest(self, adapter)
}
}
/// 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
/// 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)
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try adaptedRequest.prepare(db)
}
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
return try adaptedRequest.fetchCount(db)
}
private let adaptedRequest: AdaptedRequest<Base>
}
/// A type-erased TypedRequest.
///
/// An instance of AnyTypedRequest forwards its operations to an underlying
/// typed request, hiding its specifics.
public struct AnyTypedRequest<T> : TypedRequest {
/// The fetched type
public typealias Fetched = T
/// The type that can convert raw database rows to fetched values
public typealias RowDecoder = T
/// Creates a new request that wraps and forwards operations to `request`.
public init<Request>(_ request: Request) where Request: TypedRequest, Request.Fetched == Fetched {
public init<Request>(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder {
self._prepare = { try request.prepare($0) }
}
@@ -148,6 +261,8 @@ public struct AnyTypedRequest<T> : TypedRequest {
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
}
@@ -155,15 +270,15 @@ public struct AnyTypedRequest<T> : TypedRequest {
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
}
extension TypedRequest where Fetched: RowConvertible {
extension TypedRequest where RowDecoder: RowConvertible {
// MARK: Fetching Record and RowConvertible
/// A cursor over fetched records.
///
/// let request: ... // Some TypedRequest that fetches Person
/// let persons = try request.fetchCursor(db) // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// let request: ... // Some TypedRequest that fetches Player
/// let players = try request.fetchCursor(db) // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
///
@@ -175,43 +290,43 @@ extension TypedRequest where Fetched: RowConvertible {
/// - parameter db: A database connection.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Fetched> {
return try Fetched.fetchCursor(db, self)
public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched records.
///
/// let request: ... // Some TypedRequest that fetches Person
/// let persons = try request.fetchAll(db) // [Person]
/// let request: ... // Some TypedRequest that fetches Player
/// let players = try request.fetchAll(db) // [Player]
///
/// - parameter db: A database connection.
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Fetched] {
return try Fetched.fetchAll(db, self)
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
}
/// The first fetched record.
///
/// let request: ... // Some TypedRequest that fetches Person
/// let person = try request.fetchOne(db) // Person?
/// let request: ... // Some TypedRequest that fetches Player
/// let player = try request.fetchOne(db) // Player?
///
/// - parameter db: A database connection.
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Fetched? {
return try Fetched.fetchOne(db, self)
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
}
}
extension TypedRequest where Fetched: DatabaseValueConvertible {
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
// MARK: Fetching Values
/// A cursor over fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String>
/// let strings = try request.fetchCursor(db) // Cursor of String
/// while let string = try strings.next() { // String
/// ...
/// }
@@ -224,8 +339,8 @@ extension TypedRequest where Fetched: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Fetched> {
return try Fetched.fetchCursor(db, self)
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched values.
@@ -236,8 +351,8 @@ extension TypedRequest where Fetched: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Fetched] {
return try Fetched.fetchAll(db, self)
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
}
/// The first fetched value.
@@ -251,19 +366,19 @@ extension TypedRequest where Fetched: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Fetched? {
return try Fetched.fetchOne(db, self)
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
}
}
extension TypedRequest where Fetched: DatabaseValueConvertible & StatementColumnConvertible {
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching Values
/// A cursor over fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String>
/// let strings = try request.fetchCursor(db) // Cursor of String
/// while let string = try strings.next() { // String
/// ...
/// }
@@ -276,8 +391,8 @@ extension TypedRequest where Fetched: DatabaseValueConvertible & StatementColumn
/// - parameter db: A database connection.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Fetched> {
return try Fetched.fetchCursor(db, self)
public func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched values.
@@ -288,8 +403,8 @@ extension TypedRequest where Fetched: DatabaseValueConvertible & StatementColumn
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Fetched] {
return try Fetched.fetchAll(db, self)
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
}
/// The first fetched value.
@@ -303,29 +418,19 @@ extension TypedRequest where Fetched: DatabaseValueConvertible & StatementColumn
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Fetched? {
return try Fetched.fetchOne(db, self)
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
}
}
/// This protocol is an implementation detail of GRDB. Don't use it.
public protocol _OptionalFetchable {
associatedtype _Wrapped
}
/// This conformance is an implementation detail of GRDB. Don't rely on it.
extension Optional : _OptionalFetchable {
public typealias _Wrapped = Wrapped
}
extension TypedRequest where Fetched: _OptionalFetchable, Fetched._Wrapped: DatabaseValueConvertible {
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
// MARK: Fetching Optional values
/// A cursor over fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String?>
/// let strings = try request.fetchCursor(db) // Cursor of String?
/// while let string = try strings.next() { // String?
/// ...
/// }
@@ -338,8 +443,8 @@ extension TypedRequest where Fetched: _OptionalFetchable, Fetched._Wrapped: Data
/// - parameter db: A database connection.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Fetched._Wrapped?> {
return try Optional<Fetched._Wrapped>.fetchCursor(db, self)
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
}
/// An array of fetched optional values.
@@ -350,22 +455,59 @@ extension TypedRequest where Fetched: _OptionalFetchable, Fetched._Wrapped: Data
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Fetched._Wrapped?] {
return try Optional<Fetched._Wrapped>.fetchAll(db, self)
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
}
}
extension TypedRequest where Fetched: Row {
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching Optional values
/// A cursor over fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchCursor(db) // Cursor of String?
/// while let string = try strings.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameter db: A database connection.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
}
/// An array of fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let strings = try request.fetchAll(db) // [String?]
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
}
}
extension TypedRequest where RowDecoder: Row {
// MARK: Fetching Rows
/// A cursor over fetched rows.
///
/// let request: ... // Some TypedRequest that fetches Row
/// let rows = try request.fetchCursor(db) // DatabaseCursor<Row>
/// let rows = try request.fetchCursor(db) // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
@@ -384,7 +526,7 @@ extension TypedRequest where Fetched: Row {
/// - parameter db: A database connection.
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row> {
public func fetchCursor(_ db: Database) throws -> RowCursor {
return try Row.fetchCursor(db, self)
}
+143 -118
View File
@@ -1,26 +1,15 @@
import Foundation
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A database row.
public final class Row {
/// The number of columns in the row.
public let count: Int
// MARK: - Building rows
/// Creates an empty row.
@@ -43,10 +32,10 @@ public final class Row {
guard let columnName = key as? String else {
return nil
}
guard let databaseValue = DatabaseValue(value: value) else {
guard let dbValue = DatabaseValue(value: value) else {
return nil
}
initDictionary[columnName] = databaseValue
initDictionary[columnName] = dbValue
}
self.init(initDictionary)
}
@@ -60,11 +49,11 @@ public final class Row {
return impl.copy(self)
}
// MARK: - Not Public
let impl: RowImpl
/// Returns true if and only if the row was fetched from a database.
var isFetched: Bool {
return impl.isFetched
}
@@ -73,7 +62,7 @@ public final class Row {
/// a statement:
///
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let persons = try Person.fetchAll(db, "SELECT ...")
/// let players = try Player.fetchAll(db, "SELECT ...")
///
/// This row keeps an unmanaged reference to the statement, and a handle to
/// the sqlite statement, so that we avoid many retain/release invocations.
@@ -97,6 +86,7 @@ public final class Row {
self.statementRef = statementRef
self.sqliteStatement = statement.sqliteStatement
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statementRef: statementRef)
self.count = Int(sqlite3_column_count(sqliteStatement))
}
/// Creates a row that contain a copy of the current state of the
@@ -109,17 +99,9 @@ public final class Row {
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames))
}
/// Creates a row from the *current state* of the SQLite statement.
///
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
/// the values from the SQLite statement so that further iteration of the
/// statement does not modify the row.
convenience init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, columnNames: [String]) {
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: columnNames))
}
init(impl: RowImpl) {
self.impl = impl
self.count = impl.count
self.statementRef = nil
self.sqliteStatement = nil
}
@@ -154,9 +136,9 @@ extension Row {
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
public func value(atIndex index: Int) -> DatabaseValueConvertible? {
public subscript(_ index: Int) -> DatabaseValueConvertible? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atUncheckedIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).storage.value
}
/// Returns the value at given index, converted to the requested type.
@@ -167,9 +149,9 @@ extension Row {
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
/// value is converted to the requested type `Value`. Should this conversion
/// fail, a fatal error is raised.
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? {
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atUncheckedIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given index, converted to the requested type.
@@ -184,12 +166,12 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(atIndex index: Int) -> Value? {
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard let sqliteStatement = sqliteStatement else {
return impl.databaseValue(atUncheckedIndex: index).value()
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
}
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given index, converted to the requested type.
@@ -199,9 +181,9 @@ extension Row {
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value {
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atUncheckedIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given index, converted to the requested type.
@@ -215,12 +197,12 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(atIndex index: Int) -> Value {
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard let sqliteStatement = sqliteStatement else {
return impl.databaseValue(atUncheckedIndex: index).value()
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
}
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns Int64, Double, String, Data or nil, depending on the value
@@ -230,18 +212,18 @@ extension Row {
/// the same name, the leftmost column is considered.
///
/// The result is nil if the row does not contain the column.
public func value(named columnName: String) -> DatabaseValueConvertible? {
public subscript(_ columnName: String) -> DatabaseValueConvertible? {
// IMPLEMENTATION NOTE
// This method has a single know use case: checking if the value is nil,
// as in:
//
// if row.value(named: "foo") != nil { ... }
// if row["foo"] != nil { ... }
//
// Without this method, the code above would not compile.
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.databaseValue(atUncheckedIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).storage.value
}
/// Returns the value at given column, converted to the requested type.
@@ -252,11 +234,11 @@ extension Row {
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. Otherwise the SQLite value is converted to the requested type
/// `Value`. Should this conversion fail, a fatal error is raised.
public func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value? {
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value? {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.databaseValue(atUncheckedIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given column, converted to the requested type.
@@ -271,14 +253,14 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(named columnName: String) -> Value? {
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
guard let sqliteStatement = sqliteStatement else {
return impl.databaseValue(atUncheckedIndex: index).value()
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
}
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given column, converted to the requested type.
@@ -290,12 +272,12 @@ extension Row {
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
public func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value {
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
guard let index = impl.index(ofColumn: columnName) else {
// Programmer error
fatalError("no such column: \(columnName)")
}
return impl.databaseValue(atUncheckedIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given column, converted to the requested type.
@@ -311,15 +293,15 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(named columnName: String) -> Value {
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)")
}
guard let sqliteStatement = sqliteStatement else {
return impl.databaseValue(atUncheckedIndex: index).value()
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
}
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns Int64, Double, String, NSData or nil, depending on the value
@@ -329,8 +311,8 @@ extension Row {
/// the same name, the leftmost column is considered.
///
/// The result is nil if the row does not contain the column.
public func value(_ column: Column) -> DatabaseValueConvertible? {
return value(named: column.name)
public subscript(_ column: Column) -> DatabaseValueConvertible? {
return self[column.name]
}
/// Returns the value at given column, converted to the requested type.
@@ -341,8 +323,8 @@ extension Row {
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. Otherwise the SQLite value is converted to the requested type
/// `Value`. Should this conversion fail, a fatal error is raised.
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value? {
return value(named: column.name)
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value? {
return self[column.name]
}
/// Returns the value at given column, converted to the requested type.
@@ -357,8 +339,8 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value? {
return value(named: column.name)
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value? {
return self[column.name]
}
/// Returns the value at given column, converted to the requested type.
@@ -370,8 +352,8 @@ extension Row {
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value {
return value(named: column.name)
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value {
return self[column.name]
}
/// Returns the value at given column, converted to the requested type.
@@ -387,8 +369,8 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value {
return value(named: column.name)
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value {
return self[column.name]
}
/// Returns the optional Data at given index.
@@ -456,20 +438,21 @@ extension Row {
extension Row {
// MARK: - Helpers
fileprivate static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int, in sqliteStatement: SQLiteStatement) -> Value? {
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
@inline(__always)
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int32, in sqliteStatement: SQLiteStatement) -> Value? {
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
return nil
}
return Value.init(sqliteStatement: sqliteStatement, index: Int32(index))
return Value.init(sqliteStatement: sqliteStatement, index: index)
}
fileprivate static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int, in sqliteStatement: SQLiteStatement) -> Value {
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
@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: Int32(index))
return Value.init(sqliteStatement: sqliteStatement, index: index)
}
}
@@ -495,16 +478,49 @@ extension Row {
///
/// // Scoped rows:
/// if let fooRow = row.scoped(on: "foo") {
/// fooRow.value(named: "value") // "foo"
/// fooRow["value"] // "foo"
/// }
/// if let barRow = row.scopeed(on: "bar") {
/// barRow.value(named: "value") // "bar"
/// barRow["value"] // "bar"
/// }
public func scoped(on name: String) -> Row? {
return impl.scoped(on: name)
}
}
/// A cursor of database rows. For example:
///
/// try dbQueue.inDatabase { db in
/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM players")
/// }
public final class RowCursor : Cursor {
public let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let row: Row // Reused for performance
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
}
public func next() throws -> Row? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
return row
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
extension Row {
// MARK: - Fetching From SelectStatement
@@ -512,10 +528,10 @@ extension Row {
/// Returns a cursor over rows fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let rows = try Row.fetchCursor(statement) // DatabaseCursor<Row>
/// let rows = try Row.fetchCursor(statement) // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
@@ -538,10 +554,8 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
// Reuse a single mutable row for performance
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
return statement.fetchCursor(arguments: arguments) { row }
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
return try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of rows fetched from a prepared statement.
@@ -573,7 +587,7 @@ extension Row {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
// The cursor reuses a single mutable row. Return an immutable copy.
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next().flatMap { $0.copy() }
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next().map { $0.copy() }
}
}
@@ -585,11 +599,11 @@ extension Row {
///
/// let idColumn = Column("id")
/// let nameColumn = Column("name")
/// let request = Person.select(idColumn, nameColumn)
/// let rows = try Row.fetchCursor(db) // DatabaseCursor<Row>
/// let request = Player.select(idColumn, nameColumn)
/// let rows = try Row.fetchCursor(db) // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
@@ -610,7 +624,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Row> {
public static func fetchCursor(_ db: Database, _ request: Request) throws -> RowCursor {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
@@ -619,7 +633,7 @@ extension Row {
///
/// let idColumn = Column("id")
/// let nameColumn = Column("name")
/// let request = Person.select(idColumn, nameColumn)
/// let request = Player.select(idColumn, nameColumn)
/// let rows = try Row.fetchAll(db, request)
///
/// - parameter db: A database connection.
@@ -633,7 +647,7 @@ extension Row {
///
/// let idColumn = Column("id")
/// let nameColumn = Column("name")
/// let request = Person.select(idColumn, nameColumn)
/// let request = Player.select(idColumn, nameColumn)
/// let row = try Row.fetchOne(db, request)
///
/// - parameter db: A database connection.
@@ -650,10 +664,10 @@ extension Row {
/// Returns a cursor over rows fetched from an SQL query.
///
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM persons") // DatabaseCursor<Row>
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM players") // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
@@ -676,7 +690,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
@@ -728,11 +742,6 @@ extension Row : Collection {
// MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs
/// The number of columns in the row.
public var count: Int {
return impl.count
}
/// The index of the first (ColumnName, DatabaseValue) pair.
public var startIndex: RowIndex {
return Index(0)
@@ -766,11 +775,12 @@ extension Row : Collection {
}
}
/// Row adopts Equatable.
extension Row : Equatable {
/// 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.
public static func ==(lhs: Row, rhs: Row) -> Bool {
public static func == (lhs: Row, rhs: Row) -> Bool {
if lhs === rhs {
return true
}
@@ -809,13 +819,22 @@ extension Row : Equatable {
}
}
/// Row adopts Hashable.
extension Row : Hashable {
/// The hash value
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 {
/// A textual representation of `self`.
public var description: String {
return "<Row"
+ map { (column, dbv) in
" \(column):\(dbv)"
+ map { (column, dbValue) in
" \(column):\(dbValue)"
}.joined(separator: "")
+ ">"
}
@@ -824,16 +843,18 @@ extension Row: CustomStringConvertible {
// MARK: - RowIndex
/// Indexes to (columnName, databaseValue) pairs in a database row.
/// Indexes to (columnName, dbValue) pairs in a database row.
public struct RowIndex : Comparable {
let index: Int
init(_ index: Int) { self.index = index }
public static func ==(lhs: RowIndex, rhs: RowIndex) -> Bool {
/// Equality operator
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index == rhs.index
}
public static func <(lhs: RowIndex, rhs: RowIndex) -> Bool {
// Comparison operator
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index < rhs.index
}
}
@@ -878,7 +899,7 @@ private struct ArrayRowImpl : RowImpl {
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
return databaseValue(atUncheckedIndex: index).value()
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
@@ -912,12 +933,12 @@ private struct ArrayRowImpl : RowImpl {
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
private struct StatementCopyRowImpl : RowImpl {
let databaseValues: ContiguousArray<DatabaseValue>
let dbValues: ContiguousArray<DatabaseValue>
let columnNames: [String]
init(sqliteStatement: SQLiteStatement, columnNames: [String]) {
let sqliteStatement = sqliteStatement
self.databaseValues = ContiguousArray((0..<sqlite3_column_count(sqliteStatement)).map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) } as [DatabaseValue])
self.dbValues = ContiguousArray((0..<sqlite3_column_count(sqliteStatement)).map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) } as [DatabaseValue])
self.columnNames = columnNames
}
@@ -930,11 +951,11 @@ private struct StatementCopyRowImpl : RowImpl {
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
return databaseValue(atUncheckedIndex: index).value()
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return databaseValues[index]
return dbValues[index]
}
func columnName(atUncheckedIndex index: Int) -> String {
@@ -971,9 +992,13 @@ private struct StatementRowImpl : RowImpl {
init(sqliteStatement: SQLiteStatement, statementRef: Unmanaged<SelectStatement>) {
self.statementRef = statementRef
self.sqliteStatement = sqliteStatement
// Optimize row.value(named: "...")
// Optimize row["..."]
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement)).map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: lowercaseColumnNames.enumerated().map { ($1, $0) }.reversed())
self.lowercaseColumnIndexes = Dictionary(
lowercaseColumnNames
.enumerated()
.map { ($0.element, $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}
var count: Int {
@@ -989,7 +1014,7 @@ private struct StatementRowImpl : RowImpl {
return nil
}
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
return nil
return Data()
}
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
+47 -36
View File
@@ -1,23 +1,11 @@
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#endif
import Foundation
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// LayoutedColumnMapping is a type that supports the RowAdapter protocol.
public struct LayoutedColumnMapping {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// An array of (baseIndex, mappedName) pairs, where baseIndex is the index
/// of a column in a base row, and mappedName the mapped name of
/// that column.
@@ -26,7 +14,9 @@ public struct LayoutedColumnMapping {
/// A cache for layoutIndex(ofColumn:)
let lowercaseColumnIndexes: [String: Int] // [mappedColumn: layoutColumnIndex]
/// Creates an LayoutedColumnMapping from an array of (baseIndex, mappedName)
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates a LayoutedColumnMapping from an array of (baseIndex, mappedName)
/// pairs. In each pair:
///
/// - baseIndex is the index of a column in a base row
@@ -49,10 +39,11 @@ public struct LayoutedColumnMapping {
/// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) {
self.layoutColumns = Array(layoutColumns)
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: layoutColumns
.enumerated()
.map { ($1.1.lowercased(), $0) }
.reversed()) // reversed() so that the the dictionary caches leftmost indexes
self.lowercaseColumnIndexes = Dictionary(
layoutColumns
.enumerated()
.map { ($0.element.1.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}
func baseColumnIndex(atMappingIndex index: Int) -> Int {
@@ -66,20 +57,26 @@ public struct LayoutedColumnMapping {
/// LayoutedColumnMapping adopts LayoutedRowAdapter
extension LayoutedColumnMapping : LayoutedRowAdapter {
/// Part of the LayoutedRowAdapter protocol; returns self.
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns self.
public var mapping: LayoutedColumnMapping {
return self
}
/// Part of the LayoutedRowAdapter protocol; returns the empty dictionary.
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the empty dictionary.
public var scopes: [String: LayoutedRowAdapter] {
return [:]
}
}
extension LayoutedColumnMapping : RowLayout {
/// Part of the RowLayout protocol; returns the index of the leftmost column
/// named `name`, in a case-insensitive way.
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the index of the leftmost column named `name`, in a
/// case-insensitive way.
public func layoutIndex(ofColumn name: String) -> Int? {
if let index = lowercaseColumnIndexes[name] {
return index
@@ -88,38 +85,50 @@ extension LayoutedColumnMapping : RowLayout {
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// LayoutedRowAdapter is a protocol that supports the RowAdapter protocol.
///
/// GRBD ships with a ready-made type that adopts this protocol:
/// LayoutedColumnMapping.
public protocol LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// A LayoutedColumnMapping that defines how to map a column name to a
/// column in a base row.
var mapping: LayoutedColumnMapping { get }
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The layouted row adapters for each scope.
var scopes: [String: LayoutedRowAdapter] { get }
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// RowLayout is a protocol that supports the RowAdapter protocol. It describes
/// a layout of a base row.
public protocol RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// An array of (baseIndex, name) pairs, where baseIndex is the index
/// of a column in a base row, and name the name of that column.
var layoutColumns: [(Int, String)] { get }
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the index of the leftmost column named `name`, in a
/// case-insensitive way.
func layoutIndex(ofColumn name: String) -> Int?
}
extension SelectStatement : RowLayout {
/// Part of the RowLayout protocol.
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var layoutColumns: [(Int, String)] {
return Array(columnNames.enumerated())
}
/// Part of the RowLayout protocol.
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func layoutIndex(ofColumn name: String) -> Int? {
return index(ofColumn: name)
}
@@ -144,6 +153,8 @@ extension SelectStatement : RowLayout {
/// try Row.fetchOne(db, sql, adapter: adapter)
public protocol RowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// You never call this method directly. It is called for you whenever an
/// adapter has to be applied.
///
@@ -202,13 +213,13 @@ public struct ColumnMapping : RowAdapter {
self.mapping = mapping
}
/// Part of the RowAdapter protocol
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
let layoutColumns = try mapping
.map { (mappedColumn, baseColumn) -> (Int, String) in
guard let index = layout.layoutIndex(ofColumn: baseColumn) else {
let columnNames = layout.layoutColumns.map { $0.1 }
throw DatabaseError(code: SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).")
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).")
}
let baseIndex = layout.layoutColumns[index].0
return (baseIndex, mappedColumn)
@@ -238,7 +249,7 @@ public struct SuffixRowAdapter : RowAdapter {
self.index = index
}
/// Part of the RowAdapter protocol
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
}
@@ -267,7 +278,7 @@ public struct RangeRowAdapter : RowAdapter {
self.range = range.lowerBound..<(range.upperBound + 1)
}
/// Part of the RowAdapter protocol
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
}
@@ -290,10 +301,10 @@ public struct RangeRowAdapter : RowAdapter {
///
/// // Scoped rows:
/// if let fooRow = row.scoped(on: "foo") {
/// fooRow.value(named: "value") // "foo"
/// fooRow["value"] // "foo"
/// }
/// if let barRow = row.scopeed(on: "bar") {
/// barRow.value(named: "value") // "bar"
/// barRow["value"] // "bar"
/// }
public struct ScopeAdapter : RowAdapter {
@@ -317,7 +328,7 @@ public struct ScopeAdapter : RowAdapter {
self.scopes = scopes
}
/// Part of the RowAdapter protocol
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout)
var layoutedScopes = layoutedAdapter.scopes
@@ -380,7 +391,7 @@ struct AdapterRowImpl : RowImpl {
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return base.value(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
return base[mapping.baseColumnIndex(atMappingIndex: index)]
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
+2
View File
@@ -1,3 +1,5 @@
import Dispatch
/// SchedulingWatchdog makes sure that databases connections are used on correct
/// dispatch queues, and warns the user with a fatal error whenever she misuses
/// a database connection.
+16 -3
View File
@@ -10,6 +10,9 @@ final class SerializedDatabase {
return db.configuration
}
/// The path to the database file
var path: String
/// The dispatch queue
private let queue: DispatchQueue
@@ -36,6 +39,7 @@ final class SerializedDatabase {
db = try Database(path: path, configuration: config, schemaCache: schemaCache)
queue = SchedulingWatchdog.makeSerializedQueue(allowingDatabase: db)
self.path = path
try queue.sync {
try db.setup()
}
@@ -48,8 +52,8 @@ final class SerializedDatabase {
}
}
/// Synchronously executes a block the serialized dispatch queue, and returns
/// its result.
/// Synchronously executes a block the serialized dispatch queue, and
/// returns its result.
///
/// This method is *not* reentrant.
func sync<T>(_ block: (Database) throws -> T) rethrows -> T {
@@ -92,7 +96,11 @@ final class SerializedDatabase {
}
}
private func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
/// Synchronously executes a block the serialized dispatch queue, and
/// returns its result.
///
/// This method is reentrant.
func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
// Three different cases:
//
// 1. A database is invoked from some queue like the main queue:
@@ -141,6 +149,11 @@ final class SerializedDatabase {
}
}
/// Returns true if any only if the current dispatch queue is valid.
var onValidQueue: Bool {
return SchedulingWatchdog.allows(db)
}
/// Executes the block in the current queue.
///
/// - precondition: the current dispatch queue is valid.
+254 -133
View File
@@ -1,21 +1,8 @@
import Foundation
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -32,7 +19,9 @@ public class Statement {
/// The SQL query
public var sql: String {
// trim white space and semicolumn for homogeneous output
return String(cString: sqlite3_sql(sqliteStatement))
.trimmingCharacters(in: CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines))
}
/// The database
@@ -43,7 +32,14 @@ public class Statement {
self.sqliteStatement = sqliteStatement
}
fileprivate init(database: Database, sql: String, observer: StatementCompilationObserver) throws {
/// Creates a prepared statement.
///
/// - parameter database: A database connection.
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - parameter observer: A StatementCompilationObserver
fileprivate init(database: Database, sql: String, prepFlags: Int32, observer: StatementCompilationObserver) throws {
SchedulingWatchdog.preconditionValidQueue(database)
observer.start()
@@ -56,18 +52,23 @@ public class Statement {
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var sqlEnd: UnsafePointer<Int8>? = nil
code = sqlite3_prepare_v2(database.sqliteConnection, sqlStart, -1, &sqliteStatement, &sqlEnd)
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE
code = sqlite3_prepare_v3(database.sqliteConnection, sqlStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, &sqlEnd)
#else
code = sqlite3_prepare_v2(database.sqliteConnection, sqlStart, -1, &sqliteStatement, &sqlEnd)
#endif
let remainingData = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: sqlEnd!), count: sqlStart + sqlCodeUnits.count - sqlEnd! - 1, deallocator: .none)
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
}
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)
}
guard remainingSQL.isEmpty else {
sqlite3_finalize(sqliteStatement)
throw DatabaseError(code: SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
}
self.database = database
@@ -86,7 +87,7 @@ public class Statement {
// throwing any error.
let code = sqlite3_reset(sqliteStatement)
guard code == SQLITE_OK else {
fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description)
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
}
}
@@ -138,11 +139,11 @@ public class Statement {
var valuesIterator = arguments.values.makeIterator()
for (index, argumentName) in sqliteArgumentNames.enumerated() {
if let argumentName = argumentName, let value = arguments.namedValues[argumentName] {
bind(databaseValue: value, at: index)
bind(value, at: index)
} else if let value = valuesIterator.next() {
bind(databaseValue: value, at: index)
bind(value, at: index)
} else {
bind(databaseValue: .null, at: index)
bind(.null, at: index)
}
}
}
@@ -157,15 +158,15 @@ public class Statement {
// Apply
reset()
clearBindings()
for (index, databaseValue) in bindings.enumerated() {
bind(databaseValue: databaseValue, at: index)
for (index, dbValue) in bindings.enumerated() {
bind(dbValue, at: index)
}
}
// 0-based index
private func bind(databaseValue: DatabaseValue, at index: Int) {
private func bind(_ dbValue: DatabaseValue, at index: Int) {
let code: Int32
switch databaseValue.storage {
switch dbValue.storage {
case .null:
code = sqlite3_bind_null(sqliteStatement, Int32(index + 1))
case .int64(let int64):
@@ -183,7 +184,7 @@ public class Statement {
// It looks like sqlite3_bind_xxx() functions do not access the file system.
// They should thus succeed, unless a GRDB bug: there is no point throwing any error.
guard code == SQLITE_OK else {
fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description)
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
}
}
@@ -194,17 +195,26 @@ public class Statement {
// no point throwing any error.
let code = sqlite3_clear_bindings(sqliteStatement)
guard code == SQLITE_OK else {
fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description)
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
}
}
fileprivate func prepare(withArguments arguments: StatementArguments?) throws {
fileprivate func prepare(withArguments arguments: StatementArguments?) {
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
if let arguments = arguments {
try setArgumentsWithValidation(arguments)
try! setArgumentsWithValidation(arguments)
} else if argumentsNeedValidation {
try validate(arguments: self.arguments)
try! validate(arguments: self.arguments)
}
}
/// Utility function for cursors
func cursorReset(arguments: StatementArguments? = nil) {
SchedulingWatchdog.preconditionValidQueue(database)
prepare(withArguments: arguments)
reset()
}
}
@@ -215,17 +225,24 @@ public class Statement {
/// You create SelectStatement with the Database.makeSelectStatement() method:
///
/// try dbQueue.inDatabase { db in
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement {
private(set) var selectionInfo: SelectionInfo
/// Information about the table and columns read by a SelectStatement
public private(set) var selectionInfo: SelectionInfo
init(database: Database, sql: String) throws {
/// Creates a prepared statement.
///
/// - parameter database: A database connection.
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
init(database: Database, sql: String, prepFlags: Int32) throws {
self.selectionInfo = SelectionInfo()
let observer = StatementCompilationObserver(database)
try super.init(database: database, sql: sql, observer: observer)
try super.init(database: database, sql: sql, prepFlags: prepFlags, observer: observer)
Database.preconditionValidSelectStatement(sql: sql, observer: observer)
self.selectionInfo = observer.selectionInfo
}
@@ -243,90 +260,116 @@ public final class SelectStatement : Statement {
/// Cache for indexOfColumn(). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
return Dictionary(keyValueSequence: self.columnNames.enumerated().map { ($1.lowercased(), $0) }.reversed())
return Dictionary(
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}()
/// Returns the index of the leftmost column named `name`, in a
/// case-insensitive way.
func index(ofColumn name: String) -> Int? {
public func index(ofColumn name: String) -> Int? {
return columnIndexes[name.lowercased()]
}
/// Creates a DatabaseCursor
func fetchCursor<Element>(arguments: StatementArguments? = nil, element: @escaping () throws -> Element) -> DatabaseCursor<Element> {
// Check that cursor is built on a valid queue.
SchedulingWatchdog.preconditionValidQueue(database, "Database was not used on the correct thread.")
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
try! prepare(withArguments: arguments)
reset()
return DatabaseCursor(statement: self, element: element)
}
/// Creates a cursor whose results are ignored
func fetchCursor(arguments: StatementArguments? = nil) -> DatabaseCursor<Void> {
return fetchCursor(arguments: arguments) { }
/// Creates a cursor over the statement. This cursor does not produce any
/// value, and is only intended to give access to the sqlite3_step()
/// low-level function.
func cursor(arguments: StatementArguments? = nil) -> StatementCursor {
return StatementCursor(statement: self, arguments: arguments)
}
/// Allows inspection of table and columns read by a SelectStatement
struct SelectionInfo {
/// Information about the table and columns read by a SelectStatement
public struct SelectionInfo : CustomStringConvertible {
mutating func insert(allColumnsOfTable table: String) {
tables.insert(table)
}
mutating func insert(column: String, ofTable table: String) {
if selection[table] != nil {
selection[table]!.insert(column)
} else {
selection[table] = [column]
}
columns[table, default: []].insert(column)
}
/// Returns true if isUnknown is true
func contains(anyColumnFrom table: String) -> Bool {
return selection.index(forKey: table) != nil
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 {
return !(selection[table]?.isDisjoint(with: columns) ?? true)
if isUnknown { return true }
return tables.contains(table) || !(self.columns[table]?.isDisjoint(with: columns) ?? true)
}
private var selection: [String: Set<String>] = [:] // [TableName: Set<ColumnName>]
init() {
self.init(isUnknown: false)
}
static func unknown() -> SelectionInfo {
return self.init(isUnknown: true)
}
/// If true, selection is unknown
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> = []
private init(isUnknown: Bool) {
self.isUnknown = isUnknown
}
/// A textual representation of `self`.
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: ",")
}
}
}
/// A cursor on a statement
public final class DatabaseCursor<Element> : Cursor {
fileprivate let statement: SelectStatement
/// A cursor that iterates a database statement without producing any value.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let statement = db.makeSelectStatement("SELECT * FROM players")
/// let cursor: StatementCursor = statement.cursor()
/// }
public final class StatementCursor: Cursor {
public let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let element: () throws -> Element?
private var done = false
// Fileprivate so that only SelectStatement can instantiate a database cursor
fileprivate init(statement: SelectStatement, element: @escaping () throws -> Element?) {
// Use SelectStatement.cursor() instead
fileprivate init(statement: SelectStatement, arguments: StatementArguments? = nil) {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
self.element = element
statement.cursorReset(arguments: arguments)
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists. Once nil has been returned, all subsequent calls return nil.
///
/// let rows = try Row.fetchCursor(db, "SELECT ...") // DatabaseCursor<Row>
/// while let row = try rows.next() { // Row
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// }
public func next() throws -> Element? {
if done {
return nil
}
public func next() throws -> Void? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
return try element()
case let errorCode:
throw DatabaseError(code: errorCode, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
return .some(())
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
@@ -339,7 +382,7 @@ public final class DatabaseCursor<Element> : Cursor {
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
///
/// try dbQueue.inTransaction { db in
/// let statement = try db.makeUpdateStatement("INSERT INTO persons (name) VALUES (?)")
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
@@ -375,12 +418,18 @@ public final class UpdateStatement : Statement {
super.init(database: database, sqliteStatement: sqliteStatement)
}
init(database: Database, sql: String) throws {
/// Creates a prepared statement.
///
/// - parameter database: A database connection.
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
init(database: Database, sql: String, prepFlags: Int32) throws {
self.invalidatesDatabaseSchemaCache = false
self.databaseEventKinds = []
let observer = StatementCompilationObserver(database)
try super.init(database: database, sql: sql, observer: observer)
try super.init(database: database, sql: sql, prepFlags: prepFlags, observer: observer)
self.invalidatesDatabaseSchemaCache = observer.invalidatesDatabaseSchemaCache
self.transactionStatementInfo = observer.transactionStatementInfo
self.databaseEventKinds = observer.databaseEventKinds
@@ -392,11 +441,7 @@ public final class UpdateStatement : Statement {
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(arguments: StatementArguments? = nil) throws {
SchedulingWatchdog.preconditionValidQueue(database)
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
try! prepare(withArguments: arguments)
prepare(withArguments: arguments)
reset()
database.updateStatementWillExecute(self)
@@ -425,13 +470,13 @@ public final class UpdateStatement : Statement {
database.updateStatementDidExecute(self)
return
case let errorCode:
case let code:
// Failure
//
// Let database rethrow eventual transaction observer error:
try database.updateStatementDidFail(self)
throw DatabaseError(code: errorCode, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
}
}
}
@@ -440,8 +485,8 @@ public final class UpdateStatement : Statement {
// MARK: - StatementArguments
/// StatementArguments provide values to SQLite statements expressed as
/// placeholders in raw SQL queries.
/// StatementArguments provide values to argument placeholders in raw
/// SQL queries.
///
/// Placeholders can take several forms (see https://www.sqlite.org/lang_expr.html#varparam
/// for more information):
@@ -471,13 +516,13 @@ public final class UpdateStatement : Statement {
/// To fill named arguments, feed StatementArguments with a dictionary:
///
/// db.execute(
/// "INSERT ... (:name, :age)",
/// arguments: StatementArguments(["name": "Arthur", "age": 41]))
/// "INSERT ... (:name, :score)",
/// arguments: StatementArguments(["name": "Arthur", "score": 41]))
///
/// // Dictionary literals are automatically converted:
/// db.execute(
/// "INSERT ... (:name, :age)",
/// arguments: ["name": "Arthur", "age": 41])
/// "INSERT ... (:name, :score)",
/// arguments: ["name": "Arthur", "score": 41])
///
/// ## Concatenating Arguments
///
@@ -518,43 +563,48 @@ public struct StatementArguments {
}
// MARK: Empty Arguments
/// Creates empty StatementArguments.
init() {
}
// MARK: Positional Arguments
/// Initializes arguments from a sequence of optional values.
/// Creates statement arguments from a sequence of optional values.
///
/// let values: [DatabaseValueConvertible?] = ["foo", 1, nil]
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
/// - returns: A StatementArguments.
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Iterator.Element == DatabaseValueConvertible? {
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == DatabaseValueConvertible? {
values = sequence.map { $0?.databaseValue ?? .null }
}
/// Initializes arguments from a sequence of optional values.
/// Creates statement arguments from a sequence of optional values.
///
/// let values: [String] = ["foo", "bar"]
/// db.execute("INSERT ... (?,?)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
/// - returns: A StatementArguments.
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Iterator.Element: DatabaseValueConvertible {
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible {
values = sequence.map { $0.databaseValue }
}
/// Initializes arguments from [Any].
///
/// The result is nil unless all objects adopt DatabaseValueConvertible.
/// Creates statement arguments from any array. The result is nil unless all
/// array elements adopt DatabaseValueConvertible.
///
/// - parameter array: An array
/// - returns: A StatementArguments.
public init?(_ array: [Any]) {
var values = [DatabaseValueConvertible?]()
for value in array {
guard let databaseValue = DatabaseValue(value: value) else {
guard let dbValue = DatabaseValue(value: value) else {
return nil
}
values.append(databaseValue)
values.append(dbValue)
}
self.init(values)
}
@@ -562,8 +612,8 @@ public struct StatementArguments {
// MARK: Named Arguments
/// Initializes arguments from a sequence of (key, value) dictionary, such as
/// a dictionary.
/// Creates statement arguments from a sequence of (key, value) dictionary,
/// such as a dictionary.
///
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
@@ -571,22 +621,22 @@ public struct StatementArguments {
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
namedValues = Dictionary(keys: dictionary.keys) { dictionary[$0]!?.databaseValue ?? .null }
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
}
/// Initializes arguments from a sequence of (key, value) pairs, such as
/// a dictionary.
/// Creates statement arguments from a sequence of (key, value) pairs, such
/// as a dictionary.
///
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Iterator.Element == (String, DatabaseValueConvertible?) {
namedValues = Dictionary(keyValueSequence: sequence.map { ($0, $1?.databaseValue ?? .null) })
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == (String, DatabaseValueConvertible?) {
namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) })
}
/// Initializes arguments from [AnyHashable: Any].
/// Creates statement arguments from [AnyHashable: Any].
///
/// The result is nil unless all dictionary keys are strings, and values
/// adopt DatabaseValueConvertible.
@@ -599,10 +649,10 @@ public struct StatementArguments {
guard let columnName = key as? String else {
return nil
}
guard let databaseValue = DatabaseValue(value: value) else {
guard let dbValue = DatabaseValue(value: value) else {
return nil
}
initDictionary[columnName] = databaseValue
initDictionary[columnName] = dbValue
}
self.init(initDictionary)
}
@@ -767,30 +817,27 @@ public struct StatementArguments {
var values: [DatabaseValue] = []
var namedValues: [String: DatabaseValue] = [:]
init() {
}
mutating func consume(_ statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
let initialValuesCount = values.count
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
if let argumentName = argumentName {
if let databaseValue = namedValues[argumentName] {
return databaseValue
if let dbValue = namedValues[argumentName] {
return dbValue
} else if values.isEmpty {
throw DatabaseError(code: SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil)
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil)
} else {
return values.removeFirst()
}
} else {
if values.isEmpty {
throw DatabaseError(code: SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
} else {
return values.removeFirst()
}
}
}
if !allowingRemainingValues && !values.isEmpty {
throw DatabaseError(code: SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
}
return bindings
}
@@ -808,7 +855,7 @@ extension StatementArguments : ExpressibleByArrayLiteral {
extension StatementArguments : ExpressibleByDictionaryLiteral {
/// Returns a StatementArguments from a dictionary literal:
///
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "age": 41])
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
self.init(elements)
}
@@ -824,3 +871,77 @@ extension StatementArguments : CustomStringConvertible {
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
}
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
private var selectStatements: [String: SelectStatement] = [:]
private var updateStatements: [String: UpdateStatement] = [:]
init(database: Database) {
self.db = database
}
mutating func selectStatement(_ sql: String) throws -> SelectStatement {
if let statement = selectStatements[sql] {
return statement
}
#if GRDBCUSTOMSQLITE
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
let statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeSelectStatement(sql)
#endif
selectStatements[sql] = statement
return statement
}
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
if let statement = updateStatements[sql] {
return statement
}
#if GRDBCUSTOMSQLITE
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
let statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeUpdateStatement(sql)
#endif
updateStatements[sql] = statement
return statement
}
mutating func clear() {
updateStatements = [:]
selectStatements = [:]
}
mutating func remove(_ statement: SelectStatement) {
if let index = selectStatements.index(where: { $0.1 === statement }) {
selectStatements.remove(at: index)
}
}
mutating func remove(_ statement: UpdateStatement) {
if let index = updateStatements.index(where: { $0.1 === statement }) {
updateStatements.remove(at: index)
}
}
}
+269 -50
View File
@@ -1,37 +1,46 @@
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// When a type adopts both DatabaseValueConvertible and
/// StatementColumnConvertible, it is granted with faster access to the SQLite
/// database values.
/// The StatementColumnConvertible protocol grants access to the low-level C
/// interface that extracts values from query results:
/// https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
/// improvements.
///
/// To use it, have a value type adopt both StatementColumnConvertible and
/// DatabaseValueConvertible. GRDB will then automatically apply the
/// optimization whenever direct access to SQLite is possible:
///
/// let rows = Row.fetchCursor(db, "SELECT ...")
/// while let row = try rows.next() {
/// let int: Int = row[0] // there
/// }
/// let ints = Int.fetchAll(db, "SELECT ...") // there
/// struct Player {
/// init(row: Row) {
/// name = row["name"] // there
/// score = row["score"] // there
/// }
/// }
///
/// StatementColumnConvertible is already adopted by all Swift integer types,
/// Float, Double, String, and Bool.
public protocol StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
/// Initializes a value from a raw SQLite statement pointer.
///
/// As an example, here is the how Int64 adopts StatementColumnConvertible:
/// For example, here is the how Int64 adopts StatementColumnConvertible:
///
/// extension Int64: StatementColumnConvertible {
/// public init(sqliteStatement: SQLiteStatement, index: Int32) {
/// init(sqliteStatement: SQLiteStatement, index: Int32) {
/// self = sqlite3_column_int64(sqliteStatement, index)
/// }
/// }
///
/// When you implement this method, don't check for NULL.
/// This initializer is never called for NULL database values: don't perform
/// any extra check.
///
/// See https://www.sqlite.org/c3ref/column_blob.html for more information.
///
@@ -41,6 +50,91 @@ public protocol StatementColumnConvertible {
init(sqliteStatement: SQLiteStatement, index: Int32)
}
/// A cursor of database values extracted from a single column.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM players")
/// while let name = names.next() { // String
/// print(name)
/// }
/// }
public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
}
public func next() throws -> Value? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
var error = "could not convert database value NULL to \(Value.self) with statement `\(statement.sql)`"
if !statement.arguments.isEmpty {
error += " arguments \(statement.arguments)"
}
fatalError(error)
}
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
/// A cursor of optional database values extracted from a single column.
/// For example:
///
/// try dbQueue.inDatabase { db in
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM players")
/// while let email = emails.next() { // String?
/// print(email ?? "<NULL>")
/// }
/// }
public final class NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
// We'll read from leftmost column at index 0, unless adapter mangles columns
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
}
public func next() throws -> Value?? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
return .some(nil)
}
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
/// Types that adopt both DatabaseValueConvertible and
/// StatementColumnConvertible can be efficiently initialized from
@@ -55,7 +149,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
/// let names = try String.fetchCursor(statement) // Cursor of String
/// while let name = try names.next() { // String
/// ...
/// }
@@ -71,16 +165,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
// We'll read from leftmost column at index 0, unless adapter mangles columns
let columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
let sqliteStatement = statement.sqliteStatement
return statement.fetchCursor(arguments: arguments) {
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value NULL to \(Self.self)", sql: statement.sql, arguments: arguments)
}
return Self.init(sqliteStatement: sqliteStatement, index: columnIndex)
}
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
return try ColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of values fetched from a prepared statement.
@@ -110,15 +196,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
// We'll read from leftmost column at index 0, unless adapter mangles columns
let columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
let sqliteStatement = statement.sqliteStatement
let cursor = statement.fetchCursor(arguments: arguments) { () -> Self? in
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
return nil
}
return Self.init(sqliteStatement: sqliteStatement, index: columnIndex)
}
// fetchOne returns nil if there is no row, or if there is a row with a null value
let cursor = try NullableColumnCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
return try cursor.next() ?? nil
}
}
@@ -130,8 +209,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a cursor over values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
/// let request = Player.select(nameColumn)
/// let names = try String.fetchCursor(db, request) // Cursor of String
/// while let name = try names.next() { // String
/// ...
/// }
@@ -146,7 +225,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A fetch request.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
public static func fetchCursor(_ db: Database, _ request: Request) throws -> ColumnCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
@@ -154,7 +233,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns an array of values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let request = Player.select(nameColumn)
/// let names = try String.fetchAll(db, request) // [String]
///
/// - parameter db: A database connection.
@@ -170,7 +249,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// extracted from the first row.
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn)
/// let request = Player.select(nameColumn)
/// let name = try String.fetchOne(db, request) // String?
///
/// - parameter db: A database connection.
@@ -187,7 +266,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String>
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
/// while let name = try names.next() { // String
/// ...
/// }
@@ -204,7 +283,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
@@ -238,3 +317,143 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
}
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
///
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching From SelectStatement
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
return try NullableColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let names = try Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching From Request
/// Returns a cursor over optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - requet: A fetch request.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableColumnCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of optional values fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn)
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over optional values fetched from an SQL query.
///
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
}
+3 -3
View File
@@ -8,9 +8,9 @@ extension CGFloat : DatabaseValueConvertible {
return Double(self).databaseValue
}
/// Returns a CGFloat initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> CGFloat? {
guard let double = Double.fromDatabaseValue(databaseValue) else {
/// Returns a CGFloat initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CGFloat? {
guard let double = Double.fromDatabaseValue(dbValue) else {
return nil
}
return CGFloat(double)
+18 -8
View File
@@ -1,20 +1,30 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Data is convertible to and from DatabaseValue.
extension Data : DatabaseValueConvertible {
extension Data : DatabaseValueConvertible, StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
self.init(bytes: bytes, count: count) // copy bytes
} else {
self.init()
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
// SQLite cant' store zero-length blobs.
guard count > 0 else {
return .null
}
return DatabaseValue(storage: .blob(self))
}
/// Returns a Data initialized from *databaseValue*, if it contains
/// Returns a Data initialized from *dbValue*, if it contains
/// a Blob.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Data? {
guard case .blob(let data) = databaseValue.storage else {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Data? {
guard case .blob(let data) = dbValue.storage else {
return nil
}
return data
@@ -1,32 +0,0 @@
import Foundation
/// DatabaseCoder reads and stores objects that conform to NSCoding in
/// the database.
public struct DatabaseCoder: DatabaseValueConvertible {
/// The object
public let object: Any
/// Creates a DatabaseCoder from an object that conforms to NSCoding.
///
/// The result is nil if and only if *object* is nil.
public init?(_ object: Any?) {
guard let object = object else {
return nil
}
self.object = object
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return NSKeyedArchiver.archivedData(withRootObject: object).databaseValue
}
/// Returns a DatabaseCoder if *databaseValue* contains an archived object.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseCoder? {
guard let data = Data.fromDatabaseValue(databaseValue) else {
return nil
}
return DatabaseCoder(NSKeyedUnarchiver.unarchiveObject(with: data))
}
}
@@ -108,9 +108,9 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
return [dateString, timeString].flatMap { $0 }.joined(separator: " ").databaseValue
}
/// Returns a DatabaseDateComponents if *databaseValue* contains a
/// Returns a DatabaseDateComponents if *dbValue* contains a
/// valid date.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseDateComponents? {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseDateComponents? {
// https://www.sqlite.org/lang_datefunc.html
//
// Supported formats are:
@@ -127,7 +127,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
// - HH:MM:SS.SSS
// We need a String
guard let string = String.fromDatabaseValue(databaseValue) else {
guard let string = String.fromDatabaseValue(dbValue) else {
return nil
}
@@ -1,3 +1,5 @@
import Foundation
/// DatabaseValueConvertible is free for ReferenceConvertible types whose
/// ReferenceType is itself DatabaseValueConvertible.
///
@@ -11,15 +13,29 @@
///
/// // ... then the ReferenceConvertible type can freely adopt DatabaseValueConvertible:
/// extension Foo : DatabaseValueConvertible { /* empty */ }
extension ReferenceConvertible where Self: DatabaseValueConvertible, Self.ReferenceType: DatabaseValueConvertible {
extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return (self as! ReferenceType).databaseValue
}
/// Returns a value initialized from *databaseValue*, if possible.
/// Returns a value initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
return ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
}
}
public extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
// Preserve custom database decoding
return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) }
}
}
public extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
// Preserve custom database encoding
return (self as! ReferenceType).databaseValue
}
}
+62 -22
View File
@@ -3,26 +3,75 @@ import Foundation
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension NSDate : DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
/// Returns a database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
public var databaseValue: DatabaseValue {
return storageDateFormatter.string(from: self as Date).databaseValue
return (self as Date).databaseValue
}
/// Returns a Date initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(databaseValue) {
return cast(fromDatabaseDateComponents(databaseDateComponents))
/// Returns a date initialized from dbValue, if possible.
///
/// If database value contains a number, that number is interpreted as a
/// timeinterval since 00:00:00 UTC on 1 January 1970.
///
/// If database value contains a string, that string is interpreted as a
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
/// zone. Nil is returned if the date string does not contain at least the
/// year, month and day components. Other components (minutes, etc.)
/// are set to zero if missing.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
guard let date = Date.fromDatabaseValue(dbValue) else {
return nil
}
if let julianDayNumber = Double.fromDatabaseValue(databaseValue) {
return cast(fromJulianDayNumber(julianDayNumber))
return cast(date)
}
}
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension Date : DatabaseValueConvertible {
/// Returns a database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
public var databaseValue: DatabaseValue {
return storageDateFormatter.string(from: self).databaseValue
}
/// Returns a date initialized from dbValue, if possible.
///
/// If database value contains a number, that number is interpreted as a
/// timeinterval since 00:00:00 UTC on 1 January 1970.
///
/// If database value contains a string, that string is interpreted as a
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
/// zone. Nil is returned if the date string does not contain at least the
/// year, month and day components. Other components (minutes, etc.)
/// are set to zero if missing.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Date? {
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
return Date(databaseDateComponents: databaseDateComponents)
}
if let timestamp = Double.fromDatabaseValue(dbValue) {
return Date(timeIntervalSince1970: timestamp)
}
return nil
}
private static func fromJulianDayNumber(_ julianDayNumber: Double) -> Date? {
private init?(databaseDateComponents: DatabaseDateComponents) {
guard databaseDateComponents.format.hasYMDComponents else {
// Refuse to turn hours without any date information into Date:
return nil
}
guard let date = UTCCalendar.date(from: databaseDateComponents.dateComponents) else {
return nil
}
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
}
/// Creates a date from a [Julian Day](https://en.wikipedia.org/wiki/Julian_day).
public init?(julianDay: Double) {
// Conversion uses the same algorithm as SQLite: https://www.sqlite.org/src/artifact/8ec787fed4929d8c
let JD = Int64(julianDayNumber * 86400000)
// TODO: check for overflows one day, and return nil when computation can't complete.
let JD = Int64(julianDay * 86400000)
let Z = Int(((JD + 43200000)/86400000))
var A = Int(((Double(Z) - 1867216.25)/36524.25))
A = Z + 1 + A - (A/4)
@@ -52,22 +101,13 @@ extension NSDate : DatabaseValueConvertible {
dateComponents.second = Int(second)
dateComponents.nanosecond = Int((second - Double(Int(second))) * 1.0e9)
return UTCCalendar.date(from: dateComponents)!
}
private static func fromDatabaseDateComponents(_ databaseDateComponents: DatabaseDateComponents) -> Date? {
guard databaseDateComponents.format.hasYMDComponents else {
// Refuse to turn hours without any date information into Date:
guard let date = UTCCalendar.date(from: dateComponents) else {
return nil
}
return UTCCalendar.date(from: databaseDateComponents.dateComponents)!
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
}
}
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension Date : DatabaseValueConvertible { }
/// The DatabaseDate date formatter for stored dates.
private let storageDateFormatter: DateFormatter = {
let formatter = DateFormatter()
+3 -3
View File
@@ -8,10 +8,10 @@ extension NSData : DatabaseValueConvertible {
return (self as Data).databaseValue
}
/// Returns an NSData initialized from *databaseValue*, if it contains
/// Returns an NSData initialized from *dbValue*, if it contains
/// a Blob.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
guard let data = Data.fromDatabaseValue(databaseValue) else {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
guard let data = Data.fromDatabaseValue(dbValue) else {
return nil
}
return cast(data)
+1 -1
View File
@@ -9,7 +9,7 @@ extension NSNull : DatabaseValueConvertible {
}
/// Returns nil.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
return nil
}
}
+3 -3
View File
@@ -53,9 +53,9 @@ extension NSNumber : DatabaseValueConvertible {
}
}
/// Returns an NSNumber initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
switch databaseValue.storage {
/// Returns an NSNumber initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
switch dbValue.storage {
case .int64(let int64):
return self.init(value: int64)
case .double(let double):
+3 -3
View File
@@ -8,9 +8,9 @@ extension NSString : DatabaseValueConvertible {
return (self as String).databaseValue
}
/// Returns an NSString initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
guard let string = String.fromDatabaseValue(databaseValue) else {
/// Returns an NSString initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
guard let string = String.fromDatabaseValue(dbValue) else {
return nil
}
return self.init(string: string)
+3 -3
View File
@@ -9,9 +9,9 @@ extension NSURL : DatabaseValueConvertible {
return absoluteString?.databaseValue ?? .null
}
/// Returns an NSURL initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
guard let string = String.fromDatabaseValue(databaseValue) else {
/// Returns an NSURL initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
guard let string = String.fromDatabaseValue(dbValue) else {
return nil
}
return cast(URL(string: string))
+4 -4
View File
@@ -7,14 +7,14 @@ extension NSUUID : DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
return uuidBytes.withUnsafeMutableBufferPointer { buffer in
getBytes(buffer.baseAddress)
getBytes(buffer.baseAddress!)
return NSData(bytes: buffer.baseAddress, length: 16).databaseValue
}
}
/// Returns an NSUUID initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
guard let data = NSData.fromDatabaseValue(databaseValue), data.length == 16 else {
/// Returns an NSUUID initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
return nil
}
return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
@@ -0,0 +1,91 @@
private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
let dbValue: DatabaseValue
let codingPath: [CodingKey]
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
func decodeNil() -> Bool {
return dbValue.isNull
}
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode(_ type: Bool.Type) throws -> Bool { return dbValue.losslessConvert() }
func decode(_ type: Int.Type) throws -> Int { return dbValue.losslessConvert() }
func decode(_ type: Int8.Type) throws -> Int8 { return dbValue.losslessConvert() }
func decode(_ type: Int16.Type) throws -> Int16 { return dbValue.losslessConvert() }
func decode(_ type: Int32.Type) throws -> Int32 { return dbValue.losslessConvert() }
func decode(_ type: Int64.Type) throws -> Int64 { return dbValue.losslessConvert() }
func decode(_ type: UInt.Type) throws -> UInt { return dbValue.losslessConvert() }
func decode(_ type: UInt8.Type) throws -> UInt8 { return dbValue.losslessConvert() }
func decode(_ type: UInt16.Type) throws -> UInt16 { return dbValue.losslessConvert() }
func decode(_ type: UInt32.Type) throws -> UInt32 { return dbValue.losslessConvert() }
func decode(_ type: UInt64.Type) throws -> UInt64 { return dbValue.losslessConvert() }
func decode(_ type: Float.Type) throws -> Float { return dbValue.losslessConvert() }
func decode(_ type: Double.Type) throws -> Double { return dbValue.losslessConvert() }
func decode(_ type: String.Type) throws -> String { return dbValue.losslessConvert() }
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows custom database decoding, such as decoding Date from
// String, for example.
return type.fromDatabaseValue(dbValue) as! T
} else {
return try T(from: DatabaseValueDecoder(dbValue: dbValue, codingPath: codingPath))
}
}
}
private struct DatabaseValueDecoder: Decoder {
let dbValue: DatabaseValue
init(dbValue: DatabaseValue, codingPath: [CodingKey]) {
self.dbValue = dbValue
self.codingPath = codingPath
}
// Decoder
let codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any] { return [:] }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
throw DecodingError.typeMismatch(
type,
DecodingError.Context(codingPath: codingPath, debugDescription: "keyed decoding is not supported"))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
return DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath)
}
}
public extension DatabaseValueConvertible where Self: Decodable {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
return try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
}
}
public extension DatabaseValueConvertible where Self: Decodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
// Preserve custom database decoding
return RawValue.fromDatabaseValue(databaseValue).flatMap { self.init(rawValue: $0) }
}
}
@@ -0,0 +1,106 @@
private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
let encode: (DatabaseValue) -> Void
var codingPath: [CodingKey] { return [] }
/// Encodes a null value.
///
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
mutating func encodeNil() throws { encode(.null) }
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
mutating func encode(_ value: Bool) throws { encode(value.databaseValue) }
mutating func encode(_ value: Int) throws { encode(value.databaseValue) }
mutating func encode(_ value: Int8) throws { encode(value.databaseValue) }
mutating func encode(_ value: Int16) throws { encode(value.databaseValue) }
mutating func encode(_ value: Int32) throws { encode(value.databaseValue) }
mutating func encode(_ value: Int64) throws { encode(value.databaseValue) }
mutating func encode(_ value: UInt) throws { encode(value.databaseValue) }
mutating func encode(_ value: UInt8) throws { encode(value.databaseValue) }
mutating func encode(_ value: UInt16) throws { encode(value.databaseValue) }
mutating func encode(_ value: UInt32) throws { encode(value.databaseValue) }
mutating func encode(_ value: UInt64) throws { encode(value.databaseValue) }
mutating func encode(_ value: Float) throws { encode(value.databaseValue) }
mutating func encode(_ value: Double) throws { encode(value.databaseValue) }
mutating func encode(_ value: String) throws { encode(value.databaseValue) }
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
mutating func encode<T>(_ value: T) throws where T : Encodable {
if let dbValueConvertible = value as? DatabaseValueConvertible {
// Prefer DatabaseValueConvertible encoding over Decodable.
// This allows us to encode Date as String, for example.
encode(dbValueConvertible.databaseValue)
} else {
try value.encode(to: DatabaseValueEncoder(encode: encode))
}
}
}
private struct DatabaseValueEncoder : Encoder {
let encode: (DatabaseValue) -> Void
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey] { return [] }
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey : Any] = [:]
init(encode: @escaping (DatabaseValue) -> Void) {
self.encode = encode
}
/// Returns an encoding container appropriate for holding multiple values keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A new keyed encoding container.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
fatalError("keyed encoding is not supported")
}
/// Returns an encoding container appropriate for holding multiple unkeyed values.
///
/// - returns: A new empty unkeyed container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func unkeyedContainer() -> UnkeyedEncodingContainer {
fatalError("unkeyed encoding is not supported")
}
/// Returns an encoding container appropriate for holding a single primitive value.
///
/// - returns: A new empty single value container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer {
return DatabaseValueEncodingContainer(encode: encode)
}
}
public extension DatabaseValueConvertible where Self: Encodable {
public var databaseValue: DatabaseValue {
var dbValue: DatabaseValue! = nil
let encoder = DatabaseValueEncoder(encode: { dbValue = $0 })
try! self.encode(to: encoder)
return dbValue
}
}
public extension DatabaseValueConvertible where Self: Encodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
// Preserve custom database encoding
return rawValue.databaseValue
}
}
@@ -10,15 +10,15 @@
///
/// // ... then the RawRepresentable type can freely adopt DatabaseValueConvertible:
/// extension Color : DatabaseValueConvertible { /* empty */ }
extension RawRepresentable where Self: DatabaseValueConvertible, Self.RawValue: DatabaseValueConvertible {
extension DatabaseValueConvertible where Self: RawRepresentable, Self.RawValue: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawValue.databaseValue
}
/// Returns a value initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
return RawValue.fromDatabaseValue(databaseValue).flatMap { self.init(rawValue: $0) }
/// Returns a value initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
return RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) }
}
}
@@ -1,22 +1,9 @@
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - Value Types
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -36,8 +23,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
return (self ? 1 : 0).databaseValue
}
/// Returns a Bool initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Bool? {
/// Returns a Bool initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Bool? {
// IMPLEMENTATION NOTE
//
// https://www.sqlite.org/lang_expr.html#booleanexpr
@@ -94,7 +81,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
// the natural boolean storage class, and Real because Numeric affinity
// store big numbers as Real.
switch databaseValue.storage {
switch dbValue.storage {
case .int64(let int64):
return (int64 != 0)
case .double(let double):
@@ -115,8 +102,11 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
GRDBPrecondition(int64 >= Int64(Int.min) && int64 <= Int64(Int.max), "could not convert database value \(int64) to Int")
self = Int(int64)
if let v = Int(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int")
}
}
/// Returns a value that can be stored in the database.
@@ -124,28 +114,66 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
return Int64(self).databaseValue
}
/// Returns an Int initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Int? {
switch databaseValue.storage {
case .int64(let int64):
guard int64 >= Int64(Int.min) else { return nil }
guard int64 <= Int64(Int.max) else { return nil }
return Int(int64)
case .double(let double):
// Cast from Double to Int64 to Int
// Why? Because on 32-bits platforms we'll convert more values this way (Swift bug?)
// - Int(Int64(-2147483648.999999)) // -2147483648
// - Int(-2147483648.999999) // fatal error
guard double >= Double(Int64.min) else { return nil }
guard double < Double(Int64.max) else { return nil }
let int64 = Int64(double)
guard int64 >= Int64(Int.min) else { return nil }
guard int64 <= Int64(Int.max) else { return nil }
return Int(int64)
default:
return nil
/// Returns an Int initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
}
}
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = Int8(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int8")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an Int8 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
}
}
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = Int16(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int16")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an Int16 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
}
}
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -158,8 +186,11 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
GRDBPrecondition(int64 >= Int64(Int32.min) && int64 <= Int64(Int32.max), "could not convert database value \(int64) to Int32")
self = Int32(int64)
if let v = Int32(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to Int32")
}
}
/// Returns a value that can be stored in the database.
@@ -167,27 +198,9 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
return Int64(self).databaseValue
}
/// Returns an Int32 initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Int32? {
switch databaseValue.storage {
case .int64(let int64):
guard int64 >= Int64(Int32.min) else { return nil }
guard int64 <= Int64(Int32.max) else { return nil }
return Int32(int64)
case .double(let double):
// Cast from Double to Int64 to Int32
// Why? Because we'll convert more values this way (Swift bug?)
// - Int32(Int64(-2147483648.999999)) // -2147483648
// - Int32(-2147483648.999999) // fatal error
guard double >= Double(Int64.min) else { return nil }
guard double < Double(Int64.max) else { return nil }
let int64 = Int64(double)
guard int64 >= Int64(Int32.min) else { return nil }
guard int64 <= Int64(Int32.max) else { return nil }
return Int32(int64)
default:
return nil
}
/// Returns an Int32 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
return Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
}
}
@@ -208,9 +221,9 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
return DatabaseValue(storage: .int64(self))
}
/// Returns an Int64 initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Int64? {
switch databaseValue.storage {
/// Returns an Int64 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int64? {
switch dbValue.storage {
case .int64(let int64):
return int64
case .double(let double):
@@ -223,6 +236,146 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an Int initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
}
}
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt8(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt8")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an UInt8 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
}
}
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt16(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt16")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an UInt16 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
}
}
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt32(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt32")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an UInt32 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
}
}
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt64(exactly: int64) {
self = v
} else {
fatalError("could not convert database value \(int64) to UInt64")
}
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Int64(self).databaseValue
}
/// Returns an UInt64 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? {
return Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
}
}
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
@@ -240,9 +393,9 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
return DatabaseValue(storage: .double(self))
}
/// Returns a Double initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Double? {
switch databaseValue.storage {
/// Returns a Double initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Double? {
switch dbValue.storage {
case .int64(let int64):
return Double(int64)
case .double(let double):
@@ -270,9 +423,9 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
return Double(self).databaseValue
}
/// Returns a Float initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Float? {
switch databaseValue.storage {
/// Returns a Float initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Float? {
switch dbValue.storage {
case .int64(let int64):
return Float(int64)
case .double(let double):
@@ -300,9 +453,9 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
return DatabaseValue(storage: .string(self))
}
/// Returns a String initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> String? {
switch databaseValue.storage {
/// Returns a String initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> String? {
switch dbValue.storage {
case .string(let string):
return string
default:
@@ -325,10 +478,10 @@ extension DatabaseFunction {
/// capitalized:
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.capitalized)
/// let request = Player.select(nameColumn.capitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.capitalized
@@ -344,10 +497,10 @@ extension DatabaseFunction {
/// lowercased:
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.lowercased())
/// let request = Player.select(nameColumn.lowercased())
/// let names = try String.fetchAll(dbQueue, request) // [String]
public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.lowercased()
@@ -363,10 +516,10 @@ extension DatabaseFunction {
/// uppercased:
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.uppercased())
/// let request = Player.select(nameColumn.uppercased())
/// let names = try String.fetchAll(dbQueue, request) // [String]
public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.uppercased()
@@ -384,11 +537,11 @@ extension DatabaseFunction {
/// localizedCapitalized:
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.localizedCapitalized)
/// let request = Player.select(nameColumn.localizedCapitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedCapitalized
@@ -404,11 +557,11 @@ extension DatabaseFunction {
/// localizedLowercased:
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.localizedLowercased)
/// let request = Player.select(nameColumn.localizedLowercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedLowercase
@@ -424,11 +577,11 @@ extension DatabaseFunction {
/// localizedUppercased:
///
/// let nameColumn = Column("name")
/// let request = Person.select(nameColumn.localizedUppercased)
/// let request = Player.select(nameColumn.localizedUppercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedUppercase
@@ -460,7 +613,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
@@ -478,7 +631,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
@@ -496,7 +649,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
@@ -514,7 +667,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.localizedCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
@@ -532,7 +685,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.localizedStandardCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
-238
View File
@@ -1,238 +0,0 @@
import Foundation
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#endif
// MARK: - Public
extension String {
/// Returns the receiver, quoted for safe insertion as an identifier in an
/// SQL query.
///
/// db.execute("SELECT * FROM \(tableName.quotedDatabaseIdentifier)")
public var quotedDatabaseIdentifier: String {
// See https://www.sqlite.org/lang_keywords.html
return "\"" + self + "\""
}
}
/// Return as many question marks separated with commas as the *count* argument.
///
/// databaseQuestionMarks(count: 3) // "?,?,?"
public func databaseQuestionMarks(count: Int) -> String {
return Array(repeating: "?", count: count).joined(separator: ",")
}
// MARK: - Internal
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
/// Custom precondition function which aims at solving
/// https://bugs.swift.org/browse/SR-905 and
/// https://github.com/groue/GRDB.swift/issues/37
///
/// TODO: remove this function when https://bugs.swift.org/browse/SR-905 is solved.
func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) {
if !condition() {
fatalError(message, file: file, line: line)
}
}
// Workaround Swift inconvenience around factory methods of non-final classes
func cast<T, U>(_ value: T) -> U? {
return value as? U
}
extension Array {
/// Removes the first object that matches *predicate*.
mutating func removeFirst(_ predicate: (Element) throws -> Bool) rethrows {
if let index = try index(where: predicate) {
remove(at: index)
}
}
}
extension Dictionary {
/// Create a dictionary with the keys and values in the given sequence.
init<Sequence: Swift.Sequence>(keyValueSequence: Sequence) where Sequence.Iterator.Element == (Key, Value) {
self.init(minimumCapacity: keyValueSequence.underestimatedCount)
for (key, value) in keyValueSequence {
self[key] = value
}
}
/// Create a dictionary from keys and a value builder.
init<Sequence: Swift.Sequence>(keys: Sequence, value: (Key) -> Value) where Sequence.Iterator.Element == Key {
self.init(minimumCapacity: keys.underestimatedCount)
for key in keys {
self[key] = value(key)
}
}
}
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a value.
final class ReadWriteBox<T> {
var value: T {
get { return read { $0 } }
set { write { $0 = newValue } }
}
init(_ value: T) {
self._value = value
self.queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent])
}
func read<U>(_ block: (T) -> U) -> U {
var result: U? = nil
queue.sync {
result = block(self._value)
}
return result!
}
func write(_ block: (inout T) -> Void) {
queue.sync(flags: [.barrier]) {
block(&self._value)
}
}
private var _value: T
private var queue: DispatchQueue
}
/// A Pool maintains a set of elements that are built them on demand. A pool has
/// a maximum number of elements.
///
/// // A pool of 3 integers
/// var number = 0
/// let pool = Pool<Int>(maximumCount: 3, makeElement: {
/// number = number + 1
/// return number
/// })
///
/// The function get() dequeues an available element and gives this element to
/// the block argument. During the block execution, the element is not
/// available. When the block is ended, the element is available again.
///
/// // got 1
/// pool.get { n in
/// print("got \(n)")
/// }
///
/// If there is no available element, the pool builds a new element, unless the
/// maximum number of elements is reached. In this case, the get() method
/// blocks the current thread, until an element eventually turns available again.
///
/// DispatchQueue.concurrentPerform(iterations: 6) { _ in
/// pool.get { n in
/// print("got \(n)")
/// }
/// }
///
/// got 1
/// got 2
/// got 3
/// got 2
/// got 1
/// got 3
final class Pool<T> {
var makeElement: (() throws -> T)?
private var items: [PoolItem<T>] = []
private let queue: DispatchQueue // protects items
private let semaphore: DispatchSemaphore // limits the number of elements
init(maximumCount: Int, makeElement: (() throws -> T)? = nil) {
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
self.queue = DispatchQueue(label: "GRDB.Pool")
self.semaphore = DispatchSemaphore(value: maximumCount)
}
/// Returns a tuple (element, releaseElement())
/// Client MUST call releaseElement() after the element has been used.
func get() throws -> (T, () -> ()) {
var item: PoolItem<T>! = nil
_ = semaphore.wait(timeout: .distantFuture)
do {
try queue.sync {
if let availableItem = items.first(where: { $0.available }) {
item = availableItem
item.available = false
} else {
item = try PoolItem(element: makeElement!(), available: false)
items.append(item)
}
}
} catch {
semaphore.signal()
throw error
}
let unlock = {
self.queue.sync {
item.available = true
}
self.semaphore.signal()
}
return (item.element, unlock)
}
/// Performs a synchronous block with an element. The element turns
/// available after the block has executed.
func get<U>(block: (T) throws -> U) throws -> U {
let (element, release) = try get()
defer { release() }
return try block(element)
}
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary queue.
func forEach(_ body: (T) throws -> ()) rethrows {
try queue.sync {
for item in items {
try body(item.element)
}
}
}
/// Empty the pool. Currently used items won't be reused.
func clear() {
clear {}
}
/// Empty the pool. Currently used items won't be reused.
/// Eventual block is executed before any other element is dequeued.
func clear(andThen block: () throws -> ()) rethrows {
try queue.sync {
items = []
try block()
}
}
}
private class PoolItem<T> {
let element: T
var available: Bool
init(element: T, available: Bool) {
self.element = element
self.available = available
}
}
+48 -63
View File
@@ -24,13 +24,14 @@ public struct FTS3Pattern {
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
throw DatabaseError(code: error.code, message: error.message, sql: nil, arguments: nil)
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
}
// Pattern is valid
self.rawPattern = rawPattern
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
@@ -69,6 +70,49 @@ public struct FTS3Pattern {
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
#else
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAnyTokenIn: "") // nil
/// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(iOS 8.2, OSX 10.10, *)
public init?(matchingAnyTokenIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
/// Creates a pattern that matches all tokens found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAllTokensIn: "") // nil
/// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(iOS 8.2, OSX 10.10, *)
public init?(matchingAllTokensIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
/// Creates a pattern that matches a contiguous string; returns nil if no
/// pattern could be built.
///
/// FTS3Pattern(matchingPhrase: "") // nil
/// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(iOS 8.2, OSX 10.10, *)
public init?(matchingPhrase string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
#endif
}
extension FTS3Pattern : DatabaseValueConvertible {
@@ -77,70 +121,11 @@ extension FTS3Pattern : DatabaseValueConvertible {
return rawPattern.databaseValue
}
/// Returns an FTS3Pattern initialized from *databaseValue*, if it contains
/// Returns an FTS3Pattern initialized from *dbValue*, if it contains
/// a suitable value.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> FTS3Pattern? {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS3Pattern? {
return String
.fromDatabaseValue(databaseValue)
.fromDatabaseValue(dbValue)
.flatMap { try? FTS3Pattern(rawPattern: $0) }
}
}
extension QueryInterfaceRequest {
// MARK: Full Text Search
/// Returns a new QueryInterfaceRequest with a matching predicate added
/// to the eventual set of already applied predicates.
///
/// // SELECT * FROM books WHERE books MATCH '...'
/// var request = Book.all()
/// request = request.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T> {
switch query.source {
case .table(let name, let alias)?:
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern ?? DatabaseValue.null))
default:
// Programmer error
fatalError("fts3 match requires a table")
}
}
}
extension TableMapping {
// MARK: Full Text Search
/// Returns a QueryInterfaceRequest with a matching predicate.
///
/// // SELECT * FROM books WHERE books MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM books WHERE books MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
}
}
extension Column {
/// A matching SQL expression with the `MATCH` SQL operator.
///
/// // content MATCH '...'
/// Column("content").match(pattern)
///
/// If the search pattern is nil, SQLite will evaluate the expression
/// to false.
public func match(_ pattern: FTS3Pattern?) -> SQLExpression {
return SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null)
}
}
+42 -1
View File
@@ -32,6 +32,7 @@ public struct FTS3TokenizerDescriptor {
/// See https://www.sqlite.org/fts3.html#tokenizer
public static let porter = FTS3TokenizerDescriptor("porter")
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The "unicode61" tokenizer.
///
/// db.create(virtualTable: "books", using: FTS4()) { t in
@@ -48,6 +49,33 @@ public struct FTS3TokenizerDescriptor {
///
/// See https://www.sqlite.org/fts3.html#tokenizer
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
return _unicode61(removeDiacritics: removeDiacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#else
/// The "unicode61" tokenizer.
///
/// db.create(virtualTable: "books", using: FTS4()) { t in
/// t.tokenizer = .unicode61()
/// }
///
/// - parameters:
/// - removeDiacritics: If true (the default), then SQLite will strip
/// diacritics from latin characters.
/// - separators: Unless empty (the default), SQLite will consider these
/// characters as token separators.
/// - tokenCharacters: Unless empty (the default), SQLite will consider
/// these characters as token characters.
///
/// See https://www.sqlite.org/fts3.html#tokenizer
@available(iOS 8.2, OSX 10.10, *)
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return _unicode61(removeDiacritics: removeDiacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#endif
private static func _unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
var arguments: [String] = []
if !removeDiacritics {
arguments.append("remove_diacritics=0")
@@ -63,10 +91,23 @@ public struct FTS3TokenizerDescriptor {
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
func tokenize(_ string: String) -> [String] {
return _tokenize(string)
}
#else
@available(iOS 8.2, OSX 10.10, *)
func tokenize(_ string: String) -> [String] {
return _tokenize(string)
}
#endif
/// Returns an array of tokens found in the string argument.
///
/// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"]
func tokenize(_ string: String) -> [String] {
private func _tokenize(_ string: String) -> [String] {
// fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return DatabaseQueue().inDatabase { db in
var tokenizerChunks: [String] = []
tokenizerChunks.append(name)
+41 -23
View File
@@ -95,7 +95,7 @@ public struct FTS4 : VirtualTableModule {
case .synchronized(let contentTable):
// https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
let rowIDColumn = (try? db.primaryKey(contentTable))??.rowIDColumn ?? "rowid"
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
let indexedColumns = definition.columns.map { $0.name }
@@ -110,25 +110,20 @@ public struct FTS4 : VirtualTableModule {
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
try db.execute(
"CREATE TRIGGER \("__\(contentTable)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN " +
"DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); " +
"END")
try db.execute(
"CREATE TRIGGER \("__\(contentTable)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN " +
"DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); " +
"END")
try db.execute(
"CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN " +
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); " +
"END")
try db.execute(
"CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN " +
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); " +
"END")
try db.execute("""
CREATE TRIGGER \("__\(contentTable)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
END;
CREATE TRIGGER \("__\(contentTable)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
END;
CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
END;
CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
END;
""")
// https://www.sqlite.org/fts3.html#*fts4rebuidcmd
@@ -247,7 +242,7 @@ public final class FTS4TableDefinition {
///
/// You get instances of this class when you create an FTS4 table:
///
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
/// t.column("content") // FTS4ColumnDefinition
/// }
///
@@ -263,9 +258,10 @@ public final class FTS4ColumnDefinition {
self.isLanguageId = false
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
/// t.column("a")
/// t.column("b").notIndexed()
/// }
@@ -275,13 +271,35 @@ public final class FTS4ColumnDefinition {
/// - returns: Self so that you can further refine the column definition.
@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
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
#else
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
/// t.column("a")
/// t.column("b").notIndexed()
/// }
///
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
///
/// - returns: Self so that you can further refine the column definition.
@available(iOS 8.2, OSX 10.10, *)
@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
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
#endif
/// Uses the column as the Int32 language id hidden column.
///
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
/// t.column("a")
/// t.column("lid").asLanguageId()
/// }
+34 -29
View File
@@ -62,7 +62,7 @@
}
case .synchronized(let contentTable):
arguments.append("content=\(contentTable.sqlExpression.sql)")
if let rowIDColumn = try db.primaryKey(contentTable)?.rowIDColumn {
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
arguments.append("content_rowid=\(rowIDColumn.sqlExpression.sql)")
}
}
@@ -93,7 +93,7 @@
case .synchronized(let contentTable):
// https://sqlite.org/fts5.html#external_content_tables
let rowIDColumn = (try? db.primaryKey(contentTable))??.rowIDColumn ?? "rowid"
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
let indexedColumns = definition.columns.map { $0.name }
@@ -110,21 +110,18 @@
.map { "old.\($0.quotedDatabaseIdentifier)" }
.joined(separator: ", ")
try db.execute(
"CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN " +
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); " +
"END")
try db.execute(
"CREATE TRIGGER \("__\(contentTable)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN " +
"INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); " +
"END")
try db.execute(
"CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN " +
"INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); " +
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); " +
"END")
try db.execute("""
CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
CREATE TRIGGER \("__\(contentTable)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
END;
CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
""")
// https://sqlite.org/fts5.html#the_rebuild_command
@@ -132,17 +129,25 @@
}
}
static func api(_ db: Database) -> UnsafePointer<fts5_api>? {
do {
return try Data.fetchOne(db, "SELECT fts5()").flatMap { data in
guard data.count == MemoryLayout<UnsafePointer<fts5_api>>.size else {
return nil
}
return data.withUnsafeBytes { $0.pointee }
}
} catch {
return nil
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
let sqliteConnection = db.sqliteConnection
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
guard code == SQLITE_OK else {
fatalError("FTS5 is not available")
}
defer { sqlite3_finalize(statement) }
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
}
sqlite3_step(statement)
guard let result = api else {
fatalError("FTS5 is not available")
}
return result
}
}
@@ -279,7 +284,7 @@
///
/// You get instances of this class when you create an FTS5 table:
///
/// try db.create(virtualTable: "persons", using: FTS5()) { t in
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
/// t.column("content") // FTS5ColumnDefinition
/// }
///
@@ -295,7 +300,7 @@
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "persons", using: FTS5()) { t in
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
/// t.column("a")
/// t.column("b").notIndexed()
/// }
+3 -6
View File
@@ -55,10 +55,7 @@
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// db.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
guard let api = FTS5.api(self) else {
// Assume a GRDB bug or an SQLite miscompilation: there is no point throwing any error.
fatalError("FTS5 is not enabled")
}
let api = FTS5.api(self)
// Swift won't let the @convention(c) xCreate() function below create
// an instance of the generic Tokenizer type.
@@ -81,7 +78,7 @@
tokenizerHandle.pointee = tokenizerPointer
return SQLITE_OK
} catch let error as DatabaseError {
return error.code
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
@@ -134,7 +131,7 @@
}
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(code: code, message: lastErrorMessage).description)
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
}
}
}
+5 -55
View File
@@ -62,12 +62,12 @@
}
}
try db.makeSelectStatement("SELECT * FROM documents WHERE documents MATCH ?")
.fetchCursor(arguments: [rawPattern])
.cursor(arguments: [rawPattern])
.next() // error on next() for invalid patterns
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
throw DatabaseError(code: error.code, message: error.message, sql: nil, arguments: nil)
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
}
// Pattern is valid
@@ -95,62 +95,12 @@
return rawPattern.databaseValue
}
/// Returns an FTS5Pattern initialized from *databaseValue*, if it
/// Returns an FTS5Pattern initialized from *dbValue*, if it
/// contains a suitable value.
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> FTS5Pattern? {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS5Pattern? {
return String
.fromDatabaseValue(databaseValue)
.fromDatabaseValue(dbValue)
.flatMap { try? FTS5Pattern(rawPattern: $0) }
}
}
extension QueryInterfaceRequest {
// MARK: Full Text Search
/// Returns a new QueryInterfaceRequest with a matching predicate added
/// to the eventual set of already applied predicates.
///
/// // SELECT * FROM books WHERE books MATCH '...'
/// var request = Book.all()
/// request = request.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
switch query.source {
case .table(let name, let alias)?:
if let pattern = pattern {
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern))
} else {
return filter(false)
}
default:
// Programmer error
fatalError("fts5 match requires a table")
}
}
}
extension TableMapping {
// MARK: Full Text Search
/// Returns a QueryInterfaceRequest with a matching predicate.
///
/// // SELECT * FROM books WHERE books MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the `selectsRowID` type property is true, then the selection
/// includes the hidden "rowid" column:
///
/// // SELECT *, rowid FROM books WHERE books MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
}
}
#endif
+6 -8
View File
@@ -87,7 +87,7 @@
return SQLITE_OK
})
if (code != SQLITE_OK) {
throw DatabaseError(code: code)
throw DatabaseError(resultCode: code)
}
}
return context.tokens
@@ -116,7 +116,7 @@
init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws {
guard let xCreate = xTokenizer.xCreate else {
throw DatabaseError(code: SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate")
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate")
}
self.xTokenizer = xTokenizer
@@ -147,13 +147,13 @@
}
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: "failed fts5_tokenizer.xCreate")
throw DatabaseError(resultCode: code, message: "failed fts5_tokenizer.xCreate")
}
if let tokenizerPointer = tokenizerPointer {
self.tokenizerPointer = tokenizerPointer
} else {
throw DatabaseError(code: code, message: "nil tokenizer")
throw DatabaseError(resultCode: code, message: "nil tokenizer")
}
}
@@ -188,9 +188,7 @@
/// }
/// }
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer {
guard let api = FTS5.api(self) else {
throw DatabaseError(code: SQLITE_MISUSE, message: "FTS5 API not found")
}
let api = FTS5.api(self)
let xTokenizerPointer: UnsafeMutablePointer<fts5_tokenizer> = .allocate(capacity: 1)
defer { xTokenizerPointer.deallocate(capacity: 1) }
@@ -205,7 +203,7 @@
xTokenizerPointer)
guard code == SQLITE_OK else {
throw DatabaseError(code: code)
throw DatabaseError(resultCode: code)
}
let contextPointer = contextHandle.pointee
+2 -2
View File
@@ -123,14 +123,14 @@
// Inject token bytes into SQLite
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: "token callback failed")
throw DatabaseError(resultCode: code, message: "token callback failed")
}
}
})
return SQLITE_OK
} catch let error as DatabaseError {
return error.code
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
+2 -2
View File
@@ -48,8 +48,8 @@ extension RowConvertible where Self: TableMapping {
public static func fetch(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> Any { preconditionFailure() }
}
@available(*, unavailable, message:"DatabaseSequence has been replaced by DatabaseCursor.")
@available(*, unavailable, message:"DatabaseSequence has been replaced by Cursor.")
public struct DatabaseSequence<T> { }
@available(*, unavailable, message:"DatabaseIterator has been replaced by DatabaseCursor.")
@available(*, unavailable, message:"DatabaseIterator has been replaced by Cursor.")
public struct DatabaseIterator<T> { }
+4
View File
@@ -0,0 +1,4 @@
extension DatabaseError {
@available(*, unavailable, renamed:"resultCode")
public var code: Int32 { return 0 }
}
+9
View File
@@ -0,0 +1,9 @@
extension Database {
@available(*, unavailable, renamed:"inTransaction")
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { }
}
extension DatabaseValue {
@available(*, unavailable, message:"DatabaseSequence has been replaced by Cursor.")
public func value() -> Any { preconditionFailure() }
}
+4
View File
@@ -0,0 +1,4 @@
extension Request {
@available(*, unavailable, renamed:"asRequest(of:)")
public func bound<T>(to type: T.Type) -> AnyTypedRequest<T> { preconditionFailure() }
}
+28
View File
@@ -0,0 +1,28 @@
extension Row {
@available(*, unavailable, message:"use subscript instead: row[index]")
public func value(atIndex index: Int) -> DatabaseValueConvertible? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[index]")
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[index]")
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value(named name: String) -> DatabaseValueConvertible? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value<Value: DatabaseValueConvertible>(named name: String) -> Value? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value<Value: DatabaseValueConvertible>(named name: String) -> Value { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value(_ column: Column) -> DatabaseValueConvertible? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value { preconditionFailure() }
}
+195
View File
@@ -0,0 +1,195 @@
/// A DatabaseMigrator registers and applies database migrations.
///
/// Migrations are named blocks of SQL statements that are guaranteed to be
/// applied in order, once and only once.
///
/// When a user upgrades your application, only non-applied migration are run.
///
/// Usage:
///
/// var migrator = DatabaseMigrator()
///
/// // v1.0 database
/// migrator.registerMigration("createAuthors") { db in
/// try db.execute("""
/// CREATE TABLE authors (
/// id INTEGER PRIMARY KEY,
/// creationDate TEXT,
/// name TEXT NOT NULL
/// )
/// """)
/// }
///
/// migrator.registerMigration("createBooks") { db in
/// try db.execute("""
/// CREATE TABLE books (
/// uuid TEXT PRIMARY KEY,
/// authorID INTEGER NOT NULL
/// REFERENCES authors(id)
/// ON DELETE CASCADE ON UPDATE CASCADE,
/// title TEXT NOT NULL
/// )
/// """)
/// }
///
/// // v2.0 database
/// migrator.registerMigration("AddBirthYearToAuthors") { db in
/// try db.execute("ALTER TABLE authors ADD COLUMN birthYear INT")
/// }
///
/// try migrator.migrate(dbQueue)
public struct DatabaseMigrator {
/// A new migrator.
public init() {
}
/// Registers a migration.
///
/// migrator.registerMigration("createPlayers") { db in
/// try db.execute("""
/// CREATE TABLE players (
/// id INTEGER PRIMARY KEY,
/// creationDate TEXT,
/// name TEXT NOT NULL
/// )
/// """)
/// }
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, migrate: migrate))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.execute("""
/// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
/// INSERT INTO new_players SELECT * FROM players;
/// DROP TABLE players;
/// ALTER TABLE new_players RENAME TO players;
/// """)
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
#else
@available(iOS 8.2, OSX 10.10, *)
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.execute("""
/// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
/// INSERT INTO new_players SELECT * FROM players;
/// DROP TABLE players;
/// ALTER TABLE new_players RENAME TO players;
/// """)
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
#endif
/// Iterate migrations in the same order as they were registered. If a
/// migration has not yet been applied, its block is executed in
/// a transaction.
///
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
/// migrations should apply.
/// - throws: An eventual error thrown by the registered migration blocks.
public func migrate(_ writer: DatabaseWriter) throws {
try writer.write { db in
try setupMigrations(db)
try runMigrations(db)
}
}
/// Iterate migrations in the same order as they were registered, up to the
/// provided target. If a migration has not yet been applied, its block is
/// executed in a transaction.
///
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
/// migrations should apply.
/// - targetIdentifier: The identifier of a registered migration.
/// - throws: An eventual error thrown by the registered migration blocks.
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws {
try writer.write { db in
try setupMigrations(db)
try runMigrations(db, upTo: targetIdentifier)
}
}
// MARK: - Non public
private var migrations: [Migration] = []
private mutating func registerMigration(_ migration: Migration) {
GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))")
migrations.append(migration)
}
private func setupMigrations(_ db: Database) throws {
try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
}
private func appliedIdentifiers(_ db: Database) throws -> Set<String> {
return try Set(String.fetchAll(db, "SELECT identifier FROM grdb_migrations"))
}
private func runMigrations(_ db: Database) throws {
let appliedIdentifiers = try self.appliedIdentifiers(db)
for migration in migrations where !appliedIdentifiers.contains(migration.identifier) {
try migration.run(db)
}
}
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
var prefixMigrations: [Migration] = []
for migration in migrations {
prefixMigrations.append(migration)
if migration.identifier == targetIdentifier {
break
}
}
// targetIdentifier must refer to a registered migration
GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))")
// Subsequent migration must not be applied
let appliedIdentifiers = try self.appliedIdentifiers(db)
if prefixMigrations.count < migrations.count {
let nextIdentifier = migrations[prefixMigrations.count].identifier
GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
}
for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) {
try migration.run(db)
}
}
}
@@ -1,49 +1,35 @@
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#endif
/// An internal struct that defines a migration.
struct Migration {
// PRAGMA foreign_key_check = ON was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let identifier: String
let disabledForeignKeyChecks: Bool
let migrate: (Database) throws -> Void
init(identifier: String, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = false
self.migrate = migrate
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
#else
init(identifier: String, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = false
self.migrate = migrate
}
@available(iOS 8.2, OSX 10.10, *)
init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
@available(iOS 8.2, OSX 10.10, *)
// PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
#endif
func run(_ db: Database) throws {
if #available(iOS 8.2, OSX 10.10, *) {
if try disabledForeignKeyChecks && (Bool.fetchOne(db, "PRAGMA foreign_keys") ?? false) {
try runWithDisabledForeignKeys(db)
} else {
try runWithoutDisabledForeignKeys(db)
}
if try disabledForeignKeyChecks && (Bool.fetchOne(db, "PRAGMA foreign_keys") ?? false) {
try runWithDisabledForeignKeys(db)
} else {
try runWithoutDisabledForeignKeys(db)
}
@@ -58,7 +44,6 @@ struct Migration {
}
}
@available(iOS 8.2, OSX 10.10, *)
private func runWithDisabledForeignKeys(_ db: Database) throws {
// Support for database alterations described at
// https://www.sqlite.org/lang_altertable.html#otheralter
@@ -83,7 +68,7 @@ struct Migration {
//
// Let's turn any violation into an SQLITE_CONSTRAINT
// error, and rollback the transaction.
throw DatabaseError(code: SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed")
throw DatabaseError(resultCode: .SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed")
}
// > 11. Commit the transaction started in step 2.
-122
View File
@@ -1,122 +0,0 @@
/// A DatabaseMigrator registers and applies database migrations.
///
/// Migrations are named blocks of SQL statements that are guaranteed to be
/// applied in order, once and only once.
///
/// When a user upgrades your application, only non-applied migration are run.
///
/// Usage:
///
/// var migrator = DatabaseMigrator()
///
/// // v1.0 database
/// migrator.registerMigration("createPersons") { db in
/// try db.execute(
/// "CREATE TABLE persons (" +
/// "id INTEGER PRIMARY KEY, " +
/// "creationDate TEXT, " +
/// "name TEXT NOT NULL" +
/// ")")
/// }
///
/// migrator.registerMigration("createBooks") { db in
/// try db.execute(
/// "CREATE TABLE books (" +
/// "uuid TEXT PRIMARY KEY, " +
/// "ownerID INTEGER NOT NULL " +
/// " REFERENCES persons(id) " +
/// " ON DELETE CASCADE ON UPDATE CASCADE, " +
/// "title TEXT NOT NULL" +
/// ")")
/// }
///
/// // v2.0 database
/// migrator.registerMigration("AddAgeToPersons") { db in
/// try db.execute("ALTER TABLE persons ADD COLUMN age INT")
/// }
///
/// try migrator.migrate(dbQueue)
public struct DatabaseMigrator {
/// A new migrator.
public init() {
}
/// Registers a migration.
///
/// migrator.registerMigration("createPersons") { db in
/// try db.execute(
/// "CREATE TABLE persons (" +
/// "id INTEGER PRIMARY KEY, " +
/// "creationDate TEXT, " +
/// "name TEXT NOT NULL" +
/// ")")
/// }
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, migrate: migrate))
}
@available(iOS 8.2, OSX 10.10, *)
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on persons.name:
/// migrator.registerMigrationWithDisabledForeignKeyChecks("AddNotNullCheckOnName") { db in
/// try db.execute(
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
/// "INSERT INTO new_persons SELECT * FROM persons;" +
/// "DROP TABLE persons;" +
/// "ALTER TABLE new_persons RENAME TO persons;")
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigrationWithDisabledForeignKeyChecks(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
/// Iterate migrations in the same order as they were registered. If a
/// migration has not yet been applied, its block is executed in
/// a transaction.
///
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
/// migrations should apply.
/// - throws: An eventual error thrown by the registered migration blocks.
public func migrate(_ db: DatabaseWriter) throws {
try db.write { db in
try setupMigrations(db)
try runMigrations(db)
}
}
// MARK: - Non public
private var migrations: [Migration] = []
private mutating func registerMigration(_ migration: Migration) {
GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \"\(migration.identifier)\"")
migrations.append(migration)
}
private func setupMigrations(_ db: Database) throws {
try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
}
private func runMigrations(_ db: Database) throws {
let appliedIdentifiers = try String.fetchAll(db, "SELECT identifier FROM grdb_migrations")
for migration in migrations where !appliedIdentifiers.contains(migration.identifier) {
try migration.run(db)
}
}
}
+23
View File
@@ -0,0 +1,23 @@
/// A column in the database
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct Column {
/// The hidden rowID column
public static let rowID = Column("rowid")
/// The name of the column
public let name: String
/// 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)
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
return name.quotedDatabaseIdentifier
}
}
@@ -0,0 +1,56 @@
extension QueryInterfaceRequest {
// MARK: Full Text Search
/// Returns a new QueryInterfaceRequest with a matching predicate added
/// to the eventual set of already applied predicates.
///
/// // SELECT * FROM books WHERE books MATCH '...'
/// var request = Book.all()
/// request = request.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T> {
switch query.source {
case .table(let name, let alias)?:
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern ?? DatabaseValue.null))
default:
// Programmer error
fatalError("fts3 match requires a table")
}
}
}
extension TableMapping {
// MARK: Full Text Search
/// Returns a QueryInterfaceRequest with a matching predicate.
///
/// // SELECT * FROM books WHERE books MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
///
/// 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 matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
}
}
extension Column {
/// A matching SQL expression with the `MATCH` SQL operator.
///
/// // content MATCH '...'
/// Column("content").match(pattern)
///
/// If the search pattern is nil, SQLite will evaluate the expression
/// to false.
public func match(_ pattern: FTS3Pattern?) -> SQLExpression {
return SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null)
}
}
@@ -0,0 +1,49 @@
#if SQLITE_ENABLE_FTS5
extension QueryInterfaceRequest {
// MARK: Full Text Search
/// Returns a new QueryInterfaceRequest with a matching predicate added
/// to the eventual set of already applied predicates.
///
/// // SELECT * FROM books WHERE books MATCH '...'
/// var request = Book.all()
/// request = request.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
///
/// 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 matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
switch query.source {
case .table(let name, let alias)?:
if let pattern = pattern {
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern))
} else {
return filter(false)
}
default:
// Programmer error
fatalError("fts5 match requires a table")
}
}
}
extension TableMapping {
// MARK: Full Text Search
/// Returns a QueryInterfaceRequest with a matching predicate.
///
/// // SELECT * FROM books WHERE books MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
}
}
#endif
+90 -117
View File
@@ -1,9 +1,7 @@
/// A QueryInterfaceRequest describes an SQL query.
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct QueryInterfaceRequest<T> : TypedRequest {
public typealias Fetched = T
public struct QueryInterfaceRequest<T> {
let query: QueryInterfaceSelectQueryDefinition
init(query: QueryInterfaceSelectQueryDefinition) {
@@ -11,18 +9,22 @@ public struct QueryInterfaceRequest<T> : TypedRequest {
}
}
extension QueryInterfaceRequest : SQLSelectQuery {
extension QueryInterfaceRequest : TypedRequest {
public typealias RowDecoder = T
/// This function is an implementation detail of the query interface.
/// Do not use it directly.
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
/// - parameter db: A database connection.
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try query.prepare(db)
}
/// The number of rows fetched by the request.
///
/// # Low Level Query Interface
///
/// See SQLSelectQuery.selectQuerySQL(_)
public func selectQuerySQL(_ arguments: inout StatementArguments?) -> String {
return query.selectQuerySQL(&arguments)
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
return try query.fetchCount(db)
}
}
@@ -32,13 +34,13 @@ extension QueryInterfaceRequest {
/// A new QueryInterfaceRequest with a new net of selected columns.
///
/// // SELECT id, email FROM persons
/// var request = Person.all()
/// // SELECT id, email FROM players
/// var request = Player.all()
/// request = request.select(Column("id"), Column("email"))
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM persons
/// // SELECT email FROM players
/// request
/// .select(Column("id"))
/// .select(Column("email"))
@@ -48,13 +50,13 @@ extension QueryInterfaceRequest {
/// A new QueryInterfaceRequest with a new net of selected columns.
///
/// // SELECT id, email FROM persons
/// var request = Person.all()
/// // SELECT id, email FROM players
/// var request = Player.all()
/// request = request.select([Column("id"), Column("email")])
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM persons
/// // SELECT email FROM players
/// request
/// .select([Column("id")])
/// .select([Column("email")])
@@ -66,13 +68,13 @@ extension QueryInterfaceRequest {
/// A new QueryInterfaceRequest with a new net of selected columns.
///
/// // SELECT id, email FROM persons
/// var request = Person.all()
/// // SELECT id, email FROM players
/// var request = Player.all()
/// request = request.select(sql: "id, email")
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM persons
/// // SELECT email FROM players
/// request
/// .select(sql: "id")
/// .select(sql: "email")
@@ -82,12 +84,12 @@ extension QueryInterfaceRequest {
/// A new QueryInterfaceRequest which returns distinct rows.
///
/// // SELECT DISTINCT * FROM persons
/// var request = Person.all()
/// // SELECT DISTINCT * FROM players
/// var request = Player.all()
/// request = request.distinct()
///
/// // SELECT DISTINCT name FROM persons
/// var request = Person.select(Column("name"))
/// // SELECT DISTINCT name FROM players
/// var request = Player.select(Column("name"))
/// request = request.distinct()
public func distinct() -> QueryInterfaceRequest<T> {
var query = self.query
@@ -98,8 +100,8 @@ extension QueryInterfaceRequest {
/// A new QueryInterfaceRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
///
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
/// var request = Person.all()
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
/// var request = Player.all()
/// request = request.filter(Column("email") == "arthur@example.com")
public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
var query = self.query
@@ -114,8 +116,8 @@ extension QueryInterfaceRequest {
/// A new QueryInterfaceRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
///
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
/// var request = Person.all()
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
/// var request = Player.all()
/// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"])
public func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
return filter(SQLExpressionLiteral(sql, arguments: arguments))
@@ -158,15 +160,16 @@ extension QueryInterfaceRequest {
/// A new QueryInterfaceRequest with the provided *orderings*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.all()
/// // SELECT * FROM players ORDER BY name
/// var request = Player.all()
/// request = request.order(Column("name"))
///
/// Any previous ordering is replaced:
///
/// // SELECT * FROM persons ORDER BY name
/// // SELECT * FROM players ORDER BY name
/// request
/// .order(Column("email"))
/// .reversed()
/// .order(Column("name"))
public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<T> {
return order(orderings)
@@ -174,31 +177,33 @@ extension QueryInterfaceRequest {
/// A new QueryInterfaceRequest with the provided *orderings*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.all()
/// // SELECT * FROM players ORDER BY name
/// var request = Player.all()
/// request = request.order([Column("name")])
///
/// Any previous ordering is replaced:
///
/// // SELECT * FROM persons ORDER BY name
/// // SELECT * FROM players ORDER BY name
/// request
/// .order([Column("email")])
/// .reversed()
/// .order([Column("name")])
public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<T> {
var query = self.query
query.orderings = orderings
query.isReversed = false
return QueryInterfaceRequest(query: query)
}
/// A new QueryInterfaceRequest with the provided *sql* used for sorting.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.all()
/// // SELECT * FROM players ORDER BY name
/// var request = Player.all()
/// request = request.order(sql: "name")
///
/// Any previous ordering is replaced:
///
/// // SELECT * FROM persons ORDER BY name
/// // SELECT * FROM players ORDER BY name
/// request
/// .order(sql: "email")
/// .order(sql: "name")
@@ -208,8 +213,8 @@ extension QueryInterfaceRequest {
/// A new QueryInterfaceRequest sorted in reversed order.
///
/// // SELECT * FROM persons ORDER BY name DESC
/// var request = Person.all().order(Column("name"))
/// // SELECT * FROM players ORDER BY name DESC
/// var request = Player.all().order(Column("name"))
/// request = request.reversed()
public func reversed() -> QueryInterfaceRequest<T> {
var query = self.query
@@ -220,8 +225,8 @@ extension QueryInterfaceRequest {
/// A QueryInterfaceRequest which fetches *limit* rows, starting
/// at *offset*.
///
/// // SELECT * FROM persons LIMIT 1
/// var request = Person.all()
/// // SELECT * FROM players LIMIT 1
/// var request = Player.all()
/// request = request.limit(1)
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<T> {
var query = self.query
@@ -230,19 +235,7 @@ extension QueryInterfaceRequest {
}
}
extension QueryInterfaceRequest {
// MARK: Counting
/// The number of rows matched by the request.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
return try query.countRequest.fetchOne(db)!
}
}
extension QueryInterfaceRequest {
extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
// MARK: Deleting
@@ -264,22 +257,14 @@ extension TableMapping {
/// Creates a QueryInterfaceRequest which fetches all records.
///
/// // SELECT * FROM persons
/// var request = Person.all()
/// // SELECT * FROM players
/// let request = Player.all()
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons
/// var request = Person.all()
/// 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 all() -> QueryInterfaceRequest<Self> {
let selection: [SQLSelectable]
if selectsRowID {
selection = [star, Column.rowID]
} else {
selection = [star]
}
return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: selection, from: .table(name: databaseTableName, alias: nil)))
return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: databaseSelection, from: .table(name: databaseTableName, alias: nil)))
}
/// Creates a QueryInterfaceRequest which fetches no record.
@@ -289,52 +274,48 @@ extension TableMapping {
/// Creates a QueryInterfaceRequest which selects *selection*.
///
/// // SELECT id, email FROM persons
/// var request = Person.select(Column("id"), Column("email"))
/// // SELECT id, email FROM players
/// let request = Player.select(Column("id"), Column("email"))
public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest<Self> {
return all().select(selection)
}
/// Creates a QueryInterfaceRequest which selects *selection*.
///
/// // SELECT id, email FROM persons
/// var request = Person.select([Column("id"), Column("email")])
/// // SELECT id, email FROM players
/// let request = Player.select([Column("id"), Column("email")])
public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<Self> {
return all().select(selection)
}
/// Creates a QueryInterfaceRequest which selects *sql*.
///
/// // SELECT id, email FROM persons
/// var request = Person.select(sql: "id, email")
/// // SELECT id, email FROM players
/// let request = Player.select(sql: "id, email")
public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
return all().select(sql: sql, arguments: arguments)
}
/// Creates a QueryInterfaceRequest with the provided *predicate*.
///
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
/// var request = Person.filter(Column("email") == "arthur@example.com")
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
/// let request = Player.filter(Column("email") == "arthur@example.com")
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons WHERE email = 'arthur@example.com'
/// var request = Person.filter(Column("email") == "arthur@example.com")
/// 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(_ predicate: SQLExpressible) -> QueryInterfaceRequest<Self> {
return all().filter(predicate)
}
/// Creates a QueryInterfaceRequest with the provided *predicate*.
///
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
/// var request = Person.filter(sql: "email = ?", arguments: ["arthur@example.com"])
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
/// let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"])
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons WHERE email = 'arthur@example.com'
/// var request = Person.filter(sql: "email = ?", arguments: ["arthur@example.com"])
/// 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(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
return all().filter(sql: sql, arguments: arguments)
}
@@ -342,14 +323,12 @@ extension TableMapping {
/// Creates a QueryInterfaceRequest sorted according to the
/// provided *orderings*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.order(Column("name"))
/// // SELECT * FROM players ORDER BY name
/// let request = Player.order(Column("name"))
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons ORDER BY name
/// var request = Person.order(Column("name"))
/// 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 order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<Self> {
return all().order(orderings)
}
@@ -357,28 +336,24 @@ extension TableMapping {
/// Creates a QueryInterfaceRequest sorted according to the
/// provided *orderings*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.order([Column("name")])
/// // SELECT * FROM players ORDER BY name
/// let request = Player.order([Column("name")])
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons ORDER BY name
/// var request = Person.order([Column("name")])
/// 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 order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<Self> {
return all().order(orderings)
}
/// Creates a QueryInterfaceRequest sorted according to *sql*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.order(sql: "name")
/// // SELECT * FROM players ORDER BY name
/// let request = Player.order(sql: "name")
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons ORDER BY name
/// var request = Person.order(sql: "name")
/// 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 order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
return all().order(sql: sql, arguments: arguments)
}
@@ -386,14 +361,12 @@ extension TableMapping {
/// Creates a QueryInterfaceRequest which fetches *limit* rows, starting at
/// *offset*.
///
/// // SELECT * FROM persons LIMIT 1
/// var request = Person.limit(1)
/// // SELECT * FROM players LIMIT 1
/// let request = Player.limit(1)
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons LIMIT 1
/// var request = Person.limit(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 limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<Self> {
return all().limit(limit, offset: offset)
}
@@ -59,7 +59,59 @@ struct QueryInterfaceSelectQueryDefinition {
sql += " HAVING " + havingExpression.expressionSQL(&arguments)
}
var orderings = self.orderings
let orderings = self.queryOrderings
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ")
}
if let limit = limit {
sql += " LIMIT " + limit.sql
}
return sql
}
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
guard groupByExpressions.isEmpty else {
// Programmer error
fatalError("Can't delete query with GROUP BY expression")
}
guard havingExpression == nil else {
// Programmer error
fatalError("Can't delete query with GROUP BY expression")
}
var sql = "DELETE"
var arguments: StatementArguments? = StatementArguments()
if let source = source {
sql += " FROM " + source.sourceSQL(&arguments)
}
if let whereExpression = whereExpression {
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
}
if let limit = limit {
let orderings = self.queryOrderings
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ")
}
if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") {
sql += " LIMIT " + limit.sql
} else {
fatalError("Can't delete query with limit")
}
}
let statement = try db.makeUpdateStatement(sql)
statement.arguments = arguments!
return statement
}
private var queryOrderings: [SQLOrderingTerm] {
if isReversed {
if orderings.isEmpty {
// https://www.sqlite.org/lang_createtable.html#rowid
@@ -74,25 +126,35 @@ struct QueryInterfaceSelectQueryDefinition {
// Here we assume that rowid is not a custom column.
// TODO: support for user-defined rowid column.
// TODO: support for WITHOUT ROWID tables.
orderings = [Column.rowID.desc]
return [Column.rowID.desc]
} else {
orderings = orderings.map { $0.reversed }
return orderings.map { $0.reversed }
}
} else {
return orderings
}
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ")
}
if let limit = limit {
sql += " LIMIT " + limit.sql
}
return sql
}
/// Returns a fetch request that counts the number of rows matched by self.
var countRequest: AnyTypedRequest<Int> {
return countQuery.bound(to: Int.self)
/// Remove ordering
var unorderedQuery: QueryInterfaceSelectQueryDefinition {
var query = self
query.isReversed = false
query.orderings = []
return query
}
}
extension QueryInterfaceSelectQueryDefinition : Request {
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
var arguments: StatementArguments? = StatementArguments()
let sql = self.sql(&arguments)
let statement = try db.makeSelectStatement(sql)
try statement.setArgumentsWithValidation(arguments!)
return (statement, nil)
}
func fetchCount(_ db: Database) throws -> Int {
return try Int.fetchOne(db, countQuery)!
}
private var countQuery: QueryInterfaceSelectQueryDefinition {
@@ -102,19 +164,19 @@ struct QueryInterfaceSelectQueryDefinition {
return trivialCountQuery
}
guard let source = source, case .table(name: let tableName, alias: let alias) = source else {
guard let source = source, case .table = source else {
// SELECT ... FROM (something which is not a table)
return trivialCountQuery
}
assert(!selection.isEmpty)
if selection.count == 1 {
guard let selectable = self.selection[0].countingSelectable(distinct: isDistinct, from: tableName, aliased: alias) else {
guard let count = self.selection[0].count(distinct: isDistinct) else {
return trivialCountQuery
}
var countQuery = unorderedQuery
countQuery.isDistinct = false
countQuery.selection = [selectable]
countQuery.selection = [count.sqlSelectable]
return countQuery
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
@@ -122,62 +184,22 @@ struct QueryInterfaceSelectQueryDefinition {
guard !isDistinct else {
return trivialCountQuery
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
var countQuery = unorderedQuery
countQuery.selection = [SQLExpressionCount(star)]
countQuery.selection = [SQLExpressionCount(AllColumns())]
return countQuery
}
}
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
guard groupByExpressions.isEmpty else {
// Programmer error
fatalError("Can't delete query with GROUP BY expression")
}
guard havingExpression == nil else {
// Programmer error
fatalError("Can't delete query with GROUP BY expression")
}
guard limit == nil else {
// Programmer error
fatalError("Can't delete query with limit")
}
var sql = "DELETE"
var arguments: StatementArguments? = StatementArguments()
if let source = source {
sql += " FROM " + source.sourceSQL(&arguments)
}
if let whereExpression = whereExpression {
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
}
let statement = try db.makeUpdateStatement(sql)
statement.arguments = arguments!
return statement
}
// SELECT COUNT(*) FROM (self)
private var trivialCountQuery: QueryInterfaceSelectQueryDefinition {
return QueryInterfaceSelectQueryDefinition(
select: [SQLExpressionCount(star)],
select: [SQLExpressionCount(AllColumns())],
from: .query(query: unorderedQuery, alias: nil))
}
/// Remove ordering
private var unorderedQuery: QueryInterfaceSelectQueryDefinition {
var query = self
query.isReversed = false
query.orderings = []
return query
}
}
indirect enum SQLSource {
@@ -214,3 +236,14 @@ struct SQLLimit {
}
}
}
extension SQLCount {
var sqlSelectable: SQLSelectable {
switch self {
case .all:
return SQLExpressionCount(AllColumns())
case .distinct(let expression):
return SQLExpressionCountDistinct(expression)
}
}
}
@@ -5,8 +5,8 @@
///
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
///
/// // SELECT * FROM persons WHERE email = 'arthur@example.com' COLLATE NOCASE
/// Persons.filter(email == "arthur@example.com")
/// // SELECT * FROM players WHERE email = 'arthur@example.com' COLLATE NOCASE
/// Players.filter(email == "arthur@example.com")
public struct SQLCollatedExpression {
/// The tainted expression
public let expression: SQLExpression
@@ -18,8 +18,8 @@ public struct SQLCollatedExpression {
///
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
///
/// // SELECT * FROM persons ORDER BY email COLLATE NOCASE ASC
/// Persons.order(email.asc)
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE ASC
/// Players.order(email.asc)
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var asc: SQLOrderingTerm {
@@ -30,8 +30,8 @@ public struct SQLCollatedExpression {
///
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
///
/// // SELECT * FROM persons ORDER BY email COLLATE NOCASE DESC
/// Persons.order(email.desc)
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE DESC
/// Players.order(email.desc)
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var desc: SQLOrderingTerm {
@@ -47,3 +47,16 @@ public struct SQLCollatedExpression {
return SQLExpressionCollate(expression, collationName: collationName)
}
}
extension SQLCollatedExpression : SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var reversed: SQLOrderingTerm {
return desc
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.orderingTermSQL(&arguments)
}
}
+6 -21
View File
@@ -1,20 +1,10 @@
// MARK: - SQLCollection
/// This protocol is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLCollection is the protocol for types that can be checked for inclusion.
public protocol SQLCollection {
/// This function is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an SQL string that represents the collection.
///
@@ -34,14 +24,10 @@ public protocol SQLCollection {
/// arguments // [1,2,3]
func collectionSQL(_ arguments: inout StatementArguments?) -> String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an expression that check whether the collection contains
/// the expression.
///
/// The default implementation returns a SQLExpressionContains which applies
/// the `IN` operator:
///
/// let request = Person.select(Column("id"))
/// request.contains(Column("id")) // id IN (SELECT id FROM persons)
func contains(_ value: SQLExpressible) -> SQLExpression
}
@@ -49,10 +35,9 @@ public protocol SQLCollection {
// MARK: Default Implementations
extension SQLCollection {
/// Returns a SQLExpressionContains which applies the `IN` operator:
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// let request = Person.select(Column("id"))
/// request.contains(Column("id")) // id IN (SELECT id FROM persons)
/// Returns a SQLExpressionContains which applies the `IN` SQL operator.
public func contains(_ value: SQLExpressible) -> SQLExpression {
return SQLExpressionContains(value, self)
}
Loaded 100 of 431 files, more files were not shown because too many files have changed in this diff. Show more