Compare commits

...
155 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
199 changed files with 8658 additions and 13328 deletions

No files matched your search

+1 -1
View File
@@ -106,7 +106,7 @@ Pods
# SPM
.build
Package.pins
Package.resolved
Tests/SPM/Packages
# Ruby
+1 -1
View File
@@ -1 +1 @@
3.1
4.0
+38 -38
View File
@@ -12,98 +12,98 @@ jobs:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 8.3)
# Test GRDBOSX (Xcode 9)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBOSX (Xcode 8.3, macOS 10.12)
- TID=GRDBOSX (Xcode 9, macOS 10.12)
script: make test_framework_GRDBOSX
# Test GRDBWatchOS (Xcode 8.3)
# Test GRDBWatchOS (Xcode 9)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBWatchOS (Xcode 8.3, watchOS)
- TID=GRDBWatchOS (Xcode 9, watchOS)
script: make test_framework_GRDBWatchOS
# Test GRDBiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
# Test GRDBiOS (Xcode 9, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBiOS (Xcode 8.3, iOS <MAX>)
- TID=GRDBiOS (Xcode 9, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget
# Test GRDBiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
# Test GRDBiOS (Xcode 9, iOS <MINIMUM VERSION>))
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBiOS (Xcode 8.3, iOS <MIN>)
- TID=GRDBiOS (Xcode 9, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 8.3, macOS 10.12)
# Test GRDB [SPM] (Xcode 9, macOS 10.12)
- stage: Test GRDB
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDB [SPM] (Xcode 8.3, macOS 10.12)
- TID=GRDB [SPM] (Xcode 9, macOS 10.12)
script: make test_SPM
###########################################
## Test GRDB (Custom SQLite)
# Test GRDBCustomSQLiteOSX (Xcode 8.3)
# Test GRDBCustomSQLiteOSX (Xcode 9)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteOSX (Xcode 8.3, macOS 10.12)
- TID=GRDBCustomSQLiteOSX (Xcode 9, macOS 10.12)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAX>)
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MINIMUM VERSION>))
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MIN>)
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test GRDB (SQLCipher)
# Test GRDBCipherOSX (Xcode 8.3)
# Test GRDBCipherOSX (Xcode 9)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBCipherOSX (Xcode 8.3, macOS 10.12)
- TID=GRDBCipherOSX (Xcode 9, macOS 10.12)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
# Test GRDBCipheriOS (Xcode 9, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MAX>)
- TID=GRDBCipheriOS (Xcode 9, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 8.3, iOS <MINIMUM VERSION>))
# Test GRDBCipheriOS (Xcode 9, iOS <MINIMUM VERSION>))
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MIN>)
- TID=GRDBCipheriOS (Xcode 9, iOS <MIN>)
script: make test_framework_GRDBCipheriOS_minTarget
###########################################
@@ -112,7 +112,7 @@ jobs:
# Manual Install
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=Manual Install
script: make test_install_manual
@@ -120,14 +120,14 @@ jobs:
# Manual Install (GRDBCipher)
- stage: Test Installation
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=Manual Install (GRDBCipher)
script: make test_install_GRDBCipher
# Cocoapods Lint
- stage: Test Installation
osx_image: xcode8.3
osx_image: xcode9
install:
- gem install cocoapods # Since Travis is not always on latest version
env:
@@ -136,7 +136,7 @@ jobs:
# SPM Install
- stage: Test Installation
osx_image: xcode8.3
osx_image: xcode9
env:
- TID=SPM
script: make test_install_SPM
@@ -144,7 +144,7 @@ jobs:
## The following doesn’t work, as `make test_CarthageBuild` does not yet work.
## Carthage Build
#- stage: Carthage
# osx_image: xcode8.3
# osx_image: xcode9
# before_install:
# - brew update
# - brew outdated carthage || brew upgrade carthage
+392 -2
View File
@@ -1,6 +1,396 @@
Release Notes
=============
## 2.0
Released September 16, 2017
**GRDB 2.0 brings support for Swift 4.** Notable changes are:
- **Use subscript notation when extracting row values** ([documentation](https://github.com/groue/GRDB.swift#column-values)):
```swift
let name: String = row[0] // 0 is the leftmost column
let name: String = row["name"] // Leftmost matching column - lookup is case-insensitive
let name: String = row[Column("name")] // Using query interface's Column
```
- **Support for the `Codable` protocol** ([documentation](https://github.com/groue/GRDB.swift#codable-records))
Record types that adopt the standard `Codable` protocol are granted with automatic adoption of GRDB record protocols. This means that you no longer have to write boilerplate code :tada::
```swift
struct Player : RowConvertible, Persistable, Codable {
static let databaseTableName = "players"
let name: String
let score: Int
}
// Automatically derived:
//
// extension Player {
// init(row: Row) {
// name = row["name"]
// score = row["score"]
// }
//
// func encode(to container: inout PersistenceContainer) {
// container["name"] = name
// container["score"] = score
// }
// }
try dbQueue.inDatabase { db in
let arthur = Player(name: "Arthur", score: 100)
try arthur.insert(db)
let players = try Player.fetchAll(db) // [Players]
}
```
- **Records can now specify the columns they feed from** ([documentation](https://github.com/groue/GRDB.swift#columns-selected-by-a-request)).
In previous versions of GRDB, `SELECT *` was the norm. GRDB 2.0 introduces `databaseSelection`, which allows any type to define its preferred set of columns:
```swift
struct Player : RowConvertible, TableMapping {
let id: Int64
let name: String
enum Columns {
static let id = Column("id")
static let name = Column("name")
}
init(row: Row) {
id = row[Columns.id]
name = row[Columns.name]
}
static let databaseTableName = "players"
static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name]
}
// SELECT id, name FROM players
let players = Player.fetchAll(db)
```
- **Record protocols have more precise semantics**: RowConvertible *reads database rows*, TableMapping *builds SQL requests*, and Persistable *writes* ([documentation](https://github.com/groue/GRDB.swift#record-protocols-overview)).
This means that with GRDB 2.0, being able to write `Player.fetchAll(db)` does not imply that `Player.deleteAll(db)` is available: you have a better control on the abilities of your record types.
### Fixed
- GRDB is now able to store and load zero-length blobs.
### New
New features have been added in order to plug a few holes and support the [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](http://github.com/groue/GRDBObjc) companion projects:
- Persistable records can export themselves as dictionaries:
```swift
let player = try Player.fetchOne(db, key: 1)
let dict = player.databaseDictionary // [String: DatabaseValue]
print(dict)
// Prints {"id": 1, "name": "Arthur", "score": 1000}
```
- Query interface requests learned how to limit the number of deleted rows:
```swift
// Delete the worse ten players:
// DELETE FROM players ORDER BY score LIMIT 10
let request = Player.order(scoreColumn).limit(10)
try request.deleteAll(db)
```
- Prepared statements know the index of their columns:
```swift
let statement = try db.makeSelectStatement("SELECT a, b FROM t")
statement.index(ofColumn: "b") // 1
```
- Row cursors (of type RowCursor) expose their underlying statement:
```swift
let rows = try Row.fetchCursor(db, "SELECT ...")
let statement = rows.statement
```
- One can build a Set from a cursor:
```swift
let strings = try Set(String.fetchCursor(...))
```
- The new `AnyDatabaseReader` and `AnyDatabaseWriter` type erasers help dealing with the `DatabaseReader` and `DatabaseWriter` protocols.
### Breaking Changes
- Requirements have changed: Xcode 9+ / Swift 4
- WatchOS extension targets no longer need `libsqlite3.tbd` to be added to the *Linked Frameworks and Libraries* section of their *General* tab.
- The `Row.value` method has been replaced with subscript notation:
```diff
-row.value(atIndex: 0)
-row.value(named: "id")
-row.value(Column("id"))
+row[0]
+row["id"]
+row[Column("id")]
```
- Date and NSDate now interpret numerical database values as timestamps that fuel `Date(timeIntervalSince1970:)`. Previous version of GRDB would interpret numbers as [julian days](https://en.wikipedia.org/wiki/Julian_day) (a date representation supported by SQLite). Support for julian days remains, with the `Date(julianDay:)` initializer.
- All `TableMapping` methods that would modify the database have moved to `MutablePersistable`, now the only record protocol that is able to write.
- The `TableMapping.selectsRowID` property has been replaced with `TableMapping.databaseSelection`.
To upgrade, replace:
```diff
struct Player: TableMapping {
- static let selectsRowID = true
+ static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
}
```
- The `DatabaseCursor` type has been removed, and replaced with several concrete types that all adopt the `Cursor` protocol. Those new types allow dedicated optimizations depending on the type of the fetched elements.
If your application has code that depends on `DatabaseCursor`, make it target the new concrete types, or make it generic on the `Cursor` protocol, just like you'd write generic methods on the Swift `Sequence` protocol.
- `RowConvertible.fetchCursor(_:keys:)` returns a non-optional cursor.
- `Database.primaryKey(_:)` returns a non-optional PrimaryKeyInfo. When a table has no explicit primary key, the result is the hidden rowid column.
- The deprecated `TableMapping.primaryKeyRowComparator` method has been removed.
### Documentation diff
- [WatchOS installation procedure](https://github.com/groue/GRDB.swift#installation) has been updated with new instructions.
- The [introduction to multithreading with database pools](https://github.com/groue/GRDB.swift#database-pools) has been enhanced.
- The [Rows as Dictionaries](https://github.com/groue/GRDB.swift#rows-as-dictionaries) chapter has been enhanced with instructions for converting a row into a dictionary.
- The [description of cursors](https://github.com/groue/GRDB.swift#cursors) better explains how to choose between a cursor and an array.
- The [Date and DateComponents](https://github.com/groue/GRDB.swift#date-and-datecomponents) chapter has been updated for the new support for unix timestamps.
- The [Fatal Errors](https://github.com/groue/GRDB.swift#fatal-errors) chapter has an enhanced description of value conversion errors and how to handle them.
- The [Usage of raw SQLite pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers) chapter has been updated for the new `SQLite3` standard module that comes with Swift4.
- A new [Record Protocols Overview](https://github.com/groue/GRDB.swift#record-protocols-overview) chapter has been added.
- A new [Codable Records](https://github.com/groue/GRDB.swift#codable-records) chapter has been added.
- A new [Columns Selected by a Request](https://github.com/groue/GRDB.swift#columns-selected-by-a-request) chapter describes the new `TableMapping.databaseSelection` property.
- The [Exposing the RowID Column](https://github.com/groue/GRDB.swift#exposing-the-rowid-column) chapter has been updated for the new `TableMapping.databaseSelection` property.
### API diff
```diff
class Row {
- func value(atIndex index: Int) -> DatabaseValueConvertible?
- func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value?
- func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value
- func value(named columnName: String) -> DatabaseValueConvertible?
- func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value?
- func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value
- func value(_ column: Column) -> DatabaseValueConvertible?
- func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value?
- func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value
+ subscript(_ index: Int) -> DatabaseValueConvertible?
+ subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value?
+ subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value
+ subscript(_ columnName: String) -> DatabaseValueConvertible?
+ subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value?
+ subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value
+ subscript(_ column: Column) -> DatabaseValueConvertible?
+ subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value?
+ subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value
}
class SelectStatement {
+ func index(ofColumn columnName: String) -> Int?
}
+extension MutablePersistable {
+ var databaseDictionary: [String: DatabaseValue]
+}
-extension TableMapping {
+extension MutablePersistable {
@discardableResult static func deleteAll(_ db: Database) throws -> Int
@discardableResult static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible
@discardableResult static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool
@discardableResult static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int
@discardableResult static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool
}
-extension QueryInterfaceRequest {
+extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
@discardableResult func deleteAll(_ db: Database) throws -> Int
}
protocol TableMapping {
- static var selectsRowID: Bool { get }
+ static var databaseSelection: [SQLSelectable] { get }
}
class Record {
- open class var selectsRowID: Bool
+ open class var databaseSelection: [SQLSelectable]
}
+struct AllColumns {
+ init()
+}
class Database {
- func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo?
+ func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo
}
struct PrimaryKeyInfo {
+ var isRowID: Bool { get }
}
+extension Set {
+ init<C: Cursor>(_ cursor: C) throws where C.Element == Element
+}
-final class DatabaseCursor { }
+final class ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
+ typealias Element = Value
+}
+final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
+ typealias Element = Value
+}
+final class NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
+ typealias Element = Value?
+}
+final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
+ typealias Element = Value?
+}
+final class RecordCursor<Record: RowConvertible> : Cursor {
+ typealias Element = Record
+}
+final class RowCursor : Cursor {
+ typealias Element = Row
+ let statement: SelectStatement
+}
extension DatabaseValueConvertible {
- static func fetchCursor(...) throws -> DatabaseCursor<Self>
+ static func fetchCursor(...) throws -> DatabaseValueCursor<Self>
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
+ static func fetchCursor(...) throws -> ColumnCursor<Self>
}
extension Optional where Wrapped: DatabaseValueConvertible {
- static func fetchCursor(...) throws -> DatabaseCursor<Wrapped?>
+ static func fetchCursor(...) throws -> NullableDatabaseValueCursor<Wrapped>
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
+ static func fetchCursor(...) throws -> NullableColumnCursor<Wrapped>
}
extension Row {
- static func fetchCursor(...) throws -> DatabaseCursor<Row>
+ static func fetchCursor(...) throws -> RowCursor
}
extension RowConvertible where Self: TableMapping {
- static func fetchCursor(...) throws -> DatabaseCursor<Self>?
+ static func fetchCursor(...) throws -> RecordCursor<Self>
}
extension TypedRequest where RowDecoder: RowConvertible {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
+ func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?>
+ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
+ func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped>
}
extension TypedRequest where RowDecoder: Row {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row>
+ func fetchCursor(_ db: Database) throws -> RowCursor
}
extension TableMapping {
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
}
+final class AnyDatabaseReader : DatabaseReader {
+ init(_ base: DatabaseReader)
+}
+final class AnyDatabaseWriter : DatabaseWriter {
+ init(_ base: DatabaseWriter)
+}
```
### Experimental API diff
```diff
enum SQLCount {
- case star
+ case all
}
```
## 1.3.0
Released August 18, 2017
**New**
- Upgrade custom SQLite builds to [v3.20.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- Complete support for all signed and unsigned integer types: from Int8 toUInt64, all integers can be stored and loaded from the database.
**API diff**
```diff
+extension Int8: DatabaseValueConvertible, StatementColumnConvertible { }
+extension Int16: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt8: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt16: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt32: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt64: DatabaseValueConvertible, StatementColumnConvertible { }
+extension UInt: DatabaseValueConvertible, StatementColumnConvertible { }
```
## 1.2.2
Released July 20, 2017
**Fixed**
- The `Configuration.trace` function no longer leaks memory.
## 1.2.1
Released July 19, 2017
**Fixed**
- Upgrade custom SQLite builds to [v3.19.3](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
- The [Query Interface](https://github.com/groue/GRDB.swift/#the-query-interface) now generates `IS NULL` SQL snippets for comparisons with `DatabaseValue.null`:
```swift
// SELECT * FROM players WHERE email IS NULL
Player.filter(Column("email") == DatabaseValue.null)
```
It used to generate `= NULL` which would not behave as expected.
## 1.2
Released July 13, 2017
@@ -1110,7 +1500,7 @@ Released September 16, 2016
```diff
-let dbValue = row.databaseValue(atIndex: 0)
+let dbValue: DatabaseValue = row.value(atIndex: 0)
+let dbValue: DatabaseValue = row[0]
```
@@ -1466,7 +1856,7 @@ Released September 16, 2016
```diff
-let dbValue = row.databaseValue(atIndex: 0)
+let dbValue: DatabaseValue = row.value(atIndex: 0)
+let dbValue: DatabaseValue = row[0]
```
@@ -1,11 +1,3 @@
//
// ExtensionDelegate.swift
// GRDBDemoWatchOS Extension
//
// Created by Gwendal Roué on 03/04/2017.
// Copyright © 2017 Gwendal Roué. All rights reserved.
//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
@@ -1,14 +1,7 @@
//
// InterfaceController.swift
// GRDBDemoWatchOS Extension
//
// Created by Gwendal Roué on 03/04/2017.
// Copyright © 2017 Gwendal Roué. All rights reserved.
//
import WatchKit
import Foundation
import GRDB
import SQLite3
class InterfaceController: WKInterfaceController {
@@ -7,7 +7,6 @@
objects = {
/* Begin PBXBuildFile section */
5657C36E1E926B05008402E8 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 5657C36D1E926B05008402E8 /* libsqlite3.tbd */; };
568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; };
568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; };
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
@@ -243,7 +242,6 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
5657C36D1E926B05008402E8 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/WatchOS.platform/Developer/SDKs/WatchOS3.2.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; };
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = "<group>"; };
568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
@@ -273,7 +271,6 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
5657C36E1E926B05008402E8 /* libsqlite3.tbd in Frameworks */,
568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -289,14 +286,6 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
5657C36C1E926B05008402E8 /* Frameworks */ = {
isa = PBXGroup;
children = (
5657C36D1E926B05008402E8 /* libsqlite3.tbd */,
);
name = Frameworks;
sourceTree = "<group>";
};
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */ = {
isa = PBXGroup;
children = (
@@ -326,7 +315,6 @@
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
56B036041E8D9EBE003B6DA4 /* Products */,
5657C36C1E926B05008402E8 /* Frameworks */,
);
sourceTree = "<group>";
};
@@ -459,7 +447,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0830;
LastUpgradeCheck = 0830;
LastUpgradeCheck = 0900;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
568E5FBE1E926430002582E0 = {
@@ -755,7 +743,6 @@
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
@@ -772,7 +759,6 @@
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
@@ -790,7 +776,6 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
@@ -808,7 +793,6 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = 4;
WATCHOS_DEPLOYMENT_TARGET = 3.2;
};
@@ -824,7 +808,9 @@
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
@@ -832,7 +818,11 @@
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
@@ -855,12 +845,12 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 4.0;
};
name = Debug;
};
@@ -874,7 +864,9 @@
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
@@ -882,7 +874,11 @@
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
@@ -899,10 +895,10 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 4.0;
VALIDATE_PRODUCT = YES;
};
name = Release;
@@ -917,7 +913,6 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -931,7 +926,6 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
};
name = Release;
};
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0730"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -18,9 +18,9 @@ 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)
}
+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.19.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 v1.2
cd [GRDB directory]
git checkout v2.0
git submodule update --init SQLiteCustom/src
````
+8 -8
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,8 +112,8 @@ 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)
}
@@ -497,7 +497,7 @@ Build a `value BETWEEN min AND max` expression from Swift ranges:
#### The COUNT Function
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/1.2/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.2/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)
@@ -588,4 +588,4 @@ You may want to compare it to another protocol, SQLSpecificExpressible, which ha
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/1.2/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.
-1
View File
@@ -10,7 +10,6 @@ To release a new GRDB version:
- Build and run GRDBDemoiOS in Release configuration on a device
- Archive GRDBDemoiOS
- Check for performance regression with GRDBOSXPerformanceTests
- On SDK upgrade, update Support/sqlite3.h
- 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:
+2 -2
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '1.2'
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/**/*.swift', 'Support/*.{c,h}'
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
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
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"
@@ -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>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0730"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -10,6 +10,7 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -30,6 +31,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -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"
+2 -1
View File
@@ -1,7 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Configuration for a DatabaseQueue or DatabasePool.
+13
View File
@@ -11,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
+238 -180
View File
@@ -1,7 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A raw SQLite connection, suitable for the SQLite C API.
@@ -121,7 +122,7 @@ public final class Database {
/// An SQL column type.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("id", .integer).primaryKey()
/// t.column("title", .text)
/// }
@@ -212,7 +213,7 @@ public final class Database {
/// The states that keep track of transaction completions in order to notify
/// transaction observers.
fileprivate enum TransactionHookState {
private enum TransactionHookState {
case pending
case commit
case rollback
@@ -254,6 +255,9 @@ public final class Database {
// MARK: - Database Information
/// The list of compile options used when building SQLite
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase { try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS")) }
/// The database configuration
public let configuration: Configuration
@@ -294,29 +298,37 @@ public final class Database {
var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
/// True if the database connection is currently in a transaction.
public var isInsideTransaction: Bool { return isInsideExplicitTransaction || !savepointStack.isEmpty }
/// Set by BEGIN/ROLLBACK/COMMIT transaction statements.
fileprivate var isInsideExplicitTransaction: Bool = false
public var isInsideTransaction: Bool {
// https://sqlite.org/c3ref/get_autocommit.html
//
// > The sqlite3_get_autocommit() interface returns non-zero or zero if
// > the given database connection is or is not in autocommit mode,
// > respectively.
//
// > Autocommit mode is on by default. Autocommit mode is disabled by a
// > BEGIN statement. Autocommit mode is re-enabled by a COMMIT
// > or ROLLBACK.
return sqlite3_get_autocommit(sqliteConnection) == 0
}
/// Set by SAVEPOINT/COMMIT/ROLLBACK/RELEASE savepoint statements.
fileprivate var savepointStack = SavepointStack()
private var savepointStack = SavepointStack()
/// Traces transaction hooks
fileprivate var transactionHookState: TransactionHookState = .pending
private var transactionHookState: TransactionHookState = .pending
/// Transaction observers
fileprivate var transactionObservers = [ManagedTransactionObserver]()
fileprivate var activeTransactionObservers = [ManagedTransactionObserver]() // subset of transactionObservers, set in updateStatementWillExecute
private var transactionObservers = [ManagedTransactionObserver]()
private var activeTransactionObservers = [ManagedTransactionObserver]() // subset of transactionObservers, set in updateStatementWillExecute
/// See setupBusyMode()
private var busyCallback: BusyCallback?
/// Available functions
fileprivate var functions = Set<DatabaseFunction>()
private var functions = Set<DatabaseFunction>()
/// Available collations
fileprivate var collations = Set<DatabaseCollation>()
private var collations = Set<DatabaseCollation>()
/// Schema Cache
var schemaCache: DatabaseSchemaCache // internal so that it can be tested
@@ -333,8 +345,8 @@ public final class Database {
case grdb
case user
}
fileprivate lazy var grdbStatementCache: StatementCache = StatementCache(database: self)
fileprivate lazy var userStatementCache: StatementCache = StatementCache(database: self)
private lazy var grdbStatementCache: StatementCache = StatementCache(database: self)
private lazy var userStatementCache: StatementCache = StatementCache(database: self)
init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws {
// Error log setup must happen before any database connection
@@ -463,7 +475,7 @@ public final class Database {
guard configuration.trace != nil else {
return
}
let dbPointer = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 http://www.sqlite.org/changes.html#version_3_14
// It is available from iOS 10.0 and OS X 10.12 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE
@@ -471,15 +483,16 @@ public final class Database {
guard let stmt = stmt else { return SQLITE_OK }
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
let sql = String(cString: expandedSQLCString)
let database = unsafeBitCast(dbPointer, to: Database.self)
database.configuration.trace!(sql)
sqlite3_free(expandedSQLCString)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
return SQLITE_OK
}, dbPointer)
#elseif GRDBCIPHER
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map({ String(cString: $0) }) else { return }
let database = unsafeBitCast(dbPointer, to: Database.self)
database.configuration.trace!(sql)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
#else
if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) {
@@ -487,15 +500,16 @@ public final class Database {
guard let stmt = stmt else { return SQLITE_OK }
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
let sql = String(cString: expandedSQLCString)
let database = unsafeBitCast(dbPointer, to: Database.self)
database.configuration.trace!(sql)
sqlite3_free(expandedSQLCString)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
return SQLITE_OK
}, dbPointer)
} else {
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map({ String(cString: $0) }) else { return }
let database = unsafeBitCast(dbPointer, to: Database.self)
database.configuration.trace!(sql)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
}
#endif
@@ -512,12 +526,12 @@ public final class Database {
case .callback(let callback):
busyCallback = callback
let dbPointer = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_busy_handler(
sqliteConnection,
{ (dbPointer, numberOfTries) in
let database = unsafeBitCast(dbPointer, to: Database.self)
let callback = database.busyCallback!
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
let callback = db.busyCallback!
return callback(Int(numberOfTries)) ? 1 : 0
},
dbPointer)
@@ -545,10 +559,10 @@ public final class Database {
}
private func setupTransactionHooks() {
let dbPointer = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_commit_hook(sqliteConnection, { dbPointer in
let db = unsafeBitCast(dbPointer, to: Database.self)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
do {
try db.willCommit()
db.transactionHookState = .commit
@@ -563,7 +577,7 @@ public final class Database {
sqlite3_rollback_hook(sqliteConnection, { dbPointer in
let db = unsafeBitCast(dbPointer, to: Database.self)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
switch db.transactionHookState {
case .cancelledCommit:
// Next step: updateStatementDidFail()
@@ -675,7 +689,7 @@ extension Database {
/// Returns a new prepared statement that can be reused.
///
/// 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])!
///
@@ -683,12 +697,27 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
return try SelectStatement(database: self, sql: sql)
return try makeSelectStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?", prepFlags: 0)
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// - 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)
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement(database: self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -712,7 +741,7 @@ extension Database {
/// Returns a new prepared statement that can be reused.
///
/// 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"])
///
@@ -720,12 +749,27 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
return try UpdateStatement(database: self, sql: sql)
return try makeUpdateStatement(sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)", prepFlags: 0)
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - 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)
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement(database: self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedUpdateStatement("INSERT INTO persons (name) VALUES (?)")
/// let statement = try db.cachedUpdateStatement("INSERT INTO players (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -750,14 +794,14 @@ extension Database {
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(
/// "INSERT INTO persons (name) VALUES (:name)",
/// "INSERT INTO players (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try db.execute(
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);",
/// arguments; ['Arthur', 'Barbara', 'Craig'])
/// try db.execute("""
/// INSERT INTO players (name) VALUES (?);
/// INSERT INTO players (name) VALUES (?);
/// INSERT INTO players (name) VALUES (?);
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
///
/// This method may throw a DatabaseError.
///
@@ -897,14 +941,14 @@ extension Database {
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
let collationPointer = unsafeBitCast(collation, to: UnsafeMutableRawPointer.self)
let collationPointer = Unmanaged.passUnretained(collation).toOpaque()
let code = sqlite3_create_collation_v2(
sqliteConnection,
collation.name,
SQLITE_UTF8,
collationPointer,
{ (collationPointer, length1, buffer1, length2, buffer2) -> Int32 in
let collation = unsafeBitCast(collationPointer, to: DatabaseCollation.self)
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
return Int32(collation.function(length1, buffer1, length2, buffer2).rawValue)
}, nil)
guard code == SQLITE_OK else {
@@ -972,7 +1016,7 @@ extension DatabaseCollation : Hashable {
#if SQLITE_HAS_CODEC
extension Database {
fileprivate class func set(passphrase: String, forConnection sqliteConnection: SQLiteConnection) throws {
private class func set(passphrase: String, forConnection sqliteConnection: SQLiteConnection) throws {
let data = passphrase.data(using: .utf8)!
let code = data.withUnsafeBytes { bytes in
sqlite3_key(sqliteConnection, bytes, Int32(data.count))
@@ -1031,11 +1075,14 @@ extension Database {
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) != nil
}
/// The primary key for table named `tableName`; nil if table has no
/// primary key.
/// The primary key for table named `tableName`.
///
/// All tables have a primary key, even when it is not explicit. When a
/// table has no explicit primary key, the result is the hidden
/// "rowid" column.
///
/// - throws: A DatabaseError if table does not exist.
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo? {
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
SchedulingWatchdog.preconditionValidQueue(self)
if let primaryKey = schemaCache.primaryKey(tableName) {
@@ -1054,29 +1101,29 @@ extension Database {
// > column in the primary key for columns that are part of the primary
// > key.
//
// CREATE TABLE persons (
// CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
// name TEXT,
// score INTEGER)
//
// PRAGMA table_info("persons")
// PRAGMA table_info("players")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | firstName | TEXT | 0 | NULL | 0 |
// 2 | lastName | TEXT | 0 | NULL | 0 |
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
let columns = try self.columns(in: tableName)
let primaryKey: PrimaryKeyInfo?
let primaryKey: PrimaryKeyInfo
let pkColumns = columns
.filter { $0.primaryKeyIndex > 0 }
.sorted { $0.primaryKeyIndex < $1.primaryKeyIndex }
switch pkColumns.count {
case 0:
// No primary key column
primaryKey = nil
// No explicit primary key => primary key is hidden rowID column
primaryKey = .hiddenRowID
case 1:
// Single column
let pkColumn = pkColumns.first!
@@ -1142,18 +1189,18 @@ extension Database {
// > column in the primary key for columns that are part of the primary
// > key.
//
// CREATE TABLE persons (
// CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
//
// PRAGMA table_info("persons")
// PRAGMA table_info("players")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | firstName | TEXT | 0 | NULL | 0 |
// 2 | lastName | TEXT | 0 | NULL | 0 |
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
if sqlite3_libversion_number() < 3008005 {
// Work around a bug in SQLite where PRAGMA table_info would
// return a result even after the table was deleted.
@@ -1184,10 +1231,10 @@ extension Database {
}
let indexes = try Row.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in
let indexName: String = row.value(atIndex: 1)
let unique: Bool = row.value(atIndex: 2)
let indexName: String = row[1]
let unique: Bool = row[2]
let columns = try Row.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.map { ($0.value(atIndex: 0) as Int, $0.value(atIndex: 2) as String) }
.map { ($0[0] as Int, $0[2] as String) }
.sorted { $0.0 < $1.0 }
.map { $0.1 }
return IndexInfo(name: indexName, columns: columns, unique: unique)
@@ -1200,23 +1247,16 @@ extension Database {
/// If there exists a unique key on columns, return the columns
/// ordered as the matching index (or primay key). Case of returned columns
/// is not guaranteed.
func columnsForUniqueKey(_ columns: [String], in tableName: String) throws -> [String]? {
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
let lowercasedColumns = Set(columns.map { $0.lowercased() })
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
return primaryKey.columns
}
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
// There is an explicit unique index on the columns
return index.columns
}
if let lowercasedColumn = lowercasedColumns.first, lowercasedColumns.count == 1 {
if let rowIDColumnName = primaryKey?.rowIDColumn, rowIDColumnName.lowercased() == lowercasedColumn {
// An explicit INTEGER PRIMARY KEY column is a unique key.
return [rowIDColumnName]
}
if try primaryKey == nil && ["rowid", "oid", "_rowid_"].contains(lowercasedColumn) && !self.columns(in: tableName).map({ $0.name.lowercased() }).contains(lowercasedColumn) {
// A rowid, oid or _rowid_ column is a unique key when there is no explicit primary key and the column is not already used.
return [lowercasedColumn]
}
}
return nil
}
@@ -1236,11 +1276,11 @@ extension Database {
var previousId: Int? = nil
for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
// row = <Row id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"...">
let id: Int = row.value(atIndex: 0)
let seq: Int = row.value(atIndex: 1)
let table: String = row.value(atIndex: 2)
let origin: String = row.value(atIndex: 3)
let destination: String? = row.value(atIndex: 4)
let id: Int = row[0]
let seq: Int = row[1]
let table: String = row[2]
let origin: String = row[3]
let destination: String? = row[4]
if previousId == id {
rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq))
@@ -1257,7 +1297,7 @@ extension Database {
let completeMapping: [(origin: String, destination: String)]
if orderedMapping.contains(where: { (_, destination) in destination == nil }) {
let pk = try primaryKey(destinationTable)!
let pk = try primaryKey(destinationTable)
completeMapping = zip(pk.columns, orderedMapping).map { (pkColumn, arrow) in
(origin: arrow.origin, destination: pkColumn)
}
@@ -1276,17 +1316,17 @@ extension Database {
/// A column of a table
struct ColumnInfo : RowConvertible {
// CREATE TABLE persons (
// CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
//
// PRAGMA table_info("persons")
// PRAGMA table_info("players")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | firstName | TEXT | 0 | NULL | 0 |
// 2 | lastName | TEXT | 0 | NULL | 0 |
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
let name: String
let type: String
let notNull: Bool
@@ -1294,11 +1334,11 @@ struct ColumnInfo : RowConvertible {
let primaryKeyIndex: Int
init(row: Row) {
name = row.value(named: "name")
type = row.value(named: "type")
notNull = row.value(named: "notnull")
defaultDatabaseValue = row.value(named: "dflt_value")
primaryKeyIndex = row.value(named: "pk")
name = row["name"]
type = row["type"]
notNull = row["notnull"]
defaultDatabaseValue = row["dflt_value"]
primaryKeyIndex = row["pk"]
}
}
@@ -1322,41 +1362,45 @@ public struct IndexInfo {
}
}
/// You get primary keys from table names, with the Database.primaryKey(_)
/// method.
/// Primary keys are returned from the Database.primaryKey(_:) method.
///
/// Primary key is nil when table has no primary key:
/// When the table's primary key is the rowid:
///
/// // CREATE TABLE items (name TEXT)
/// let itemPk = try db.primaryKey("items") // nil
/// let pk = try db.primaryKey("items")
/// pk.columns // ["rowid"]
/// pk.rowIDColumn // nil
/// pk.isRowID // true
///
/// Primary keys have one or several columns. When the primary key has a single
/// column, it may contain the row id:
///
/// // CREATE TABLE persons (
/// // CREATE TABLE citizens (
/// // id INTEGER PRIMARY KEY,
/// // name TEXT
/// // )
/// let personPk = try db.primaryKey("persons")!
/// personPk.columns // ["id"]
/// personPk.rowIDColumn // "id"
/// let pk = try db.primaryKey("citizens")!
/// pk.columns // ["id"]
/// pk.rowIDColumn // "id"
/// pk.isRowID // true
///
/// When the table's primary key is not the rowid:
///
/// // CREATE TABLE countries (
/// // isoCode TEXT NOT NULL PRIMARY KEY
/// // name TEXT
/// // )
/// let countryPk = db.primaryKey("countries")!
/// countryPk.columns // ["isoCode"]
/// countryPk.rowIDColumn // nil
/// let pk = db.primaryKey("countries")!
/// pk.columns // ["isoCode"]
/// pk.rowIDColumn // nil
/// pk.isRowID // false
///
/// // CREATE TABLE citizenships (
/// // personID INTEGER NOT NULL REFERENCES persons(id)
/// // citizenID INTEGER NOT NULL REFERENCES citizens(id)
/// // countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode)
/// // PRIMARY KEY (personID, countryIsoCode)
/// // PRIMARY KEY (citizenID, countryIsoCode)
/// // )
/// let citizenshipsPk = db.primaryKey("citizenships")!
/// citizenshipsPk.columns // ["personID", "countryIsoCode"]
/// citizenshipsPk.rowIDColumn // nil
/// let pk = db.primaryKey("citizenships")!
/// pk.columns // ["citizenID", "countryIsoCode"]
/// pk.rowIDColumn // nil
/// pk.isRowID // false
public struct PrimaryKeyInfo {
private enum Impl {
/// The hidden rowID.
@@ -1407,6 +1451,18 @@ public struct PrimaryKeyInfo {
return nil
}
}
/// When true, the primary key is the rowid:
public var isRowID: Bool {
switch impl {
case .hiddenRowID:
return true
case .rowID:
return true
case .regular:
return false
}
}
}
/// You get foreign keys from table names, with the
@@ -1459,7 +1515,7 @@ final class StatementCompilationObserver {
// Call this method before calling sqlite3_prepare_v2()
func start() {
let observerPointer = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
let observerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(database.sqliteConnection, { (observerPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
// print("\(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
@@ -1470,7 +1526,7 @@ final class StatementCompilationObserver {
// > the authorization callback.
switch actionCode {
case SQLITE_DROP_TABLE, SQLITE_DROP_TEMP_TABLE, SQLITE_DROP_TEMP_VIEW, SQLITE_DROP_VIEW, SQLITE_DETACH, SQLITE_ALTER_TABLE, SQLITE_DROP_VTABLE, SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX, SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
let observer = unsafeBitCast(observerPointer, to: StatementCompilationObserver.self)
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
if actionCode == SQLITE_DROP_TABLE || actionCode == SQLITE_DROP_VTABLE {
observer.isDropTableStatement = true
}
@@ -1478,21 +1534,21 @@ final class StatementCompilationObserver {
case SQLITE_READ:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = unsafeBitCast(observerPointer, to: StatementCompilationObserver.self)
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
observer.selectionInfo.insert(table: tableName)
observer.selectionInfo.insert(allColumnsOfTable: tableName)
} else {
// SELECT column FROM table
observer.selectionInfo.insert(column: columnName, ofTable: tableName)
}
case SQLITE_INSERT:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = unsafeBitCast(observerPointer, to: StatementCompilationObserver.self)
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
observer.databaseEventKinds.append(.insert(tableName: tableName))
case SQLITE_DELETE:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = unsafeBitCast(observerPointer, to: StatementCompilationObserver.self)
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
if tableName != "sqlite_master" && !observer.isDropTableStatement {
observer.databaseEventKinds.append(.delete(tableName: tableName))
// Prevent [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
@@ -1502,17 +1558,17 @@ final class StatementCompilationObserver {
case SQLITE_UPDATE:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = unsafeBitCast(observerPointer, to: StatementCompilationObserver.self)
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
observer.insertUpdateEventKind(tableName: tableName, columnName: columnName)
case SQLITE_TRANSACTION:
guard let rawAction = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = unsafeBitCast(observerPointer, to: StatementCompilationObserver.self)
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
let action = UpdateStatement.TransactionStatementInfo.TransactionAction(rawValue: rawAction)!
observer.transactionStatementInfo = .transaction(action: action)
case SQLITE_SAVEPOINT:
guard let rawAction = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let savepointName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = unsafeBitCast(observerPointer, to: StatementCompilationObserver.self)
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
let action = UpdateStatement.TransactionStatementInfo.SavepointAction(rawValue: rawAction)!
observer.transactionStatementInfo = .savepoint(name: savepointName, action: action)
case SQLITE_FUNCTION:
@@ -1527,7 +1583,7 @@ final class StatementCompilationObserver {
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
guard let functionName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
if functionName.uppercased() == "COUNT" {
let observer = unsafeBitCast(observerPointer, to: StatementCompilationObserver.self)
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
observer.selectionInfo = SelectStatement.SelectionInfo.unknown()
}
default:
@@ -1629,7 +1685,7 @@ extension Database {
if needsRollback {
do {
try rollback(underlyingError: firstError)
try rollback()
} catch {
if firstError == nil {
firstError = error
@@ -1706,7 +1762,7 @@ extension Database {
if needsRollback {
do {
if topLevelSavepoint {
try rollback(underlyingError: firstError)
try rollback()
} else {
// Rollback, and release the savepoint.
// Rollback alone is not enough to clear the savepoint from
@@ -1737,36 +1793,48 @@ extension Database {
}
}
private func rollback(underlyingError: Error?) throws {
do {
private func rollback() throws {
// The SQLite documentation contains two related but distinct techniques
// to handle rollbacks and errors:
//
// https://www.sqlite.org/lang_transaction.html#immediate
//
// > Response To Errors Within A Transaction
// >
// > If certain kinds of errors occur within a transaction, the
// > transaction may or may not be rolled back automatically.
// > The errors that can cause an automatic rollback include:
// >
// > - SQLITE_FULL: database or disk full
// > - SQLITE_IOERR: disk I/O error
// > - SQLITE_BUSY: database in use by another process
// > - SQLITE_NOMEM: out or memory
// >
// > [...] It is recommended that applications respond to the
// > errors listed above by explicitly issuing a ROLLBACK
// > command. If the transaction has already been rolled back
// > automatically by the error response, then the ROLLBACK
// > command will fail with an error, but no harm is caused
// > by this.
//
// https://sqlite.org/c3ref/get_autocommit.html
//
// > The sqlite3_get_autocommit() interface returns non-zero or zero if
// > the given database connection is or is not in autocommit mode,
// > respectively.
// >
// > [...] If certain kinds of errors occur on a statement within a
// > multi-statement transaction (errors including SQLITE_FULL,
// > SQLITE_IOERR, SQLITE_NOMEM, SQLITE_BUSY, and SQLITE_INTERRUPT) then
// > the transaction might be rolled back automatically. The only way to
// > find out whether SQLite automatically rolled back the transaction
// > after an error is to use this function.
//
// The second technique is more robust, because we don't have to guess
// which rollback errors should be ignored, and which rollback errors
// should be exposed to the library user.
if sqlite3_get_autocommit(sqliteConnection) == 0 {
try execute("ROLLBACK TRANSACTION")
} catch {
// https://www.sqlite.org/lang_transaction.html#immediate
//
// > Response To Errors Within A Transaction
// >
// > If certain kinds of errors occur within a transaction, the
// > transaction may or may not be rolled back automatically.
// > The errors that can cause an automatic rollback include:
// >
// > - SQLITE_FULL: database or disk full
// > - SQLITE_IOERR: disk I/O error
// > - SQLITE_BUSY: database in use by another process
// > - SQLITE_NOMEM: out or memory
// >
// > [...] It is recommended that applications respond to the
// > errors listed above by explicitly issuing a ROLLBACK
// > command. If the transaction has already been rolled back
// > automatically by the error response, then the ROLLBACK
// > command will fail with an error, but no harm is caused
// > by this.
//
// TODO: test that isInsideTransaction, savepointStack, transaction
// observers, etc. are in good shape when such an implicit rollback
// happens.
guard let underlyingError = underlyingError as? DatabaseError, [.SQLITE_FULL, .SQLITE_IOERR, .SQLITE_BUSY, .SQLITE_NOMEM].contains(underlyingError.resultCode) else {
throw error
}
}
}
@@ -1884,9 +1952,11 @@ extension Database {
}
func updateStatementWillExecute(_ statement: UpdateStatement) {
// Grab the transaction observers that are interested in the actions
// performed by the statement.
let databaseEventKinds = statement.databaseEventKinds
activeTransactionObservers = transactionObservers.filter { observer in
return databaseEventKinds.index(where: observer.observes) != nil
return databaseEventKinds.contains(where: observer.observes)
}
}
@@ -1947,7 +2017,7 @@ extension Database {
case .transaction(action: let action):
switch action {
case .begin:
isInsideExplicitTransaction = true
break
case .commit:
if case .pending = self.transactionHookState {
// A COMMIT statement has ended a deferred transaction
@@ -1997,7 +2067,7 @@ extension Database {
}
}
/// Transaction hook
/// See sqlite3_commit_hook
func willCommit() throws {
let eventsBuffer = savepointStack.eventsBuffer
savepointStack.clear()
@@ -2013,12 +2083,10 @@ extension Database {
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Transaction hook
/// See sqlite3_preupdate_hook
private func willChange(with event: DatabasePreUpdateEvent) {
if savepointStack.isEmpty {
// Don't notify all transactionObservers about the database event.
// Only notify those that are interested in the event, and have been
// isolated in updateStatementWillExecute().
// Notify all interested transactionObservers.
for observer in activeTransactionObservers {
observer.databaseWillChange(with: event)
}
@@ -2029,12 +2097,10 @@ extension Database {
}
#endif
/// Transaction hook
/// See sqlite3_update_hook
private func didChange(with event: DatabaseEvent) {
if savepointStack.isEmpty {
// Don't notify all transactionObservers about the database event.
// Only notify those that are interested in the event, and have been
// isolated in updateStatementWillExecute().
// Notify all interested transactionObservers.
for observer in activeTransactionObservers {
observer.databaseDidChange(with: event)
}
@@ -2044,9 +2110,7 @@ extension Database {
}
}
/// Transaction hook
private func didCommit() {
isInsideExplicitTransaction = false
savepointStack.clear()
for observer in transactionObservers {
@@ -2055,9 +2119,7 @@ extension Database {
cleanupTransactionObservers()
}
/// Transaction hook
private func didRollback(notifyTransactionObservers: Bool) {
isInsideExplicitTransaction = false
savepointStack.clear()
if notifyTransactionObservers {
@@ -2069,9 +2131,9 @@ extension Database {
}
private func installUpdateHook() {
let dbPointer = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_update_hook(sqliteConnection, { (dbPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let db = unsafeBitCast(dbPointer, to: Database.self)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.didChange(with: DatabaseEvent(
kind: DatabaseEvent.Kind(rawValue: updateKind)!,
rowID: rowID,
@@ -2081,7 +2143,7 @@ extension Database {
#if SQLITE_ENABLE_PREUPDATE_HOOK
sqlite3_preupdate_hook(sqliteConnection, { (dbPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in
let db = unsafeBitCast(dbPointer, to: Database.self)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.willChange(with: DatabasePreUpdateEvent(
connection: databaseConnection!,
kind: DatabasePreUpdateEvent.Kind(rawValue: updateKind)!,
@@ -2270,10 +2332,6 @@ public enum DatabaseEventKind {
/// Returns whether event has any impact on tables and columns described
/// by selectionInfo.
public func impacts(_ selectionInfo: SelectStatement.SelectionInfo) -> Bool {
if selectionInfo.isUnknown {
return true
}
switch self {
case .delete(let tableName):
return selectionInfo.contains(anyColumnFrom: tableName)
+3 -2
View File
@@ -1,7 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
@@ -222,7 +223,7 @@ public struct DatabaseError : Error {
extension DatabaseError: CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
var description = "SQLite error \(extendedResultCode.rawValue)"
var description = "SQLite error \(resultCode.rawValue)"
if let sql = sql {
description += " with statement `\(sql)`"
}
+6 -4
View File
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// An SQL function or aggregate.
@@ -8,8 +10,8 @@ public final class DatabaseFunction {
let argumentCount: Int32?
let pure: Bool
private let kind: Kind
fileprivate var nArg: Int32 { return argumentCount ?? -1 }
fileprivate var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
private var nArg: Int32 { return argumentCount ?? -1 }
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
/// Returns an SQL function.
///
@@ -356,10 +358,10 @@ public protocol DatabaseAggregate {
/// aggregate function.
///
/// -- One value
/// SELECT maxLength(name) FROM persons
/// SELECT maxLength(name) FROM players
///
/// -- Two values
/// SELECT maxFullNameLength(firstName, lastName) FROM persons
/// SELECT maxFullNameLength(firstName, lastName) FROM players
///
/// This method is never called after the finalize() method has been called.
mutating func step(_ dbValues: [DatabaseValue]) throws
+65 -49
View File
@@ -1,11 +1,11 @@
import Foundation
#if os(iOS)
import UIKit
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if os(iOS)
import UIKit
#endif
/// A DatabasePool grants concurrent accesses to an SQLite database.
@@ -187,12 +187,12 @@ public final class DatabasePool {
// MARK: - Not public
fileprivate let writer: SerializedDatabase
fileprivate var readerConfig: Configuration
fileprivate var readerPool: Pool<SerializedDatabase>! = nil // var and nil-initialized so that we can use `self` when creating readerPool in DatabasePool.init()
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>()
}
@@ -223,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
@@ -523,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
@@ -538,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").cursor().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
+5 -5
View File
@@ -70,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.
@@ -189,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
}
@@ -217,8 +217,8 @@ extension DatabaseQueue : DatabaseReader {
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
/// let persons = try dbQueue.read { db in
/// try Person.fetchAll(...)
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(...)
/// }
///
/// This method is *not* reentrant.
+43
View File
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// The protocol for all types that can fetch values from a database.
@@ -206,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)
}
}
+7 -7
View File
@@ -7,8 +7,8 @@
protocol DatabaseSchemaCache {
mutating func clear()
func primaryKey(_ table: String) -> PrimaryKeyInfo??
mutating func set(primaryKey: PrimaryKeyInfo?, forTable table: String)
func primaryKey(_ table: String) -> PrimaryKeyInfo?
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
func columns(in table: String) -> [ColumnInfo]?
mutating func set(columns: [ColumnInfo], forTable table: String)
@@ -22,7 +22,7 @@ protocol DatabaseSchemaCache {
/// 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]] = [:]
@@ -34,11 +34,11 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
foreignKeys = [:]
}
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return primaryKeys[table]
}
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
primaryKeys[table] = primaryKey
}
@@ -75,11 +75,11 @@ final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
cache.write { $0.clear() }
}
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
return cache.read { $0.primaryKey(table) }
}
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
}
+16 -22
View File
@@ -1,7 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - DatabaseValue
@@ -94,9 +95,6 @@ public struct DatabaseValue {
// 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
}
@@ -112,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)")
@@ -133,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)")
@@ -190,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)):
@@ -203,16 +207,6 @@ 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 {
// 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
+110 -41
View File
@@ -1,3 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - DatabaseValueConvertible
/// Types that adopt DatabaseValueConvertible can be initialized from
@@ -6,12 +12,12 @@
/// 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?
///
@@ -33,16 +39,93 @@ extension DatabaseValueConvertible {
}
}
/// 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
///
@@ -55,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
/// ...
/// }
@@ -71,13 +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.cursor(arguments: arguments, next: {
let dbValue: DatabaseValue = row.value(atIndex: 0)
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self
})
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.
@@ -110,12 +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: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
let dbValue: DatabaseValue = row.value(atIndex: 0)
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self?
})
// 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
}
}
@@ -127,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
/// ...
/// }
@@ -143,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)
}
@@ -151,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.
@@ -167,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.
@@ -184,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
/// ...
/// }
@@ -201,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))
}
@@ -243,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.
@@ -258,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?
/// ...
/// }
@@ -274,13 +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.cursor(arguments: arguments, next: {
let dbValue: DatabaseValue = row.value(atIndex: 0)
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Wrapped?
})
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.
@@ -306,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?
/// ...
/// }
@@ -322,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)
}
@@ -330,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.
@@ -347,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?
/// ...
/// }
@@ -364,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))
}
+62 -9
View File
@@ -53,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
@@ -71,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
/// }
@@ -88,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
/// }
@@ -123,3 +123,56 @@ extension DatabaseWriter {
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)
}
}
+70 -33
View File
@@ -4,9 +4,9 @@
/// 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.
@@ -44,10 +44,10 @@ extension Request {
/// The returned request can fetch if the type T is fetchable (Row,
/// value, record).
///
/// // minHeight in Double?
/// let minHeight = Person
/// .select(min(heightColumn))
/// .asRequest(of: Double.self) // <--
/// // Int?
/// let maxScore = Player
/// .select(max(scoreColumn))
/// .asRequest(of: Int.self) // <--
/// .fetchOne(db)
///
/// - parameter type: The fetched type T
@@ -129,8 +129,8 @@ 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])
/// let request = SQLRequest("SELECT * FROM players")
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
@@ -146,8 +146,8 @@ 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])
/// let request = SQLRequest("SELECT * FROM players")
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
@@ -190,11 +190,11 @@ public struct SQLRequest : Request {
/// Typed requests can fetch if their associated type RowDecoder is able to
/// decode rows (Row, value, record)
///
/// struct Person: RowConvertible { ... }
/// 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 type that can convert raw database rows to fetched values
@@ -276,9 +276,9 @@ extension TypedRequest where RowDecoder: 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
/// ...
/// }
///
@@ -290,14 +290,14 @@ extension TypedRequest where RowDecoder: 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<RowDecoder> {
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.
@@ -308,8 +308,8 @@ extension TypedRequest where RowDecoder: RowConvertible {
/// 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.
@@ -326,7 +326,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible {
/// 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
/// ...
/// }
@@ -339,7 +339,7 @@ extension TypedRequest where RowDecoder: 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<RowDecoder> {
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
@@ -378,7 +378,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// 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
/// ...
/// }
@@ -391,7 +391,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - 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<RowDecoder> {
public func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
@@ -430,7 +430,7 @@ extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
/// 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?
/// ...
/// }
@@ -443,7 +443,7 @@ extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
/// - 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<RowDecoder._Wrapped?> {
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
}
@@ -460,6 +460,43 @@ extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
}
}
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
@@ -467,10 +504,10 @@ extension TypedRequest where RowDecoder: Row {
/// 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
@@ -489,7 +526,7 @@ extension TypedRequest where RowDecoder: 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)
}
+108 -81
View File
@@ -1,12 +1,15 @@
import Foundation
#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.
@@ -59,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.
@@ -83,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
@@ -95,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
}
@@ -140,7 +136,7 @@ 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).storage.value
}
@@ -153,7 +149,7 @@ 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).losslessConvert()
}
@@ -170,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).losslessConvert()
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.
@@ -185,7 +181,7 @@ 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).losslessConvert()
}
@@ -201,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).losslessConvert()
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
@@ -216,12 +212,12 @@ 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 {
@@ -238,7 +234,7 @@ 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
}
@@ -257,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).losslessConvert()
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.
@@ -276,7 +272,7 @@ 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)")
@@ -297,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).losslessConvert()
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
@@ -315,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.
@@ -327,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.
@@ -343,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.
@@ -356,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.
@@ -373,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.
@@ -442,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)
}
}
@@ -481,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
@@ -498,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
@@ -524,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.cursor(arguments: arguments, next: { 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.
@@ -571,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
@@ -596,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)
}
@@ -605,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.
@@ -619,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.
@@ -636,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
@@ -662,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))
}
@@ -714,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)
@@ -969,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 {
@@ -987,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)
+8 -7
View File
@@ -39,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 {
@@ -300,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 {
@@ -390,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? {
-4
View File
@@ -1,9 +1,5 @@
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#endif
/// 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.
+146 -97
View File
@@ -1,7 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -31,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()
@@ -44,7 +52,12 @@ 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)
}
@@ -186,13 +199,22 @@ public class Statement {
}
}
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()
}
}
@@ -203,7 +225,7 @@ 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])!
/// }
@@ -211,10 +233,16 @@ public final class SelectStatement : Statement {
/// 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
}
@@ -232,57 +260,43 @@ 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 cursor<Element>(arguments: StatementArguments? = nil, next 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 cursor(arguments: StatementArguments? = nil) -> DatabaseCursor<Void> {
return cursor(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)
}
/// Information about the table and columns read by a SelectStatement
public struct SelectionInfo : CustomStringConvertible {
mutating func insert(table: String) {
mutating func insert(allColumnsOfTable table: String) {
tables.insert(table)
}
mutating func insert(column: String, ofTable table: String) {
if columns[table] != nil {
columns[table]!.insert(column)
} else {
columns[table] = [column]
}
columns[table, default: []].insert(column)
}
/// If true, selection is unknown
let isUnknown: Bool
/// Relevant iff isUnknown is false
/// Returns true if isUnknown is true
func contains(anyColumnFrom table: String) -> Bool {
if isUnknown { return true }
return tables.contains(table) || columns.index(forKey: table) != nil
}
/// Relevant iff isUnknown is false
/// Returns true if isUnknown is true
func contains(anyColumnIn columns: Set<String>, from table: String) -> Bool {
if isUnknown { return true }
return tables.contains(table) || !(self.columns[table]?.isDisjoint(with: columns) ?? true)
}
@@ -294,6 +308,9 @@ public final class SelectStatement : Statement {
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>] = [:]
@@ -306,48 +323,50 @@ public final class SelectStatement : Statement {
/// A textual representation of `self`.
public var description: String {
// TODO: include tables in the description
return columns
.sorted { $0.key < $1.key }
.map { (table, columns) in "\(table)(\(columns.sorted().joined(separator: ", ")))" }
.joined(separator: ", ")
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()
return .some(())
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
@@ -363,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
@@ -399,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
@@ -416,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)
@@ -495,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
///
@@ -542,33 +563,38 @@ 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.
@@ -586,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))
@@ -595,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.
@@ -791,9 +817,6 @@ 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
@@ -832,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)
}
@@ -864,7 +887,20 @@ struct StatementCache {
return statement
}
let statement = try db.makeSelectStatement(sql)
#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
}
@@ -874,7 +910,20 @@ struct StatementCache {
return statement
}
let statement = try db.makeUpdateStatement(sql)
#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
}
+267 -38
View File
@@ -1,23 +1,46 @@
#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.
///
@@ -27,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
@@ -41,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
/// ...
/// }
@@ -57,20 +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.cursor(arguments: arguments, next: {
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
var error = "could not convert database value NULL to \(Self.self) with statement `\(statement.sql)`"
if let arguments = arguments, !arguments.isEmpty {
error += " arguments \(arguments)"
}
fatalError(error)
}
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.
@@ -100,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: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
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
}
}
@@ -120,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
/// ...
/// }
@@ -136,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)
}
@@ -144,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.
@@ -160,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.
@@ -177,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
/// ...
/// }
@@ -194,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))
}
@@ -228,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))
}
}
+15 -5
View File
@@ -1,13 +1,23 @@
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))
}
@@ -13,7 +13,7 @@ import Foundation
///
/// // ... 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 {
@@ -25,3 +25,17 @@ extension ReferenceConvertible where Self: DatabaseValueConvertible, Self.Refere
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
}
}
+61 -21
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 *dbValue*, if possible.
/// 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? {
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
return cast(fromDatabaseDateComponents(databaseDateComponents))
guard let date = Date.fromDatabaseValue(dbValue) else {
return nil
}
if let julianDayNumber = Double.fromDatabaseValue(dbValue) {
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()
@@ -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,7 +10,7 @@
///
/// // ... 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 {
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - Value Types
@@ -114,17 +116,64 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns an Int initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
switch dbValue.storage {
case .int64(let int64):
return Int(exactly: int64)
case .double(let double):
guard double >= Double(Int64.min) else { return nil }
guard double < Double(Int64.max) else { return nil }
return Int(exactly: Int64(double))
default:
return nil
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.
@@ -151,16 +200,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns an Int32 initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
switch dbValue.storage {
case .int64(let int64):
return Int32(exactly: int64)
case .double(let double):
guard double >= Double(Int64.min) else { return nil }
guard double < Double(Int64.max) else { return nil }
return Int32(exactly: Int64(double))
default:
return nil
}
return Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
}
}
@@ -196,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 {
@@ -298,7 +478,7 @@ 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) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
@@ -317,7 +497,7 @@ 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) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
@@ -336,7 +516,7 @@ 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) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
@@ -357,7 +537,7 @@ 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) { dbValues in
@@ -377,7 +557,7 @@ 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) { dbValues in
@@ -397,7 +577,7 @@ 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) { dbValues in
@@ -433,7 +613,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
@@ -451,7 +631,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
@@ -469,7 +649,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
@@ -487,7 +667,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.localizedCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
@@ -505,7 +685,7 @@ extension DatabaseCollation {
///
/// let collationName = DatabaseCollation.localizedStandardCompare.name
/// dbQueue.execute(
/// "CREATE TABLE persons (" +
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
+19 -24
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
/// }
///
@@ -266,7 +261,7 @@ public final class FTS4ColumnDefinition {
#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()
/// }
@@ -284,7 +279,7 @@ public final class FTS4ColumnDefinition {
#else
/// 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()
/// }
@@ -304,7 +299,7 @@ public final class FTS4ColumnDefinition {
/// 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()
/// }
+1 -4
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.
+1 -3
View File
@@ -188,9 +188,7 @@
/// }
/// }
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer {
guard let api = FTS5.api(self) else {
throw DatabaseError(resultCode: .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) }
+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> { }
+1 -1
View File
@@ -4,6 +4,6 @@ extension Database {
}
extension DatabaseValue {
@available(*, unavailable, message:"DatabaseSequence has been replaced by DatabaseCursor.")
@available(*, unavailable, message:"DatabaseSequence has been replaced by Cursor.")
public func value() -> Any { 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() }
}
+41 -36
View File
@@ -10,29 +10,31 @@
/// 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("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, " +
/// "ownerID INTEGER NOT NULL " +
/// " REFERENCES persons(id) " +
/// " ON DELETE CASCADE ON UPDATE CASCADE, " +
/// "title TEXT NOT NULL" +
/// ")")
/// 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("AddAgeToPersons") { db in
/// try db.execute("ALTER TABLE persons ADD COLUMN age INT")
/// migrator.registerMigration("AddBirthYearToAuthors") { db in
/// try db.execute("ALTER TABLE authors ADD COLUMN birthYear INT")
/// }
///
/// try migrator.migrate(dbQueue)
@@ -44,13 +46,14 @@ public struct DatabaseMigrator {
/// Registers a migration.
///
/// migrator.registerMigration("createPersons") { db in
/// try db.execute(
/// "CREATE TABLE persons (" +
/// "id INTEGER PRIMARY KEY, " +
/// "creationDate TEXT, " +
/// "name TEXT NOT NULL" +
/// ")")
/// migrator.registerMigration("createPlayers") { db in
/// try db.execute("""
/// CREATE TABLE players (
/// id INTEGER PRIMARY KEY,
/// creationDate TEXT,
/// name TEXT NOT NULL
/// )
/// """)
/// }
///
/// - parameters:
@@ -64,13 +67,14 @@ public struct DatabaseMigrator {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on persons.name:
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("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;")
/// 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
@@ -88,13 +92,14 @@ public struct DatabaseMigrator {
@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:
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("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;")
/// 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
@@ -31,14 +31,12 @@ extension TableMapping {
/// // 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.
///
/// 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)
}
@@ -12,6 +12,10 @@
///
/// 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)?:
@@ -36,12 +40,6 @@
/// // 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> {
+73 -93
View File
@@ -34,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"))
@@ -50,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")])
@@ -68,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")
@@ -84,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
@@ -100,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
@@ -116,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))
@@ -160,13 +160,13 @@ 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()
@@ -177,13 +177,13 @@ 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()
@@ -197,13 +197,13 @@ extension QueryInterfaceRequest {
/// 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")
@@ -213,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
@@ -225,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
@@ -235,7 +235,7 @@ extension QueryInterfaceRequest {
}
}
extension QueryInterfaceRequest {
extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
// MARK: Deleting
@@ -257,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 = [SQLStar(), Column.rowID]
} else {
selection = [SQLStar()]
}
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.
@@ -282,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)
}
@@ -335,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)
}
@@ -350,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)
}
@@ -379,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,26 +59,7 @@ struct QueryInterfaceSelectQueryDefinition {
sql += " HAVING " + havingExpression.expressionSQL(&arguments)
}
var orderings = self.orderings
if isReversed {
if orderings.isEmpty {
// https://www.sqlite.org/lang_createtable.html#rowid
//
// > The rowid value can be accessed using one of the special
// > case-independent names "rowid", "oid", or "_rowid_" in
// > place of a column name. If a table contains a user defined
// > column named "rowid", "oid" or "_rowid_", then that name
// > always refers the explicitly declared column and cannot be
// > used to retrieve the integer rowid value.
//
// 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]
} else {
orderings = orderings.map { $0.reversed }
}
}
let orderings = self.queryOrderings
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ")
}
@@ -101,11 +82,6 @@ struct QueryInterfaceSelectQueryDefinition {
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()
@@ -117,11 +93,48 @@ struct QueryInterfaceSelectQueryDefinition {
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
//
// > The rowid value can be accessed using one of the special
// > case-independent names "rowid", "oid", or "_rowid_" in
// > place of a column name. If a table contains a user defined
// > column named "rowid", "oid" or "_rowid_", then that name
// > always refers the explicitly declared column and cannot be
// > used to retrieve the integer rowid value.
//
// Here we assume that rowid is not a custom column.
// TODO: support for user-defined rowid column.
// TODO: support for WITHOUT ROWID tables.
return [Column.rowID.desc]
} else {
return orderings.map { $0.reversed }
}
} else {
return orderings
}
}
/// Remove ordering
var unorderedQuery: QueryInterfaceSelectQueryDefinition {
var query = self
@@ -176,7 +189,7 @@ extension QueryInterfaceSelectQueryDefinition : Request {
// ->
// SELECT COUNT(*) FROM tableName ...
var countQuery = unorderedQuery
countQuery.selection = [SQLExpressionCount(SQLStar())]
countQuery.selection = [SQLExpressionCount(AllColumns())]
return countQuery
}
}
@@ -184,7 +197,7 @@ extension QueryInterfaceSelectQueryDefinition : Request {
// SELECT COUNT(*) FROM (self)
private var trivialCountQuery: QueryInterfaceSelectQueryDefinition {
return QueryInterfaceSelectQueryDefinition(
select: [SQLExpressionCount(SQLStar())],
select: [SQLExpressionCount(AllColumns())],
from: .query(query: unorderedQuery, alias: nil))
}
}
@@ -227,8 +240,8 @@ struct SQLLimit {
extension SQLCount {
var sqlSelectable: SQLSelectable {
switch self {
case .star:
return SQLExpressionCount(SQLStar())
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 {
+1 -10
View File
@@ -28,12 +28,6 @@ public protocol SQLCollection {
///
/// 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
}
@@ -43,10 +37,7 @@ public protocol SQLCollection {
extension SQLCollection {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns a SQLExpressionContains which applies the `IN` operator:
///
/// 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)
}
@@ -191,6 +191,30 @@ public struct SQLBinaryOperator : Hashable {
public static func == (lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool {
return lhs.sql == rhs.sql
}
// TODO: make it an extension of Sequence (like joined(separator:)) when Swift can better handle existentials
// TODO: make it public eventually
/// Return nil if expressions is empty.
func join(_ expressions: [SQLExpression]) -> SQLExpression? {
switch expressions.count {
case 0:
return nil
case 1:
return expressions[0]
default:
let literals = expressions.map { $0.literal }
let firstLiteral = literals[0]
var sql = firstLiteral.sql
var arguments = firstLiteral.arguments ?? StatementArguments()
for literal in literals.suffix(from: 1) {
sql += " \(self.sql) \(literal.sql)"
if let args = literal.arguments {
arguments += args
}
}
return SQLExpressionLiteral("(\(sql))", arguments: arguments.isEmpty ? nil : arguments)
}
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
+1 -1
View File
@@ -94,7 +94,7 @@ extension SQLExpression {
// SELECT expr FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
return .star
return .all
}
}
}
@@ -1,15 +1,37 @@
// MARK: - SQLStar
// MARK: - AllColumns
struct SQLStar : SQLSelectable {
func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
/// AllColumns is the `*` in `SELECT *`.
///
/// You use AllColumns in your custom implementation of
/// TableMapping.databaseSelection.
///
/// For example:
///
/// struct Player : TableMapping {
/// static var databaseTableName = "players"
/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
/// }
///
/// // SELECT *, rowid FROM players
/// let request = Player.all()
public struct AllColumns {
///
public init() { }
}
extension AllColumns : SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
return "*"
}
func countedSQL(_ arguments: inout StatementArguments?) -> String {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
return "*"
}
func count(distinct: Bool) -> SQLCount? {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func count(distinct: Bool) -> SQLCount? {
// SELECT DISTINCT * FROM tableName ...
guard !distinct else {
return nil
@@ -18,7 +40,7 @@ struct SQLStar : SQLSelectable {
// SELECT * FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
return .star
return .all
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ public enum SQLCount {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Represents COUNT(*)
case star
case all
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -39,7 +39,7 @@ extension SQLSpecificExpressible {
///
/// For example:
///
/// Person.filter(Column("email").collating(.nocase) == "contact@example.com")
/// Player.filter(Column("email").collating(.nocase) == "contact@example.com")
public func collating(_ collation: Database.CollationName) -> SQLCollatedExpression {
return SQLCollatedExpression(sqlExpression, collationName: collation)
}
@@ -48,7 +48,7 @@ extension SQLSpecificExpressible {
///
/// For example:
///
/// Person.filter(Column("name").collating(.localizedStandardCompare) == "Hervé")
/// Player.filter(Column("name").collating(.localizedStandardCompare) == "Hervé")
public func collating(_ collation: DatabaseCollation) -> SQLCollatedExpression {
return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name))
}
@@ -151,7 +151,7 @@ extension SQLSpecificExpressible {
/// capitalized String property. It is NULL for non-String arguments.
///
/// 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 var capitalized: SQLExpression {
return DatabaseFunction.capitalize.apply(sqlExpression)
@@ -161,7 +161,7 @@ extension SQLSpecificExpressible {
/// lowercased String property. It is NULL for non-String arguments.
///
/// 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 var lowercased: SQLExpression {
return DatabaseFunction.lowercase.apply(sqlExpression)
@@ -171,7 +171,7 @@ extension SQLSpecificExpressible {
/// uppercased String property. It is NULL for non-String arguments.
///
/// 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 var uppercased: SQLExpression {
return DatabaseFunction.uppercase.apply(sqlExpression)
@@ -183,7 +183,7 @@ extension SQLSpecificExpressible {
/// localizedCapitalized String property. It is NULL for non-String arguments.
///
/// 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 var localizedCapitalized: SQLExpression {
@@ -194,7 +194,7 @@ extension SQLSpecificExpressible {
/// localizedLowercased String property. It is NULL for non-String arguments.
///
/// 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 var localizedLowercased: SQLExpression {
@@ -205,7 +205,7 @@ extension SQLSpecificExpressible {
/// localizedUppercased String property. It is NULL for non-String arguments.
///
/// 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 var localizedUppercased: SQLExpression {
+52 -46
View File
@@ -14,6 +14,28 @@ extension SQLBinaryOperator {
static let isNot = SQLBinaryOperator("IS NOT", negated: "IS")
}
// Outputs "x = y" or "x IS NULL"
private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression {
switch (lhs, rhs) {
case (let lhs, let rhs as DatabaseValue):
switch rhs.storage {
case .null:
return SQLExpressionBinary(.is, lhs, DatabaseValue.null)
default:
return SQLExpressionBinary(.equal, lhs, rhs)
}
case (let lhs as DatabaseValue, let rhs):
switch lhs.storage {
case .null:
return SQLExpressionBinary(.is, rhs, DatabaseValue.null)
default:
return SQLExpressionBinary(.equal, lhs, rhs)
}
default:
return SQLExpressionBinary(.equal, lhs, rhs)
}
}
/// An SQL expression that compares two expressions with the `=` SQL operator.
///
/// // name = 'Arthur'
@@ -24,11 +46,7 @@ extension SQLBinaryOperator {
/// // name IS NULL
/// Column("name") == nil
public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
if let rhs = rhs {
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.`is`, lhs.sqlExpression, DatabaseValue.null)
}
return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
}
/// An SQL expression that compares two expressions with the `=` SQL operator.
@@ -71,11 +89,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
/// // name IS NULL
/// nil == Column("name")
public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
if let lhs = lhs {
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null)
}
return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression)
}
/// An SQL expression that compares two expressions with the `=` SQL operator.
@@ -113,7 +127,7 @@ public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
/// // email = login
/// Column("email") == Column("login")
public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
return isEqual(lhs.sqlExpression, rhs.sqlExpression)
}
/// An SQL expression that compares two expressions with the `<>` SQL operator.
@@ -126,11 +140,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
/// // name IS NOT NULL
/// Column("name") != nil
public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
if let rhs = rhs {
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.isNot, lhs.sqlExpression, DatabaseValue.null)
}
return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null).negated
}
/// An SQL expression that compares two expressions with the `<>` SQL operator.
@@ -173,11 +183,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
/// // name IS NOT NULL
/// nil != Column("name")
public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
if let lhs = lhs {
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.isNot, rhs.sqlExpression, DatabaseValue.null)
}
return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression).negated
}
/// An SQL expression that compares two expressions with the `<>` SQL operator.
@@ -215,7 +221,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
/// // email <> login
/// Column("email") != Column("login")
public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
return isEqual(lhs.sqlExpression, rhs.sqlExpression).negated
}
/// An SQL expression that compares two expressions with the `IS` SQL operator.
@@ -223,7 +229,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
/// // name IS 'Arthur'
/// Column("name") === "Arthur"
public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
}
/// An SQL expression that compares two expressions with the `IS` SQL operator.
@@ -240,9 +246,9 @@ public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress
/// "Arthur" === Column("name")
public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
if let lhs = lhs {
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression)
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null)
return SQLExpressionBinary(.is, rhs.sqlExpression, DatabaseValue.null)
}
}
@@ -251,7 +257,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres
/// // name IS 'Arthur' COLLATE NOCASE
/// "Arthur" === Column("name").collating(.nocase)
public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression {
return SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName)
return SQLExpressionCollate(lhs === rhs.expression, collationName: rhs.collationName)
}
/// An SQL expression that compares two expressions with the `IS` SQL operator.
@@ -259,7 +265,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress
/// // email IS login
/// Column("email") === Column("login")
public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression)
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
}
/// An SQL expression that compares two expressions with the `IS NOT` SQL operator.
@@ -325,8 +331,8 @@ extension SQLBinaryOperator {
/// An SQL expression that compares two expressions with the `<` SQL operator.
///
/// // age < 18
/// Column("age") < 18
/// // score < 18
/// Column("score") < 18
public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
}
@@ -341,8 +347,8 @@ public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
/// An SQL expression that compares two expressions with the `<` SQL operator.
///
/// // 18 < age
/// 18 < Column("age")
/// // 18 < score
/// 18 < Column("score")
public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
}
@@ -365,8 +371,8 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
/// An SQL expression that compares two expressions with the `<=` SQL operator.
///
/// // age <= 18
/// Column("age") <= 18
/// // score <= 18
/// Column("score") <= 18
public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
}
@@ -381,8 +387,8 @@ public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio
/// An SQL expression that compares two expressions with the `<=` SQL operator.
///
/// // 18 <= age
/// 18 <= Column("age")
/// // 18 <= score
/// 18 <= Column("score")
public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
}
@@ -405,15 +411,15 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
/// An SQL expression that compares two expressions with the `>` SQL operator.
///
/// // age > 18
/// Column("age") > 18
/// // score > 18
/// Column("score") > 18
public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
}
/// An SQL expression that compares two expressions with the `>` SQL operator.
///
/// // age > 'Arthur' COLLATE NOCASE
/// // name > 'Arthur' COLLATE NOCASE
/// Column("name").collating(.nocase) > "Arthur"
public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression {
return SQLExpressionCollate(lhs.expression > rhs, collationName: lhs.collationName)
@@ -421,8 +427,8 @@ public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
/// An SQL expression that compares two expressions with the `>` SQL operator.
///
/// // 18 > age
/// 18 > Column("age")
/// // 18 > score
/// 18 > Column("score")
public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
}
@@ -445,8 +451,8 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
/// An SQL expression that compares two expressions with the `>=` SQL operator.
///
/// // age >= 18
/// Column("age") >= 18
/// // score >= 18
/// Column("score") >= 18
public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
}
@@ -461,16 +467,16 @@ public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio
/// An SQL expression that compares two expressions with the `>=` SQL operator.
///
/// // 18 >= age
/// 18 >= Column("age")
/// // 18 >= score
/// 18 >= Column("score")
public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
}
/// An SQL expression that compares two expressions with the `>=` SQL operator.
///
/// // 'Arthur' >= age COLLATE NOCASE
/// "Arthur" >= Column("age").collating(.nocase)
/// // 'Arthur' >= name COLLATE NOCASE
/// "Arthur" >= Column("name").collating(.nocase)
public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression {
return SQLExpressionCollate(lhs >= rhs.expression, collationName: rhs.collationName)
}
+30 -32
View File
@@ -97,7 +97,7 @@ extension Database {
/// Modifies a database table.
///
/// try db.alter(table: "persons") { t in
/// try db.alter(table: "players") { t in
/// t.add(column: "url", .text)
/// }
///
@@ -126,7 +126,7 @@ extension Database {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates an index.
///
/// try db.create(index: "personByEmail", on: "person", columns: ["email"])
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
///
/// SQLite can also index expressions (https://www.sqlite.org/expridx.html)
/// and use specific collations. To create such an index, use a raw SQL
@@ -154,7 +154,7 @@ extension Database {
#else
/// Creates an index.
///
/// try db.create(index: "personByEmail", on: "person", columns: ["email"])
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
///
/// SQLite can also index expressions (https://www.sqlite.org/expridx.html)
/// and use specific collations. To create such an index, use a raw SQL
@@ -180,7 +180,7 @@ extension Database {
/// Creates a partial index.
///
/// try db.create(index: "personByEmail", on: "person", columns: ["email"], condition: Column("email") != nil)
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"], condition: Column("email") != nil)
///
/// See https://www.sqlite.org/lang_createindex.html, and
/// https://www.sqlite.org/partialindex.html
@@ -217,7 +217,7 @@ extension Database {
/// You don't create instances of this class. Instead, you use the Database
/// `create(table:)` method:
///
/// try db.create(table: "persons") { t in // t is TableDefinition
/// try db.create(table: "players") { t in // t is TableDefinition
/// t.column(...)
/// }
///
@@ -244,7 +244,7 @@ public final class TableDefinition {
/// Appends a table column.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("name", .text)
/// }
///
@@ -264,9 +264,9 @@ public final class TableDefinition {
/// Defines the table primary key.
///
/// try db.create(table: "citizenships") { t in
/// t.column("personID", .integer)
/// t.column("citizenID", .integer)
/// t.column("countryCode", .text)
/// t.primaryKey(["personID", "countryCode"])
/// t.primaryKey(["citizenID", "countryCode"])
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#primkeyconst and
@@ -304,9 +304,9 @@ public final class TableDefinition {
///
/// try db.create(table: "passport") { t in
/// t.column("issueDate", .date)
/// t.column("personID", .integer)
/// t.column("citizenID", .integer)
/// t.column("countryCode", .text)
/// t.foreignKey(["personID", "countryCode"], references: "citizenships", onDelete: .cascade)
/// t.foreignKey(["citizenID", "countryCode"], references: "citizenships", onDelete: .cascade)
/// }
///
/// See https://www.sqlite.org/foreignkeys.html
@@ -327,7 +327,7 @@ public final class TableDefinition {
/// Adds a CHECK constraint.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("personalPhone", .text)
/// t.column("workPhone", .text)
/// let personalPhone = Column("personalPhone")
@@ -344,7 +344,7 @@ public final class TableDefinition {
/// Adds a CHECK constraint.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("personalPhone", .text)
/// t.column("workPhone", .text)
/// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
@@ -422,11 +422,9 @@ public final class TableDefinition {
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
} else if table == name {
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
} else if let primaryKey = try db.primaryKey(table) {
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
} else {
// Programmer error
fatalError("explicit referenced column(s) required, since table \(table) has no primary key")
let primaryKey = try db.primaryKey(table)
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
}
if let deleteAction = deleteAction {
chunks.append("ON DELETE")
@@ -471,7 +469,7 @@ public final class TableDefinition {
/// You don't create instances of this class. Instead, you use the Database
/// `alter(table:)` method:
///
/// try db.alter(table: "persons") { t in // t is TableAlteration
/// try db.alter(table: "players") { t in // t is TableAlteration
/// t.add(column: ...)
/// }
///
@@ -486,7 +484,7 @@ public final class TableAlteration {
/// Appends a column to the table.
///
/// try db.alter(table: "persons") { t in
/// try db.alter(table: "players") { t in
/// t.add(column: "url", .text)
/// }
///
@@ -528,11 +526,11 @@ public final class TableAlteration {
///
/// You get instances of this class when you create or alter a database table:
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column(...) // ColumnDefinition
/// }
///
/// try db.alter(table: "persons") { t in
/// try db.alter(table: "players") { t in
/// t.add(column: ...) // ColumnDefinition
/// }
///
@@ -561,7 +559,7 @@ public final class ColumnDefinition {
/// Adds a primary key constraint on the column.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("id", .integer).primaryKey()
/// }
///
@@ -581,7 +579,7 @@ public final class ColumnDefinition {
/// Adds a NOT NULL constraint on the column.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("name", .text).notNull()
/// }
///
@@ -598,7 +596,7 @@ public final class ColumnDefinition {
/// Adds a UNIQUE constraint on the column.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("email", .text).unique()
/// }
///
@@ -615,7 +613,7 @@ public final class ColumnDefinition {
/// Adds an index of the column.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("email", .text).indexed()
/// }
///
@@ -632,7 +630,7 @@ public final class ColumnDefinition {
/// Adds a CHECK constraint on the column.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("name", .text).check { length($0) > 0 }
/// }
///
@@ -649,7 +647,7 @@ public final class ColumnDefinition {
/// Adds a CHECK constraint on the column.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("name", .text).check(sql: "LENGTH(name) > 0")
/// }
///
@@ -665,7 +663,7 @@ public final class ColumnDefinition {
/// Defines the default column value.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("name", .text).defaults(to: "Anonymous")
/// }
///
@@ -681,7 +679,7 @@ public final class ColumnDefinition {
/// Defines the default column value.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP")
/// }
///
@@ -697,7 +695,7 @@ public final class ColumnDefinition {
// Defines the default column collation.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("email", .text).collate(.nocase)
/// }
///
@@ -713,7 +711,7 @@ public final class ColumnDefinition {
// Defines the default column collation.
///
/// try db.create(table: "persons") { t in
/// try db.create(table: "players") { t in
/// t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
/// }
///
@@ -815,11 +813,11 @@ public final class ColumnDefinition {
chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))")
} else if table.lowercased() == tableName.lowercased() {
// implicit autoreference
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table)?.columns ?? [Column.rowID.name]
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table).columns
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
} else {
// implicit external reference
let primaryKeyColumns = try db.primaryKey(table)?.columns ?? [Column.rowID.name]
let primaryKeyColumns = try db.primaryKey(table).columns
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
}
if let deleteAction = deleteAction {
+45 -27
View File
@@ -85,7 +85,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
if let isSameRecord = isSameRecord {
itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } }
} else {
itemsAreIdenticalFactory = { _ in { _ in false } }
itemsAreIdenticalFactory = { _ in { _,_ in false } }
}
try self.init(
@@ -95,7 +95,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
itemsAreIdenticalFactory: itemsAreIdenticalFactory)
}
fileprivate init<Request>(
private init<Request>(
_ databaseWriter: DatabaseWriter,
request: Request,
queue: DispatchQueue,
@@ -211,11 +211,33 @@ public final class FetchedRecordsController<Record: RowConvertible> {
onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil,
didChange: ((FetchedRecordsController<Record>) -> ())? = nil)
{
// I hate you SE-0110.
let wrappedWillChange: ((FetchedRecordsController<Record>, Void) -> ())?
if let willChange = willChange {
wrappedWillChange = { (controller, _) in willChange(controller) }
} else {
wrappedWillChange = nil
}
let wrappedDidChange: ((FetchedRecordsController<Record>, Void) -> ())?
if let didChange = didChange {
wrappedDidChange = { (controller, _) in didChange(controller) }
} else {
wrappedDidChange = nil
}
trackChanges(
fetchAlongside: { _ in },
willChange: willChange.map { callback in { (controller, _) in callback(controller) } },
willChange: wrappedWillChange,
onChange: onChange,
didChange: didChange.map { callback in { (controller, _) in callback(controller) } })
didChange: wrappedDidChange)
// Without bloody SE-0110:
// trackChanges(
// fetchAlongside: { _ in },
// willChange: willChange.map { callback in { (controller, _) in callback(controller) } },
// onChange: onChange,
// didChange: didChange.map { callback in { (controller, _) in callback(controller) } })
}
/// Registers changes notification callbacks.
@@ -348,16 +370,16 @@ public final class FetchedRecordsController<Record: RowConvertible> {
fileprivate var fetchedItems: [Item<Record>]?
/// The record comparator
fileprivate var itemsAreIdentical: ItemComparator<Record>
private var itemsAreIdentical: ItemComparator<Record>
/// The record comparator factory (support for request change)
fileprivate let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
private let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
/// The request
fileprivate var request: Request
/// The observed selection info
fileprivate var selectionInfo : SelectStatement.SelectionInfo
private var selectionInfo : SelectStatement.SelectionInfo
/// The eventual current database observer
private var observer: FetchedRecordsObserver<Record>?
@@ -461,29 +483,25 @@ extension FetchedRecordsController where Record: TableMapping {
// non-null value.
let itemsAreIdenticalFactory: ItemComparatorFactory<Record> = { db in
// Extract primary key columns from database table
let columns: [String]
if let primaryKey = try db.primaryKey(Record.databaseTableName) {
columns = primaryKey.columns
} else if Record.selectsRowID {
columns = [Column.rowID.name]
} else {
// No primary key => can't compare rows
return { _ in false }
}
let columns = try db.primaryKey(Record.databaseTableName).columns
// Compare primary keys
assert(!columns.isEmpty)
return { (lItem, rItem) in
var notNullValue = false
for column in columns {
let lValue: DatabaseValue = lItem.row.value(named: column)
let rValue: DatabaseValue = rItem.row.value(named: column)
let lValue: DatabaseValue = lItem.row[column]
let rValue: DatabaseValue = rItem.row[column]
if lValue != rValue {
// different primary keys
return false
}
if !lValue.isNull || !rValue.isNull {
notNullValue = true
}
}
// identical primary keys
return true
// identical primary keys iff at least one value is not null
return notNullValue
}
}
try self.init(
@@ -559,7 +577,7 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
// MARK: - Changes
fileprivate func makeFetchFunction<Record, T>(
private func makeFetchFunction<Record, T>(
controller: FetchedRecordsController<Record>,
fetchAlongside: @escaping (Database) throws -> T,
willProcessTransaction: @escaping () -> (),
@@ -634,7 +652,7 @@ fileprivate func makeFetchFunction<Record, T>(
}
}
fileprivate func makeFetchAndNotifyChangesFunction<Record, T>(
private func makeFetchAndNotifyChangesFunction<Record, T>(
controller: FetchedRecordsController<Record>,
fetchAlongside: @escaping (Database) throws -> T,
itemsAreIdentical: @escaping ItemComparator<Record>,
@@ -704,7 +722,7 @@ fileprivate func makeFetchAndNotifyChangesFunction<Record, T>(
}
}
fileprivate func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] {
private func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] {
let m = s.count
let n = t.count
@@ -776,7 +794,7 @@ fileprivate func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Reco
func changedValues(from oldRow: Row, to newRow: Row) -> [String: DatabaseValue] {
var changedValues: [String: DatabaseValue] = [:]
for (column, newValue) in newRow {
let oldValue: DatabaseValue? = oldRow.value(named: column)
let oldValue: DatabaseValue? = oldRow[column]
if newValue != oldValue {
changedValues[column] = oldValue
}
@@ -840,7 +858,7 @@ fileprivate func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Reco
return standardize(changes: d[m][n], itemsAreIdentical: itemsAreIdentical)
}
fileprivate func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item<Record>]) -> Bool {
private func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item<Record>]) -> Bool {
guard lhs.count == rhs.count else {
return false
}
@@ -855,8 +873,8 @@ fileprivate func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item
// MARK: - UITableView Support
fileprivate typealias ItemComparator<Record: RowConvertible> = (Item<Record>, Item<Record>) -> Bool
fileprivate typealias ItemComparatorFactory<Record: RowConvertible> = (Database) throws -> ItemComparator<Record>
private typealias ItemComparator<Record: RowConvertible> = (Item<Record>, Item<Record>) -> Bool
private typealias ItemComparatorFactory<Record: RowConvertible> = (Database) throws -> ItemComparator<Record>
extension FetchedRecordsController {
+194
View File
@@ -0,0 +1,194 @@
private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncodingContainerProtocol {
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
init(encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
self.encode = encode
}
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey] { return [] }
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
mutating func encode(_ value: Bool, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int8, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int16, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int32, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Int64, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt8, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt16, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt32, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: UInt64, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Float, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: Double, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encode(_ value: String, forKey key: Key) throws { encode(value, key.stringValue) }
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
mutating func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
if T.self is DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible encoding over Decodable.
// This allows us to encode Date as String, for example.
encode((value as! DatabaseValueConvertible), key.stringValue)
} else {
try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode))
}
}
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
fatalError("Not implemented")
}
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
fatalError("Not implemented")
}
/// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder {
fatalError("Not implemented")
}
/// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder(forKey key: Key) -> Encoder {
fatalError("Not implemented")
}
}
private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
let key: CodingKey
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
var codingPath: [CodingKey] { return [key] }
/// 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.
func encodeNil() throws { encode(nil, key.stringValue) }
/// 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.
func encode(_ value: Bool) throws { encode(value, key.stringValue) }
func encode(_ value: Int) throws { encode(value, key.stringValue) }
func encode(_ value: Int8) throws { encode(value, key.stringValue) }
func encode(_ value: Int16) throws { encode(value, key.stringValue) }
func encode(_ value: Int32) throws { encode(value, key.stringValue) }
func encode(_ value: Int64) throws { encode(value, key.stringValue) }
func encode(_ value: UInt) throws { encode(value, key.stringValue) }
func encode(_ value: UInt8) throws { encode(value, key.stringValue) }
func encode(_ value: UInt16) throws { encode(value, key.stringValue) }
func encode(_ value: UInt32) throws { encode(value, key.stringValue) }
func encode(_ value: UInt64) throws { encode(value, key.stringValue) }
func encode(_ value: Float) throws { encode(value, key.stringValue) }
func encode(_ value: Double) throws { encode(value, key.stringValue) }
func encode(_ value: String) throws { encode(value, key.stringValue) }
/// 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.
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, key.stringValue)
} else {
try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode))
}
}
}
private struct PersistableEncoder : Encoder {
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey]
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey : Any] = [:]
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
init(codingPath: [CodingKey], encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
self.codingPath = codingPath
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> {
// Asked for a keyed type: top level required
guard codingPath.isEmpty else {
fatalError("unkeyed encoding is not supported")
}
return KeyedEncodingContainer(PersistableKeyedEncodingContainer<Key>(encode: encode))
}
/// 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(key: codingPath.last!, encode: encode)
}
}
extension MutablePersistable where Self: Encodable {
public func encode(to container: inout PersistenceContainer) {
// The inout container parameter won't enter an escaping closure since
// SE-0035: https://github.com/apple/swift-evolution/blob/master/proposals/0035-limit-inout-capture.md
//
// So let's use it in a non-escaping closure:
func encode(_ encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
withoutActuallyEscaping(encode) { escapableEncode in
let encoder = PersistableEncoder(codingPath: [], encode: escapableEncode)
try! self.encode(to: encoder)
}
}
encode { (value, key) in container[key] = value }
}
}
+148 -20
View File
@@ -1,3 +1,15 @@
extension Database.ConflictResolution {
var invalidatesLastInsertedRowID: Bool {
switch self {
case .abort, .fail, .rollback, .replace:
return false
case .ignore:
// Statement may have succeeded without inserting any row
return true
}
}
}
// MARK: - PersistenceError
/// An error thrown by a type that adopts Persistable.
@@ -18,13 +30,12 @@ extension PersistenceError : CustomStringConvertible {
}
}
// MARK: - PersistenceContainer
/// Use persistence containers in the `encode(to:)` method of your
/// persistable records:
///
/// struct Person : MutablePersistable {
/// struct Player : MutablePersistable {
/// var id: Int64?
/// var name: String?
///
@@ -38,12 +49,20 @@ public struct PersistenceContainer {
fileprivate var storage: [String: DatabaseValueConvertible?]
/// Accesses the value associated with the given column.
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
public subscript(_ column: String) -> DatabaseValueConvertible? {
get { return storage[column] ?? nil }
set { storage.updateValue(newValue, forKey: column) }
}
/// Accesses the value associated with the given column.
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
public subscript(_ column: Column) -> DatabaseValueConvertible? {
get { return self[column.name] }
set { self[column.name] = newValue }
@@ -124,7 +143,6 @@ extension Row {
}
}
// MARK: - MutablePersistable
/// The MutablePersistable protocol uses this type in order to handle SQLite
@@ -170,7 +188,7 @@ public protocol MutablePersistable : TableMapping {
///
/// Primary key columns, if any, must be included.
///
/// struct Person : MutablePersistable {
/// struct Player : MutablePersistable {
/// var id: Int64?
/// var name: String?
///
@@ -179,6 +197,10 @@ public protocol MutablePersistable : TableMapping {
/// container["name"] = name
/// }
/// }
///
/// It is undefined behavior to set different values for the same column.
/// Column names are case insensitive, so defining both "name" and "NAME"
/// is considered undefined behavior.
func encode(to container: inout PersistenceContainer)
/// Notifies the record that it was succesfully inserted.
@@ -189,7 +211,7 @@ public protocol MutablePersistable : TableMapping {
///
/// This method is optional: the default implementation does nothing.
///
/// struct Person : MutablePersistable {
/// struct Player : MutablePersistable {
/// var id: Int64?
/// var name: String?
///
@@ -203,7 +225,6 @@ public protocol MutablePersistable : TableMapping {
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
mutating func didInsert(with rowID: Int64, for column: String?)
// MARK: - CRUD
/// Executes an INSERT statement.
@@ -289,6 +310,13 @@ public protocol MutablePersistable : TableMapping {
func exists(_ db: Database) throws -> Bool
}
extension MutablePersistable {
/// A dictionary whose keys are the columns encoded in the `encode(to:)` method.
public var databaseDictionary: [String: DatabaseValue] {
return PersistenceContainer(self).storage.mapValues { $0?.databaseValue ?? .null }
}
}
extension MutablePersistable {
/// Describes the conflict policy for insertions and updates.
///
@@ -304,7 +332,6 @@ extension MutablePersistable {
public mutating func didInsert(with rowID: Int64, for column: String?) {
}
// MARK: - CRUD
/// Executes an INSERT statement.
@@ -332,7 +359,7 @@ extension MutablePersistable {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == Column {
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Element == Column {
try update(db, columns: Set(columns.map { $0.name }))
}
@@ -343,7 +370,7 @@ extension MutablePersistable {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == String {
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Element == String {
try update(db, columns: Set(columns))
}
@@ -383,13 +410,12 @@ extension MutablePersistable {
return try performExists(db)
}
// MARK: - CRUD Internals
/// Return true if record has a non-null primary key
fileprivate func canUpdate(_ db: Database) throws -> Bool {
let databaseTableName = type(of: self).databaseTableName
let primaryKey = try db.primaryKey(databaseTableName) ?? PrimaryKeyInfo.hiddenRowID
let primaryKey = try db.primaryKey(databaseTableName)
let container = PersistenceContainer(self)
for column in primaryKey.columns {
if let value = container[caseInsensitive: column], !value.databaseValue.isNull {
@@ -502,15 +528,117 @@ extension MutablePersistable {
}
extension Database.ConflictResolution {
var invalidatesLastInsertedRowID: Bool {
switch self {
case .abort, .fail, .rollback, .replace:
return false
case .ignore:
// Statement may have succeeded without inserting any row
return true
extension MutablePersistable {
// MARK: - Deleting All
/// Deletes all records; returns the number of deleted rows.
///
/// - parameter db: A database connection.
/// - returns: The number of deleted rows
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public static func deleteAll(_ db: Database) throws -> Int {
return try all().deleteAll(db)
}
}
extension MutablePersistable {
// MARK: - Deleting by Single-Column Primary Key
/// Delete records identified by their primary keys; returns the number of
/// deleted rows.
///
/// // DELETE FROM players WHERE id IN (1, 2, 3)
/// try Player.deleteAll(db, keys: [1, 2, 3])
///
/// // DELETE FROM countries WHERE code IN ('FR', 'US', 'DE')
/// try Country.deleteAll(db, keys: ["FR", "US", "DE"])
///
/// When the table has no explicit primary key, GRDB uses the hidden
/// "rowid" column:
///
/// // DELETE FROM documents WHERE rowid IN (1, 2, 3)
/// try Document.deleteAll(db, keys: [1, 2, 3])
///
/// - parameters:
/// - db: A database connection.
/// - keys: A sequence of primary keys.
/// - returns: The number of deleted rows
@discardableResult
public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible {
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return 0
}
return try filter(db, keys: keys).deleteAll(db)
}
/// Delete a record, identified by its primary key; returns whether a
/// database row was deleted.
///
/// // DELETE FROM players WHERE id = 123
/// try Player.deleteOne(db, key: 123)
///
/// // DELETE FROM countries WHERE code = 'FR'
/// try Country.deleteOne(db, key: "FR")
///
/// When the table has no explicit primary key, GRDB uses the hidden
/// "rowid" column:
///
/// // DELETE FROM documents WHERE rowid = 1
/// try Document.deleteOne(db, key: 1)
///
/// - parameters:
/// - db: A database connection.
/// - key: A primary key value.
/// - returns: Whether a database row was deleted.
@discardableResult
public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool {
guard let key = key else {
// Avoid hitting the database
return false
}
return try deleteAll(db, keys: [key]) > 0
}
}
extension MutablePersistable {
// MARK: - Deleting by Key
/// Delete records identified by the provided unique keys (primary key or
/// any key with a unique index on it); returns the number of deleted rows.
///
/// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
///
/// - parameters:
/// - db: A database connection.
/// - keys: An array of key dictionaries.
/// - returns: The number of deleted rows
@discardableResult
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
if keys.isEmpty {
// Avoid hitting the database
return 0
}
return try filter(db, keys: keys).deleteAll(db)
}
/// Delete a record, identified by a unique key (the primary key or any key
/// with a unique index on it); returns whether a database row was deleted.
///
/// Player.deleteOne(db, key: ["name": Arthur"])
///
/// - parameters:
/// - db: A database connection.
/// - key: A dictionary of values.
/// - returns: Whether a database row was deleted.
@discardableResult
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
return try deleteAll(db, keys: [key]) > 0
}
}
@@ -679,7 +807,7 @@ final class DAO {
init(_ db: Database, _ record: MutablePersistable) throws {
let databaseTableName = type(of: record).databaseTableName
let primaryKey = try db.primaryKey(databaseTableName) ?? PrimaryKeyInfo.hiddenRowID
let primaryKey = try db.primaryKey(databaseTableName)
let persistenceContainer = PersistenceContainer(record)
GRDBPrecondition(!persistenceContainer.isEmpty, "\(type(of: record)): invalid empty persistence container")
+54 -15
View File
@@ -30,9 +30,9 @@ open class Record : RowConvertible, TableMapping, Persistable {
/// This table name is required by the insert, update, save, delete,
/// and exists methods.
///
/// class Person : Record {
/// class Player : Record {
/// override class var databaseTableName: String {
/// return "persons"
/// return "players"
/// }
/// }
///
@@ -60,20 +60,37 @@ open class Record : RowConvertible, TableMapping, Persistable {
return PersistenceConflictPolicy(insert: .abort, update: .abort)
}
/// This flag tells whether the hidden "rowid" column should be fetched
/// with other columns.
/// The default request selection.
///
/// Its default value is false:
/// Unless this method is overriden, requests select all columns:
///
/// // SELECT * FROM persons
/// try Person.fetchAll(db)
/// // SELECT * FROM players
/// try Player.fetchAll(db)
///
/// When true, the rowid column is fetched:
/// You can override this property and provide an explicit list
/// of columns:
///
/// // SELECT *, rowid FROM persons
/// try Person.fetchAll(db)
open class var selectsRowID: Bool {
return false
/// class RestrictedPlayer : Record {
/// override static var databaseSelection: [SQLSelectable] {
/// return [Column("id"), Column("name")]
/// }
/// }
///
/// // SELECT id, name FROM players
/// try RestrictedPlayer.fetchAll(db)
///
/// You can also add extra columns such as the `rowid` column:
///
/// class ExtendedPlayer : Player {
/// override static var databaseSelection: [SQLSelectable] {
/// return [AllColumns(), Column.rowID]
/// }
/// }
///
/// // SELECT *, rowid FROM players
/// try ExtendedPlayer.fetchAll(db)
open class var databaseSelection: [SQLSelectable] {
return [AllColumns()]
}
@@ -84,7 +101,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
///
/// Primary key columns, if any, must be included.
///
/// class Person : Record {
/// class Player : Record {
/// var id: Int64?
/// var name: String?
///
@@ -107,7 +124,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
///
/// The implementation of the base Record class does nothing.
///
/// class Person : Record {
/// class Player : Record {
/// var id: Int64?
/// var name: String?
///
@@ -196,7 +213,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let new = newValue?.databaseValue ?? .null
guard let oldRow = oldRow, let old: DatabaseValue = oldRow.value(named: column) else {
guard let oldRow = oldRow, let old: DatabaseValue = oldRow[column] else {
return (column: column, old: nil)
}
if new != old {
@@ -284,6 +301,28 @@ open class Record : RowConvertible, TableMapping, Persistable {
referenceRow = Row(dao.persistenceContainer)
}
/// If the record has been changed, executes an UPDATE statement so that
/// those changes and only those changes are saved in the database.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
///
/// This method is guaranteed to have saved the eventual changes in the
/// database if it returns without error.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
final public func updateChanges(_ db: Database) throws {
let changedColumns = Set(persistentChangedValues.keys)
guard !changedColumns.isEmpty else {
return
}
try update(db, columns: changedColumns)
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
///
+217
View File
@@ -0,0 +1,217 @@
private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
let row: Row
init(row: Row) {
self.row = row
}
/// The path of coding keys taken to get to this point in decoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey] { return [] }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
var allKeys: [Key] {
return row.columnNames.flatMap { Key(stringValue: $0) }
}
/// Returns whether the `Decoder` contains a value associated with the given key.
///
/// The value associated with the given key may be a null value as appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool {
return row.hasColumn(key.stringValue)
}
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
func decodeNil(forKey key: Key) throws -> Bool {
return row[key.stringValue] == nil
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return row[key.stringValue] }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return row[key.stringValue] }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return row[key.stringValue] }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return row[key.stringValue] }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return row[key.stringValue] }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return row[key.stringValue] }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return row[key.stringValue] }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return row[key.stringValue] }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return row[key.stringValue] }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return row[key.stringValue] }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return row[key.stringValue] }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return row[key.stringValue] }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return row[key.stringValue] }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return row[key.stringValue] }
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
let dbValue: DatabaseValue = row[key.stringValue]
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(dbValue) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
}
}
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container.
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError("Not implemented")
}
/// Returns the data stored for the given key as represented in an unkeyed container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container.
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
fatalError("Not implemented")
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key.
public func superDecoder() throws -> Decoder {
fatalError("Not implemented")
}
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
public func superDecoder(forKey key: Key) throws -> Decoder {
fatalError("Not implemented")
}
}
private struct RowSingleValueDecodingContainer: SingleValueDecodingContainer {
let row: Row
let column: CodingKey
var codingPath: [CodingKey] { return [] }
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
func decodeNil() -> Bool {
return row[column.stringValue] == nil
}
/// 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 row[column.stringValue] }
func decode(_ type: Int.Type) throws -> Int { return row[column.stringValue] }
func decode(_ type: Int8.Type) throws -> Int8 { return row[column.stringValue] }
func decode(_ type: Int16.Type) throws -> Int16 { return row[column.stringValue] }
func decode(_ type: Int32.Type) throws -> Int32 { return row[column.stringValue] }
func decode(_ type: Int64.Type) throws -> Int64 { return row[column.stringValue] }
func decode(_ type: UInt.Type) throws -> UInt { return row[column.stringValue] }
func decode(_ type: UInt8.Type) throws -> UInt8 { return row[column.stringValue] }
func decode(_ type: UInt16.Type) throws -> UInt16 { return row[column.stringValue] }
func decode(_ type: UInt32.Type) throws -> UInt32 { return row[column.stringValue] }
func decode(_ type: UInt64.Type) throws -> UInt64 { return row[column.stringValue] }
func decode(_ type: Float.Type) throws -> Float { return row[column.stringValue] }
func decode(_ type: Double.Type) throws -> Double { return row[column.stringValue] }
func decode(_ type: String.Type) throws -> String { return row[column.stringValue] }
/// 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 decoding Date from String, or DatabaseValue from NULL.
return type.fromDatabaseValue(row[column.stringValue]) as! T
} else {
return try T(from: RowDecoder(row: row, codingPath: [column]))
}
}
}
private struct RowDecoder: Decoder {
let row: Row
init(row: Row, codingPath: [CodingKey]) {
self.row = row
self.codingPath = codingPath
}
// Decoder
let codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any] { return [:] }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
// Asked for a keyed type: top level required
guard codingPath.isEmpty else {
throw DecodingError.typeMismatch(
RowDecoder.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "nested decoding is not supported"))
}
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(row: row))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
// Asked for a value type: column name required
guard let codingKey = codingPath.last else {
throw DecodingError.typeMismatch(
RowDecoder.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "single value decoding requires a coding key"))
}
return RowSingleValueDecodingContainer(row: row, column: codingKey)
}
}
extension RowConvertible where Self: Decodable {
/// Initializes a record from `row`.
public init(row: Row) {
try! self.init(from: RowDecoder(row: row, codingPath: []))
}
}
+44 -112
View File
@@ -4,8 +4,9 @@ extension RowConvertible where Self: TableMapping {
/// A cursor over all records fetched from the database.
///
/// let persons = try Person.fetchCursor(db) // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// // SELECT * FROM players
/// let players = try Player.fetchCursor(db) // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
///
@@ -16,16 +17,25 @@ extension RowConvertible where Self: TableMapping {
///
/// The cursor must be iterated in a protected dispath queue.
///
/// 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.
///
/// - parameter db: A database connection.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database) throws -> DatabaseCursor<Self> {
public static func fetchCursor(_ db: Database) throws -> RecordCursor<Self> {
return try all().fetchCursor(db)
}
/// An array of all records fetched from the database.
///
/// let persons = try Person.fetchAll(db) // [Person]
/// // SELECT * FROM players
/// let players = try Player.fetchAll(db) // [Player]
///
/// 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.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@@ -35,7 +45,12 @@ extension RowConvertible where Self: TableMapping {
/// The first found record.
///
/// let person = try Person.fetchOne(db) // Person?
/// // SELECT * FROM players
/// let player = try Player.fetchOne(db) // Player?
///
/// 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.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@@ -50,8 +65,8 @@ extension RowConvertible where Self: TableMapping {
/// Returns a cursor over records, given their primary keys.
///
/// let persons = try Person.fetchCursor(db, keys: [1, 2, 3]) // DatabaseCursor<Person>
/// while let person = try persons.next() {
/// let players = try Player.fetchCursor(db, keys: [1, 2, 3]) // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
///
@@ -62,16 +77,13 @@ extension RowConvertible where Self: TableMapping {
/// - keys: A sequence of primary keys.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> DatabaseCursor<Self>? where Sequence.Iterator.Element: DatabaseValueConvertible {
guard let statement = try makeFetchByPrimaryKeyStatement(db, keys: keys) else {
return nil
}
return try fetchCursor(statement)
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence.Element: DatabaseValueConvertible {
return try filter(db, keys: keys).fetchCursor(db)
}
/// Returns an array of records, given their primary keys.
///
/// let persons = try Person.fetchAll(db, keys: [1, 2, 3]) // [Person]
/// let players = try Player.fetchAll(db, keys: [1, 2, 3]) // [Player]
///
/// The order of records in the returned array is undefined.
///
@@ -80,16 +92,18 @@ extension RowConvertible where Self: TableMapping {
/// - keys: A sequence of primary keys.
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Iterator.Element: DatabaseValueConvertible {
guard let statement = try makeFetchByPrimaryKeyStatement(db, keys: keys) else {
public static func fetchAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Element: DatabaseValueConvertible {
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return []
}
return try fetchAll(statement)
return try filter(db, keys: keys).fetchAll(db)
}
/// Returns a single record given its primary key.
///
/// let person = try Person.fetchOne(db, key: 123) // Person?
/// let player = try Player.fetchOne(db, key: 123) // Player?
///
/// - parameters:
/// - db: A database connection.
@@ -98,43 +112,10 @@ extension RowConvertible where Self: TableMapping {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Self? {
guard let key = key else {
// Avoid hitting the database
return nil
}
return try fetchOne(makeFetchByPrimaryKeyStatement(db, keys: [key])!)
}
// Returns "SELECT * FROM table WHERE id IN (?,?,?)"
//
// Returns nil if values is empty.
private static func makeFetchByPrimaryKeyStatement<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> SelectStatement? where Sequence.Iterator.Element: DatabaseValueConvertible {
// Fail early if database table does not exist.
let databaseTableName = self.databaseTableName
let primaryKey = try db.primaryKey(databaseTableName)
// Fail early if database table has not one column in its primary key
let columns = primaryKey?.columns ?? []
GRDBPrecondition(columns.count <= 1, "requires single column primary key in table: \(databaseTableName)")
let column = columns.first ?? Column.rowID.name
let keys = Array(keys)
switch keys.count {
case 0:
// Avoid performing useless SELECT
return nil
case 1:
// SELECT * FROM table WHERE id = ?
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
let statement = try db.makeSelectStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
case let count:
// SELECT * FROM table WHERE id IN (?,?,?)
let keysSQL = databaseQuestionMarks(count: count)
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))"
let statement = try db.makeSelectStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
}
return try filter(db, keys: [key]).fetchOne(db)
}
}
@@ -145,8 +126,8 @@ extension RowConvertible where Self: TableMapping {
/// Returns a cursor over records identified by the provided unique keys
/// (primary key or any key with a unique index on it).
///
/// let persons = try Person.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// let players = try Player.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
///
@@ -157,17 +138,14 @@ extension RowConvertible where Self: TableMapping {
/// - keys: An array of key dictionaries.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> DatabaseCursor<Self>? {
guard let statement = try makeFetchByKeyStatement(db, keys: keys) else {
return nil
}
return try fetchCursor(statement)
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor<Self> {
return try filter(db, keys: keys).fetchCursor(db)
}
/// Returns an array of records identified by the provided unique keys
/// (primary key or any key with a unique index on it).
///
/// let persons = try Person.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Person]
/// let players = try Player.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Player]
///
/// The order of records in the returned array is undefined.
///
@@ -177,16 +155,18 @@ extension RowConvertible where Self: TableMapping {
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] {
guard let statement = try makeFetchByKeyStatement(db, keys: keys) else {
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return []
}
return try fetchAll(statement)
return try filter(db, keys: keys).fetchAll(db)
}
/// Returns a single record identified by a unique key (the primary key or
/// any key with a unique index on it).
///
/// let person = try Person.fetchOne(db, key: ["name": Arthur"]) // Person?
/// let player = try Player.fetchOne(db, key: ["name": Arthur"]) // Player?
///
/// - parameters:
/// - db: A database connection.
@@ -194,54 +174,6 @@ extension RowConvertible where Self: TableMapping {
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? {
return try fetchOne(makeFetchByKeyStatement(db, keys: [key])!)
}
// Returns "SELECT * FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
//
// Returns nil if keys is empty.
//
// If there is no unique index on the columns, the method raises a fatal
// (unless fatalErrorOnMissingUniqueIndex is false, for testability).
static func makeFetchByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> SelectStatement? {
// Avoid performing useless SELECT
guard keys.count > 0 else {
return nil
}
let databaseTableName = self.databaseTableName
var arguments: [DatabaseValueConvertible?] = []
var whereClauses: [String] = []
for dictionary in keys {
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
let columns = Array(dictionary.keys)
guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else {
let error = DatabaseError(resultCode: .SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))")
if fatalErrorOnMissingUniqueIndex {
// Programmer error
fatalError(error.description)
} else {
throw error
}
}
arguments.append(contentsOf: orderedColumns.map { orderedColumn in
dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value
})
whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
}
let whereClause = whereClauses.joined(separator: " OR ")
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
let statement = try db.makeSelectStatement(sql)
statement.arguments = StatementArguments(arguments)
return statement
}
fileprivate static var defaultSelection: String {
if selectsRowID {
return "*, rowid"
} else {
return "*"
}
return try filter(db, keys: [key]).fetchOne(db)
}
}
+66 -29
View File
@@ -1,19 +1,25 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Types that adopt RowConvertible can be initialized from a database Row.
///
/// let row = try Row.fetchOne(db, "SELECT ...")!
/// let person = Person(row)
/// let player = Player(row)
///
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single records:
///
/// try Person.fetchCursor(db, "SELECT ...", arguments:...) // DatabaseCursor<Person>
/// try Person.fetchAll(db, "SELECT ...", arguments:...) // [Person]
/// try Person.fetchOne(db, "SELECT ...", arguments:...) // Person?
/// try Player.fetchCursor(db, "SELECT ...", arguments:...) // Cursor of Player
/// try Player.fetchAll(db, "SELECT ...", arguments:...) // [Player]
/// try Player.fetchOne(db, "SELECT ...", arguments:...) // Player?
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// try Person.fetchCursor(statement, arguments:...) // DatabaseCursor<Person>
/// try Person.fetchAll(statement, arguments:...) // [Person]
/// try Person.fetchOne(statement, arguments:...) // Person?
/// try Player.fetchCursor(statement, arguments:...) // Cursor of Player
/// try Player.fetchAll(statement, arguments:...) // [Player]
/// try Player.fetchOne(statement, arguments:...) // Player?
///
/// RowConvertible is adopted by Record.
public protocol RowConvertible {
@@ -26,15 +32,49 @@ public protocol RowConvertible {
init(row: Row)
}
/// A cursor of records. For example:
///
/// struct Player : RowConvertible { ... }
/// try dbQueue.inDatabase { db in
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM players")
/// }
public final class RecordCursor<Record: RowConvertible> : Cursor {
private let statement: SelectStatement
private let row: Row // Reused for performance
private let sqliteStatement: SQLiteStatement
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 -> Record? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
return Record(row: row)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
extension RowConvertible {
// MARK: Fetching From SelectStatement
/// A cursor over records fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
/// let persons = try Person.fetchCursor(statement) // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// let statement = try db.makeSelectStatement("SELECT * FROM players")
/// let players = try Player.fetchCursor(statement) // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
///
@@ -49,17 +89,14 @@ extension RowConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
// Reuse a single mutable row for performance.
// It is the record's responsibility to copy the row if needed.
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
return statement.cursor(arguments: arguments, next: { self.init(row: row) })
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
return try RecordCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of records fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
/// let persons = try Person.fetchAll(statement) // [Person]
/// let statement = try db.makeSelectStatement("SELECT * FROM players")
/// let players = try Player.fetchAll(statement) // [Player]
///
/// - parameters:
/// - statement: The statement to run.
@@ -73,8 +110,8 @@ extension RowConvertible {
/// Returns a single record fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
/// let person = try Person.fetchOne(statement) // Person?
/// let statement = try db.makeSelectStatement("SELECT * FROM players")
/// let player = try Player.fetchOne(statement) // Player?
///
/// - parameters:
/// - statement: The statement to run.
@@ -94,8 +131,8 @@ extension RowConvertible {
/// Returns a cursor over records fetched from a fetch request.
///
/// let nameColumn = Column("firstName")
/// let request = Person.order(nameColumn)
/// let identities = try Identity.fetchCursor(db, request) // DatabaseCursor<Identity>
/// let request = Player.order(nameColumn)
/// let identities = try Identity.fetchCursor(db, request) // Cursor of Identity
/// while let identity = try identities.next() { // Identity
/// ...
/// }
@@ -110,7 +147,7 @@ extension RowConvertible {
/// - request: A fetch request.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
public static func fetchCursor(_ db: Database, _ request: Request) throws -> RecordCursor<Self> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
@@ -118,7 +155,7 @@ extension RowConvertible {
/// Returns an array of records fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.order(nameColumn)
/// let request = Player.order(nameColumn)
/// let identities = try Identity.fetchAll(db, request) // [Identity]
///
/// - parameter db: A database connection.
@@ -131,7 +168,7 @@ extension RowConvertible {
/// Returns a single record fetched from a fetch request.
///
/// let nameColumn = Column("name")
/// let request = Person.order(nameColumn)
/// let request = Player.order(nameColumn)
/// let identity = try Identity.fetchOne(db, request) // Identity?
///
/// - parameter db: A database connection.
@@ -148,8 +185,8 @@ extension RowConvertible {
/// Returns a cursor over records fetched from an SQL query.
///
/// let persons = try Person.fetchCursor(db, "SELECT * FROM persons") // DatabaseCursor<Person>
/// while let person = try persons.next() { // Person
/// let players = try Player.fetchCursor(db, "SELECT * FROM players") // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
///
@@ -165,13 +202,13 @@ extension RowConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of records fetched from an SQL query.
///
/// let persons = try Person.fetchAll(db, "SELECT * FROM persons") // [Person]
/// let players = try Player.fetchAll(db, "SELECT * FROM players") // [Player]
///
/// - parameters:
/// - db: A database connection.
@@ -186,7 +223,7 @@ extension RowConvertible {
/// Returns a single record fetched from an SQL query.
///
/// let person = try Person.fetchOne(db, "SELECT * FROM persons") // Person?
/// let player = try Player.fetchOne(db, "SELECT * FROM players") // Player?
///
/// - parameters:
/// - db: A database connection.
+79 -211
View File
@@ -4,32 +4,56 @@
/// Types that adopt both TableMapping and RowConvertible are granted with
/// built-in methods that allow to fetch instances identified by key:
///
/// try Person.fetchOne(db, key: 123) // Person?
/// try Citizenship.fetchOne(db, key: ["personId": 12, "countryId": 45]) // Citizenship?
/// try Player.fetchOne(db, key: 123) // Player?
/// try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship?
///
/// TableMapping is adopted by Record.
public protocol TableMapping {
/// The name of the database table
/// The name of the database table used to build requests.
///
/// struct Player : TableMapping {
/// static var databaseTableName = "players"
/// }
///
/// // SELECT * FROM players
/// try Player.fetchAll(db)
static var databaseTableName: String { get }
/// This flag tells whether the hidden "rowid" column should be fetched
/// with other columns.
/// The default request selection.
///
/// Its default value is false:
/// Unless said otherwise, requests select all columns:
///
/// // SELECT * FROM persons
/// try Person.fetchAll(db)
/// // SELECT * FROM players
/// try Player.fetchAll(db)
///
/// When true, the rowid column is fetched:
/// You can provide a custom implementation and provide an explicit list
/// of columns:
///
/// // SELECT *, rowid FROM persons
/// try Person.fetchAll(db)
static var selectsRowID: Bool { get }
/// struct RestrictedPlayer : TableMapping {
/// static var databaseTableName = "players"
/// static var databaseSelection = [Column("id"), Column("name")]
/// }
///
/// // SELECT id, name FROM players
/// try RestrictedPlayer.fetchAll(db)
///
/// You can also add extra columns such as the `rowid` column:
///
/// struct ExtendedPlayer : TableMapping {
/// static var databaseTableName = "players"
/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
/// }
///
/// // SELECT *, rowid FROM players
/// try ExtendedPlayer.fetchAll(db)
static var databaseSelection: [SQLSelectable] { get }
}
extension TableMapping {
/// Default value: false.
public static var selectsRowID: Bool { return false }
/// Default value: `[AllColumns()]`.
public static var databaseSelection: [SQLSelectable] {
return [AllColumns()]
}
}
extension TableMapping {
@@ -46,219 +70,63 @@ extension TableMapping {
extension TableMapping {
// MARK: Deleting All
// MARK: Key Requests
/// Deletes all records; returns the number of deleted rows.
///
/// - parameter db: A database connection.
/// - returns: The number of deleted rows
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public static func deleteAll(_ db: Database) throws -> Int {
return try all().deleteAll(db)
}
}
extension TableMapping {
// MARK: Deleting by Single-Column Primary Key
/// Delete records identified by their primary keys; returns the number of
/// deleted rows.
///
/// try Person.deleteAll(db, keys: [1, 2, 3])
///
/// - parameters:
/// - db: A database connection.
/// - keys: A sequence of primary keys.
/// - returns: The number of deleted rows
@discardableResult
public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Iterator.Element: DatabaseValueConvertible {
guard let statement = try makeDeleteByPrimaryKeyStatement(db, keys: keys) else {
return 0
}
try statement.execute()
return db.changesCount
}
/// Delete a record, identified by its primary key; returns whether a
/// database row was deleted.
///
/// try Person.deleteOne(db, key: 123)
///
/// - parameters:
/// - db: A database connection.
/// - key: A primary key value.
/// - returns: Whether a database row was deleted.
@discardableResult
public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool {
guard let key = key else {
return false
}
return try deleteAll(db, keys: [key]) > 0
}
// Returns "DELETE FROM table WHERE id IN (?,?,?)"
//
// Returns nil if keys is empty.
private static func makeDeleteByPrimaryKeyStatement<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> UpdateStatement? where Sequence.Iterator.Element: DatabaseValueConvertible {
// Fail early if database table does not exist.
let databaseTableName = self.databaseTableName
static func filter<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
let primaryKey = try db.primaryKey(databaseTableName)
// Fail early if database table has not one column in its primary key
let columns = primaryKey?.columns ?? []
GRDBPrecondition(columns.count <= 1, "requires single column primary key in table: \(databaseTableName)")
let column = columns.first ?? Column.rowID.name
let columns = primaryKey.columns.map { Column($0) }
GRDBPrecondition(columns.count == 1, "table \(databaseTableName) has multiple columns in its primary key")
let column = columns[0]
let keys = Array(keys)
switch keys.count {
case 0:
// Avoid performing useless DELETE
return nil
return none()
case 1:
// DELETE FROM table WHERE id = ?
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
let statement = try db.makeUpdateStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
case let count:
// DELETE FROM table WHERE id IN (?,?,?)
let keysSQL = databaseQuestionMarks(count: count)
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))"
let statement = try db.makeUpdateStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
return filter(column == keys[0])
default:
return filter(keys.contains(column))
}
}
}
extension TableMapping {
// MARK: Deleting by Key
/// Delete records identified by the provided unique keys (primary key or
/// any key with a unique index on it); returns the number of deleted rows.
///
/// try Person.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
///
/// - parameters:
/// - db: A database connection.
/// - keys: An array of key dictionaries.
/// - returns: The number of deleted rows
@discardableResult
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
guard let statement = try makeDeleteByKeyStatement(db, keys: keys) else {
return 0
}
try statement.execute()
return db.changesCount
}
/// Delete a record, identified by a unique key (the primary key or any key
/// with a unique index on it); returns whether a database row was deleted.
///
/// Person.deleteOne(db, key: ["name": Arthur"])
///
/// - parameters:
/// - db: A database connection.
/// - key: A dictionary of values.
/// - returns: Whether a database row was deleted.
@discardableResult
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
return try deleteAll(db, keys: [key]) > 0
}
// Returns "DELETE FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
// Raises a fatal error if there is no unique index on the columns (unless
// fatalErrorOnMissingUniqueIndex is false, for testability).
//
// Returns nil if keys is empty.
//
// If there is no unique index on the columns, the method raises a fatal
// (unless fatalErrorOnMissingUniqueIndex is false, for testability).
static func makeDeleteByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> UpdateStatement? {
// Avoid performing useless SELECT
guard keys.count > 0 else {
return nil
}
let databaseTableName = self.databaseTableName
var arguments: [DatabaseValueConvertible?] = []
var whereClauses: [String] = []
for dictionary in keys {
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
let columns = Array(dictionary.keys)
guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else {
let error = DatabaseError(resultCode: .SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))")
// TODO: think about
// - allowing non unique keys in Type.fetchOne(db, key: ...) ???
// - allowing non unique keys in Type.fetchAll/Cursor(db, keys: ...)
// - forbidding nil values: Player.deleteOne(db, key: ["email": nil]) may delete several rows (case of a nullable unique key)
static func filter(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> QueryInterfaceRequest<Self> {
// SELECT * FROM table WHERE ((a=? AND b=?) OR (c=? AND d=?) OR ...)
let keyPredicates: [SQLExpression] = try keys.map { key in
// Prevent filter(db, keys: [[:]])
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
// Prevent filter(db, keys: [["foo": 1, "bar": 2]]) where
// ("foo", "bar") is not a unique key (primary key or columns of a
// unique index)
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
let message = "table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))"
if fatalErrorOnMissingUniqueIndex {
fatalError(error.description)
fatalError(message)
} else {
throw error
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: message)
}
}
arguments.append(contentsOf: orderedColumns.map { orderedColumn in
dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value
})
whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
let columnPredicates: [SQLExpression] = key
// Sort key columns in the same order as the unique index
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
.map { (column, value) in Column(column) == value }
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
}
let whereClause = whereClauses.joined(separator: " OR ")
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
let statement = try db.makeUpdateStatement(sql)
statement.arguments = StatementArguments(arguments)
return statement
}
}
extension TableMapping {
/// Returns a function that returns the primary key of a row.
///
/// If the table has no primary key, and selectsRowID is true, the primary
/// key is the "rowid" column.
///
/// try dbQueue.inDatabase { db in
/// let primaryKey = try Person.rowPrimaryKey(db)
/// let row = try Row.fetchOne(db, "SELECT * FROM persons")!
/// primaryKey(row) // ["id": 1]
/// }
///
/// - throws: A DatabaseError if table does not exist.
static func rowPrimaryKey(_ db: Database) throws -> (Row) -> [String: DatabaseValue] {
if let primaryKey = try db.primaryKey(databaseTableName) {
let columns = primaryKey.columns
return { row in Dictionary(keys: columns) { row.value(named: $0) } }
} else if selectsRowID {
return { row in [Column.rowID.name: row.value(Column.rowID)] }
} else {
return { _ in [:] }
}
}
/// Returns a function that returns true if and only if two rows have the
/// same primary key and both primary keys contain at least one non-null
/// value.
///
/// try dbQueue.inDatabase { db in
/// let comparator = try Person.primaryKeyRowComparator(db)
/// let row0 = Row(["id": nil, "name": "Unsaved"])
/// let row1 = Row(["id": 1, "name": "Arthur"])
/// let row2 = Row(["id": 1, "name": "Arthur"])
/// let row3 = Row(["id": 2, "name": "Barbara"])
/// comparator(row0, row0) // false
/// comparator(row1, row2) // true
/// comparator(row1, row3) // false
/// }
///
/// - throws: A DatabaseError if table does not exist.
/// - attention: This method is deprecated. It will be removed is the next
/// major version of the library, without any replacement.
@available(*, deprecated)
public static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool {
let primaryKey = try rowPrimaryKey(db)
return { (lhs, rhs) in
let (lhs, rhs) = (primaryKey(lhs), primaryKey(rhs))
guard lhs.contains(where: { !$1.isNull }) else { return false }
guard rhs.contains(where: { !$1.isNull }) else { return false }
return lhs == rhs
}
guard let predicate = SQLBinaryOperator.or.join(keyPredicates) else {
// No key
return none()
}
return filter(predicate)
}
}
-24
View File
@@ -1,9 +1,5 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#endif
// MARK: - Public
extension String {
@@ -48,8 +44,6 @@ func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosu
/// 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.
if !condition() {
fatalError(message, file: file, line: line)
}
@@ -69,21 +63,3 @@ extension Array {
}
}
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)
}
}
}
+4 -4
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '1.2'
s.version = '2.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
@@ -13,12 +13,12 @@ Pod::Spec.new do |s|
s.osx.deployment_target = '10.9'
s.watchos.deployment_target = '2.0'
s.source_files = 'GRDB/**/*.swift', 'SQLCipher/*.h', 'Support/grdb_config.{c,h}'
s.source_files = 'GRDB/**/*.swift', 'SQLCipher/*.h', 'Support/grdb_config.h'
s.module_map = 'SQLCipher/module.modulemap'
s.xcconfig = {
'OTHER_SWIFT_FLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER',
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_HAS_CODEC -D GRDBCIPHER',
'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER',
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) SQLITE_HAS_CODEC=1'
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) SQLITE_HAS_CODEC=1 GRDBCIPHER=1'
}
s.framework = 'Foundation'
s.dependency 'SQLCipher', '~> 3.4.1'
+12 -18
View File
@@ -48,12 +48,9 @@ MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=8.1"
ifeq ($(XCODEVERSION),9.0)
# xcodebuild destination to run tests on latest iOS (Xcode 9.0)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 7,OS=11.0"
else ifeq ($(XCODEVERSION),8.3)
# xcodebuild destination to run tests on latest iOS (Xcode 8.3.3)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 7,OS=10.3.1"
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
else
# Xcode < 8.3 is not supported
# Xcode < 9.0 is not supported
endif
# If xcpretty is available, use it for xcodebuild output
@@ -204,7 +201,7 @@ test_install_GRDBCipher: SQLCipher
test_install_SPM:
cd Tests/SPM && \
$(SWIFT) package reset && \
( if [ -a .build ] && [ -a Package.resolved ]; then $(SWIFT) package reset; fi ) && \
rm -rf Packages/GRDB && \
$(SWIFT) package edit GRDB --revision master && \
rm -rf Packages/GRDB && \
@@ -233,13 +230,13 @@ endif
test_performance: Realm FMDB SQLite.swift
$(XCODEBUILD) \
-project GRDB.xcodeproj \
-scheme GRDBOSXPerformanceTests \
-scheme GRDBOSXPerformanceComparisonTests \
build-for-testing test-without-building
Realm: Tests/Performance/Realm/build/osx/swift-3.1/RealmSwift.framework
Realm: Tests/Performance/Realm/build/osx/swift-4.0/RealmSwift.framework
# Makes sure the Tests/Performance/Realm submodule has been downloaded, and Realm framework has been built.
Tests/Performance/Realm/build/osx/swift-3.1/RealmSwift.framework:
Tests/Performance/Realm/build/osx/swift-4.0/RealmSwift.framework:
$(GIT) submodule update --init --recursive Tests/Performance/Realm
cd Tests/Performance/Realm && sh build.sh osx-swift
@@ -288,10 +285,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v1.2 \
--module-version 1.2 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.0 \
--module-version 2.0 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/1.2/ \
--root-url http://groue.github.io/GRDB.swift/docs/2.0/ \
--output Documentation/Reference \
--podspec GRDB.swift.podspec
else
@@ -304,16 +301,13 @@ endif
# =======
distclean:
$(SWIFT) package reset
cd Tests/SPM && $(SWIFT) package reset
rm -rf Documentation/Reference
$(GIT) reset --hard
$(GIT) clean -dffx .
rm -rf Tests/Performance/fmdb && $(GIT) checkout -- Tests/Performance/fmdb
rm -rf Tests/Performance/SQLite.swift && $(GIT) checkout -- Tests/Performance/SQLite.swift
rm -rf Tests/Performance/Realm && $(GIT) checkout -- Tests/Performance/Realm
rm -rf SQLCipher/src && $(GIT) checkout -- SQLCipher/src
rm -rf SQLiteCustom/src && $(GIT) checkout -- SQLiteCustom/src
find . -name xcuserdata | xargs rm -rf
find . -name Package.pins | xargs rm -f
clean:
$(SWIFT) package reset
@@ -321,6 +315,6 @@ clean:
rm -rf Documentation/Reference
if [ -d SQLCipher/src ]; then cd SQLCipher/src && $(GIT) clean -f; fi
if [ -a Tests/Performance/Realm/build.sh ]; then cd Tests/Performance/Realm && sh build.sh clean; fi
find . -name Package.pins | xargs rm -f
find . -name Package.resolved | xargs rm -f
.PHONY: distclean clean doc test SQLCipher SQLiteCustom
+22 -16
View File
@@ -1,23 +1,29 @@
// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "GRDB",
dependencies: [
.Package(url: "https://github.com/groue/CSQLite.git", majorVersion: 0, minor: 2)
products: [
.library(name: "GRDB", targets: ["GRDB"]),
],
exclude: [
"DemoApps",
"Documentation",
"GRDB.xcworkspace",
"Playgrounds",
"SQLCipher",
"SQLiteCustom",
"Support",
"Tests/Carthage",
"Tests/CocoaPods",
"Tests/Crash",
"Tests/GRDBCipher",
"Tests/Performance",
"Tests/SPM"
dependencies: [
.package(url: "https://github.com/groue/CSQLite.git", from: "0.2.0"),
],
targets: [
.target(name: "GRDB", path: "GRDB"),
.testTarget(
name: "GRDBTests",
dependencies: ["GRDB"],
path: "Tests",
exclude: [
"Carthage",
"CocoaPods",
"Crash",
"GRDBCipher",
"Performance",
"SPM"
])
]
)
@@ -21,42 +21,50 @@ let dbQueue = DatabaseQueue(configuration: configuration)
// Create a database table
try dbQueue.inDatabase { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT " +
")")
try db.create(table: "players") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text)
t.column("score", .integer)
}
}
// Define the Person subclass of GRDB's Record.
// Define the Player subclass of GRDB's Record.
//
// Record provides change tracking that helps avoiding useless
// UPDATE statements.
class Person : Record {
var id: Int64?
var name: String?
// Record provides change tracking that helps avoiding useless UPDATE statements.
class Player : Record {
var id: Int64
var name: String
var score: Int
convenience init(json: [String : Any]) {
// For convenience, assume JSON keys are database columns, and reuse row initializer
self.init(row: Row(json)!)
}
func update(from json: [String: Any]) {
id = (json["id"] as! NSNumber).int64Value
name = (json["name"] as! String)
id = json["id"] as! Int64
name = json["name"] as! String
score = json["score"] as! Int
}
// Record overrides
override class var databaseTableName: String {
return "persons"
return "players"
}
required init(row: Row) {
id = row.value(named: "id")
name = row.value(named: "name")
id = row["id"]
name = row["name"]
score = row["score"]
super.init(row: row)
}
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?) {
@@ -65,88 +73,87 @@ class Person : Record {
}
// Synchronizes the persons table with a JSON payload
func synchronizePersons(with jsonString: String, in db: Database) throws {
// Synchronizes the players table with a JSON payload
func synchronizePlayers(with jsonString: String, in db: Database) throws {
let jsonData = jsonString.data(using: .utf8)!
let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any]
// A support function that extracts an ID from a JSON person.
func jsonPersonId(_ jsonPerson: [String: Any]) -> Int64 {
return (jsonPerson["id"] as! NSNumber).int64Value
// A support function that extracts an ID from a JSON player.
func jsonPlayerId(_ jsonPlayer: [String: Any]) -> Int64 {
return jsonPlayer["id"] as! Int64
}
// Sort JSON persons by id:
let jsonPersons = (json["persons"] as! [[String: Any]]).sorted {
return jsonPersonId($0) < jsonPersonId($1)
// Sort JSON players by id:
let jsonPlayers = (json["players"] as! [[String: Any]]).sorted {
return jsonPlayerId($0) < jsonPlayerId($1)
}
// Sort database persons by id:
let persons = try Person.fetchAll(db, "SELECT * FROM persons ORDER BY id")
// Sort database players by id:
let players = try Player.order(Column("id")).fetchAll(db)
// Now that both lists are sorted by id, we can compare them with
// the sortedMerge() function (see https://gist.github.com/groue/7e8510849ded36f7d770).
//
// We'll delete, insert or update persons, depending on their presence
// We'll delete, insert or update players, depending on their presence
// in either lists.
for mergeStep in sortedMerge(
left: persons, // Database persons
right: jsonPersons, // JSON persons
leftKey: { $0.id! }, // The id of a database person
rightKey: jsonPersonId) // The id of a JSON person
left: players, // Database players
right: jsonPlayers, // JSON players
leftKey: { $0.id }, // The id of a database player
rightKey: jsonPlayerId) // The id of a JSON player
{
switch mergeStep {
case .left(let person):
// Delete database person without matching JSON person:
try person.delete(db)
case .right(let jsonPerson):
// Insert JSON person without matching database person:
let row = Row(jsonPerson)! // Granted JSON keys are database columns
let person = Person(row: row)
try person.insert(db)
case .common(let person, let jsonPerson):
// Update database person with its JSON counterpart:
person.update(from: jsonPerson)
if person.hasPersistentChangedValues {
try person.update(db)
}
case .left(let player):
// Delete database player without matching JSON player:
try player.delete(db)
case .right(let jsonPlayer):
// Insert JSON player without matching database player:
let player = Player(json: jsonPlayer)
try player.insert(db)
case .common(let player, let jsonPlayer):
// Update database player with its JSON counterpart:
player.update(from: jsonPlayer)
try player.updateChanges(db)
}
}
}
do {
let jsonString =
"{ \"persons\": [" +
"{ \"id\": 1, \"name\": \"Arthur\"}, " +
"{ \"id\": 2, \"name\": \"Barbara\"}, " +
"{ \"id\": 3, \"name\": \"Craig\"}, " +
"]" +
"}"
let jsonString = """
{
"players": [
{ "id": 1, "name": "Arthur", "score": 1000},
{ "id": 2, "name": "Barbara", "score": 2000},
{ "id": 3, "name": "Craig", "score": 500},
]
}
"""
print("---\nImport \(jsonString)")
try dbQueue.inTransaction { db in
// SELECT * FROM persons ORDER BY id
// INSERT INTO "persons" ("id","name") VALUES (1,'Arthur')
// INSERT INTO "persons" ("id","name") VALUES (2,'Barbara')
// INSERT INTO "persons" ("id","name") VALUES (3,'Craig')
try synchronizePersons(with: jsonString, in: db)
return .commit
try dbQueue.inDatabase { db in
// SELECT * FROM players ORDER BY id
// INSERT INTO "players" ("id", "name", "score") VALUES (1,'Arthur',1000)
// INSERT INTO "players" ("id", "name", "score") VALUES (2,'Barbara',2000)
// INSERT INTO "players" ("id", "name", "score") VALUES (3,'Craig',500)
try synchronizePlayers(with: jsonString, in: db)
}
}
do {
let jsonString =
"{ \"persons\": [" +
"{ \"id\": 2, \"name\": \"Barbie\"}, " +
"{ \"id\": 3, \"name\": \"Craig\"}, " +
"{ \"id\": 4, \"name\": \"Daniel\"}, " +
"]" +
"}"
let jsonString = """
{
"players": [
{ "id": 2, "name": "Barbara", "score": 3000},
{ "id": 3, "name": "Craig", "score": 500},
{ "id": 4, "name": "Daniel", "score": 1500},
]
}
"""
print("---\nImport \(jsonString)")
try dbQueue.inTransaction { db in
// SELECT * FROM persons ORDER BY id
// DELETE FROM "persons" WHERE "id"=1
// UPDATE "persons" SET "name"='Barbie' WHERE "id"=2
// INSERT INTO "persons" ("id","name") VALUES (4,'Daniel')
try synchronizePersons(with: jsonString, in: db)
return .commit
try dbQueue.inDatabase { db in
// SELECT * FROM players ORDER BY id
// DELETE FROM "players" WHERE "id"=1
// UPDATE "players" SET "score"=3000 WHERE "id"=2
// INSERT INTO "players" ("id", "name", "score") VALUES (4,'Daniel',1500)
try synchronizePlayers(with: jsonString, in: db)
}
}
@@ -42,10 +42,10 @@
public func sortedMerge<LeftSequence: Sequence, RightSequence: Sequence, Key: Comparable>(
left lSeq: LeftSequence,
right rSeq: RightSequence,
leftKey: @escaping (LeftSequence.Iterator.Element) -> Key,
rightKey: @escaping (RightSequence.Iterator.Element) -> Key) -> AnySequence<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>>
leftKey: @escaping (LeftSequence.Element) -> Key,
rightKey: @escaping (RightSequence.Element) -> Key) -> AnySequence<MergeStep<LeftSequence.Element, RightSequence.Element>>
{
return AnySequence { () -> AnyIterator<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>> in
return AnySequence { () -> AnyIterator<MergeStep<LeftSequence.Element, RightSequence.Element>> in
var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator())
var (lOpt, rOpt) = (lGen.next(), rGen.next())
return AnyIterator {
+3 -3
View File
@@ -60,9 +60,9 @@ class Person : Record {
//: 2. How to build a Person from a database row:
required init(row: Row) {
id = row.value(named: "id")
firstName = row.value(named: "firstName")
lastName = row.value(named: "lastName")
id = row["id"]
firstName = row["firstName"]
lastName = row["lastName"]
super.init(row: row)
}
+9 -9
View File
@@ -42,11 +42,11 @@ try dbQueue.inDatabase { db in
try dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, "SELECT * FROM pointOfInterests")
while let row = try rows.next() {
let title: String = row.value(named: "title")
let favorite: Bool = row.value(named: "favorite")
let title: String = row["title"]
let favorite: Bool = row["favorite"]
let coordinate = CLLocationCoordinate2DMake(
row.value(named: "latitude"),
row.value(named: "longitude"))
row["latitude"],
row["longitude"])
print("Fetched", title, favorite, coordinate)
}
@@ -67,12 +67,12 @@ struct PointOfInterest {
// Adopt RowConvertible
extension PointOfInterest : RowConvertible {
init(row: Row) {
id = row.value(named: "id")
title = row.value(named: "title")
favorite = row.value(named: "favorite")
id = row["id"]
title = row["title"]
favorite = row["favorite"]
coordinate = CLLocationCoordinate2DMake(
row.value(named: "latitude"),
row.value(named: "longitude"))
row["latitude"],
row["longitude"])
}
}
+935 -716
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -6,7 +6,10 @@ FOUNDATION_EXPORT double GRDB_VersionNumber;
//! Project version string for GRDB.
FOUNDATION_EXPORT const unsigned char GRDB_VersionString[];
#ifndef SQLITE_HAS_CODEC
#define SQLITE_HAS_CODEC
#endif
#import <GRDBCipher/GRDBCipher-Bridging.h>
#ifdef COCOAPODS
#import <SQLCipher/sqlite3.h>
File renamed without changes.
+1 -1
View File
@@ -7,4 +7,4 @@ FOUNDATION_EXPORT double GRDB_VersionNumber;
FOUNDATION_EXPORT const unsigned char GRDB_VersionString[];
#import <GRDB/GRDB-Bridging.h>
#import <GRDB/sqlite3.h>
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.2</string>
<string>2.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
-12
View File
@@ -1,12 +0,0 @@
#if GRDBCIPHER && defined(COCOAPODS)
#include <GRDBCipher/grdb_config.h>
#include <SQLCipher/sqlite3.h>
#else
#include <GRDB/grdb_config.h>
#include <GRDB/sqlite3.h>
#endif
void registerErrorLogCallback(errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
+19 -1
View File
@@ -1,10 +1,28 @@
#ifndef grdb_config_h
#define grdb_config_h
#if defined(COCOAPODS)
#if defined(GRDBCIPHER)
#include <SQLCipher/sqlite3.h>
#else
#include <sqlite3.h>
#endif
#else
#if defined(GRDBCIPHER)
#include <GRDBCipher/sqlite3.h>
#elsif defined(GRDBCUSTOMSQLITE)
#include <GRDBCustom/sqlite3.h>
#else
#include <sqlite3.h>
#endif
#endif
typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg);
// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic
// function that can't be used from Swift.
void registerErrorLogCallback(errorLogCallback callback);
static inline void registerErrorLogCallback(errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
#endif /* grdb_config_h */
-8828
View File
File diff suppressed because it is too large. Load diff
+5 -1
View File
@@ -11,9 +11,13 @@
- [ ] GLOB https://www.sqlite.org/lang_expr.html
- [ ] REGEXP https://www.sqlite.org/lang_expr.html
- [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html
- [ ] See how we can use [sqlite3_get_autocommit](https://www.sqlite.org/capi3ref.html#sqlite3_get_autocommit)
- [ ] Write regression tests for #156 and #157
GRDB 2.0
- [ ] Document Record.updateChanges(_:)
- [ ] WIP on diff algorithms in RxGRDB needs access to MutablePersistable.databaseDictionary. The problem is that one should not need a writing protocol just to read. So consider introducing a new DatabaseEncodable protocol above MutablePersistable. It does not grant any writing methods. But it has encode(to:) and databaseDictionary.
Not sure
- [ ] Support for resource values (see https://developer.apple.com/library/ios/qa/qa1719/_index.html)
@@ -81,14 +81,14 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase {
func testCrashDatabaseValueConvertibleInvalidConversionFromNULL() {
assertCrash("could not convert NULL to IntConvertible.") {
let row = Row(["int": nil])
_ = row.value(named: "int") as IntConvertible
_ = row["int"] as IntConvertible
}
}
func testCrashDatabaseValueConvertibleInvalidConversionFromInvalidType() {
assertCrash("could not convert \"foo\" to IntConvertible") {
let row = Row(["int": "foo"])
_ = row.value(named: "int") as IntConvertible
_ = row["int"] as IntConvertible
}
}
@@ -18,9 +18,9 @@ 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)
}
+3 -2
View File
@@ -42,12 +42,13 @@ class AnyCursorTests: GRDBTestCase {
}
func testAnyCursorFromCursor() {
var i = 0
let base = IteratorCursor([0, 1])
// This helper function makes sure AnyCursor initializer accepts any cursor,
// and not only IteratorCursor:
func makeAnyCursor<C: Cursor>(_ cursor: C) -> AnyCursor<Int> where C.Element == Int {
return AnyCursor(cursor)
}
let cursor = makeAnyCursor(base)
let cursor = AnyCursor(base)
XCTAssertEqual(try cursor.next()!, 0)
XCTAssertEqual(try cursor.next()!, 1)
XCTAssertTrue(try cursor.next() == nil) // end
Loaded 100 of 199 files, more files were not shown because too many files have changed in this diff. Show more