Merge branch 'master' of github.com:groue/GRDB.swift into Swift3bis

Conflicts:
	GRDB.xcodeproj/project.pbxproj
	GRDB/Core/Database.swift
	GRDB/Core/DatabaseSchemaCache.swift
	GRDB/Core/Utils.swift
	GRDB/Record/TableMapping.swift
	README.md
	Tests/Private/DatabasePoolSchemaCacheTests.swift
	Tests/Public/Encryption/EncryptionTests.swift
	Tests/Public/Record/PrimaryKeyNoneTests.swift
This commit is contained in:
Gwendal Roué committed 2016-07-07 08:41:17 +02:00
commit b24075ca1c
16 files changed
+691 -89

No files matched your search

+33
View File
@@ -1,6 +1,39 @@
Release Notes
=============
## 0.74.0
Released July 6, 2016
**New**
- TableMapping protocol lets you delete rows identified by their primary keys, or any columns involved in a unique index (closes [#56](https://github.com/groue/GRDB.swift/issues/56), [documentation](https://github.com/groue/GRDB.swift/tree/Issue56#tablemapping-protocol)):
```swift
try Person.deleteOne(db, key: 1)
try Person.deleteOne(db, key: ["email": "arthur@example.com"])
try Citizenship.deleteOne(db, key: ["personID": 1, "countryCode": "FR"])
try Country.deleteAll(db, keys: ["FR", "US"])
```
**Breaking change**
- The `fetch(_:keys:)`, `fetchAll(_:keys:)` and `fetchOne(_:key:)` methods used to accept any dictionary of column/value pairs to identify rows. Now these methods raise a fatal error if the columns are not guaranteed, at the database level, to uniquely identify rows: columns must be the primary key, or involved in a unique index:
```swift
// CREATE TABLE persons (
// id INTEGER PRIMARY KEY, -- can fetch and delete by id
// email TEXT UNIQUE, -- can fetch and delete by email
// name TEXT -- nope
// )
Person.fetchOne(db, key: ["id": 1]) // Person?
Person.fetchOne(db, key: ["email": "arthur@example.com"]) // Person?
Person.fetchOne(db, key: ["name": "Arthur"]) // fatal error: table persons has no unique index on column name.
```
This change harmonizes the behavior of those fetching methods with the new `deleteOne(_:key:)` and `deleteAll(_:keys:)`.
## 0.73.0
Released June 20, 2016
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '0.73.0'
s.version = '0.74.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A versatile SQLite toolkit for Swift, with WAL mode support.'
s.homepage = 'https://github.com/groue/GRDB.swift'
+44 -2
View File
@@ -421,7 +421,6 @@
567156641CB16729007DC145 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
567156651CB16729007DC145 /* DatabaseQueueFileAttributesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363DB1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift */; };
567156671CB16729007DC145 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 560FC54D1CB003810014AA8E /* GRDBCipher.framework */; };
567156711CB18050007DC145 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
5672DE591CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */; };
5672DE5A1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */; };
5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */; };
@@ -439,6 +438,10 @@
5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; };
5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; };
567404931CF02B56003ED5CC /* AdapterRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */; };
567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567E55EE1D2BDD3F00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567E55F41D2BDDFF00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
5683C2691B4D445E00296494 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5683C2681B4D445E00296494 /* libsqlite3.dylib */; };
5687359F1CEDE16C009B9116 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; };
568735A01CEDE16C009B9116 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; };
@@ -781,7 +784,6 @@
56AFCACF1CB1ABC800F48B96 /* StatementInformationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementInformationTests.swift */; };
56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
56AFCAD21CB1ABC800F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; };
56AFCAD91CB1AC5C00F48B96 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
56B15D0B1CD4C35100A24C8B /* FetchedRecordsControlleriOSTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControlleriOSTests.swift */; };
56B15D0C1CD4C35100A24C8B /* FetchedRecordsControlleriOSTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControlleriOSTests.swift */; };
56B15D0D1CD4C35100A24C8B /* FetchedRecordsControlleriOSTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControlleriOSTests.swift */; };
@@ -841,6 +843,22 @@
56FC78691BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC78651BBAEB8C00CA1285 /* ManagedDataControllerTests.swift */; };
56FDECE21BB32DFD009AD709 /* MetalRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */; };
56FDECE31BB32DFD009AD709 /* MetalRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */; };
56FF45401D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; };
56FF45411D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; };
56FF45421D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; };
56FF45431D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; };
56FF45441D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; };
56FF45451D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; };
56FF45461D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; };
56FF45471D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */; };
56FF45561D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */; };
56FF45571D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */; };
56FF45581D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */; };
56FF45591D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */; };
56FF455A1D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */; };
56FF455B1D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */; };
56FF455C1D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */; };
56FF455D1D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */; };
DC2393C81ABE35F8003FF113 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
DC3773F919C8CBB3004FCF85 /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; };
DC70AC991AC2331000371524 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = DC37744219C8DC91004FCF85 /* libsqlite3.dylib */; };
@@ -1491,6 +1509,8 @@
56FC78641BBAEB8C00CA1285 /* MappingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MappingTests.swift; sourceTree = "<group>"; };
56FC78651BBAEB8C00CA1285 /* ManagedDataControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ManagedDataControllerTests.swift; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalRowTests.swift; sourceTree = "<group>"; };
56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeleteByKeyTests.swift; sourceTree = "<group>"; };
56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UniqueIndexTests.swift; sourceTree = "<group>"; };
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "../GRDB/GRDB-Bridging.h"; sourceTree = "<group>"; };
DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; };
DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
@@ -1873,6 +1893,7 @@
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */,
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */,
5605F1861C69111300235C62 /* StatementInformationTests.swift */,
56FF45551D2CDA5200F21EF9 /* UniqueIndexTests.swift */,
);
path = Private;
sourceTree = "<group>";
@@ -1996,6 +2017,7 @@
56A238251B9C74A90082EB20 /* Record */ = {
isa = PBXGroup;
children = (
56FF453F1D2C23BA00F21EF9 /* DeleteByKeyTests.swift */,
56A238261B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift */,
56A238271B9C74A90082EB20 /* MinimalPrimaryKeySingleTests.swift */,
56A238281B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift */,
@@ -3077,6 +3099,7 @@
files = (
560FC5611CB00B880014AA8E /* DatabaseValueConversionTests.swift in Sources */,
560FC5B31CB031EA0014AA8E /* DataMemoryTests.swift in Sources */,
56FF45411D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */,
560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */,
560FC5641CB00B880014AA8E /* DatabaseQueueConcurrencyTests.swift in Sources */,
56A8C2411D1918EE0096E9D4 /* NSUUIDTests.swift in Sources */,
@@ -3120,6 +3143,7 @@
5657AB471D108BA9006283EF /* NSNullTests.swift in Sources */,
560FC5811CB00B880014AA8E /* RecordCopyTests.swift in Sources */,
560FC5821CB00B880014AA8E /* RawRepresentableTests.swift in Sources */,
567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */,
560FC5841CB00B880014AA8E /* PersistableTests.swift in Sources */,
560FC5851CB00B880014AA8E /* ManagedDataControllerTests.swift in Sources */,
560FC5861CB00B880014AA8E /* MappingTests.swift in Sources */,
@@ -3159,6 +3183,7 @@
560FC5A41CB00B880014AA8E /* RecordWithColumnNameManglingTests.swift in Sources */,
5690C3271D23E6D800E59934 /* DateComponentsTests.swift in Sources */,
560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */,
56FF45571D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */,
560FC5A61CB00B880014AA8E /* StatementInformationTests.swift in Sources */,
5690C3381D23E7D200E59934 /* DateTests.swift in Sources */,
560FC5A71CB00B880014AA8E /* GRDBTestCase.swift in Sources */,
@@ -3189,6 +3214,7 @@
files = (
5671561D1CB16729007DC145 /* DatabaseValueConversionTests.swift in Sources */,
5671561E1CB16729007DC145 /* DataMemoryTests.swift in Sources */,
56FF45421D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */,
5671561F1CB16729007DC145 /* Record+QueryInterfaceRequestTests.swift in Sources */,
567156211CB16729007DC145 /* DatabaseQueueConcurrencyTests.swift in Sources */,
567156221CB16729007DC145 /* StatementColumnConvertibleFetchTests.swift in Sources */,
@@ -3228,6 +3254,7 @@
5671563C1CB16729007DC145 /* MutablePersistableTests.swift in Sources */,
5671563D1CB16729007DC145 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */,
5671563E1CB16729007DC145 /* DatabasePoolReadOnlyTests.swift in Sources */,
567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */,
5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */,
567156401CB16729007DC145 /* RawRepresentableTests.swift in Sources */,
567156411CB16729007DC145 /* PersistableTests.swift in Sources */,
@@ -3273,6 +3300,7 @@
5634B0751CF22BEF005360B9 /* FetchRequestTests.swift in Sources */,
567156601CB16729007DC145 /* FunctionTests.swift in Sources */,
567156611CB16729007DC145 /* RecordWithColumnNameManglingTests.swift in Sources */,
56FF45581D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */,
567156621CB16729007DC145 /* CGFloatTests.swift in Sources */,
567156631CB16729007DC145 /* StatementInformationTests.swift in Sources */,
567156641CB16729007DC145 /* GRDBTestCase.swift in Sources */,
@@ -3349,6 +3377,7 @@
56AFCA341CB1AA9900F48B96 /* DictionaryRowTests.swift in Sources */,
569C1EB61CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */,
56AFCA351CB1AA9900F48B96 /* DatabaseCoderTests.swift in Sources */,
567E55EE1D2BDD3F00CC6F79 /* EncryptionTests.swift in Sources */,
56AFCA361CB1AA9900F48B96 /* CollationTests.swift in Sources */,
56AFCA371CB1AA9900F48B96 /* StatementColumnConvertibleFetchTests.swift in Sources */,
56AFCA381CB1AA9900F48B96 /* SQLSupportTests.swift in Sources */,
@@ -3358,6 +3387,7 @@
56AFCA3D1CB1AA9900F48B96 /* RecordAwakeFromFetchTests.swift in Sources */,
5657AB4B1D108BA9006283EF /* NSNullTests.swift in Sources */,
56AFCA3E1CB1AA9900F48B96 /* DatabasePoolCollationTests.swift in Sources */,
56FF455B1D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */,
56AFCA3F1CB1AA9900F48B96 /* PrimaryKeySingleTests.swift in Sources */,
56AFCA401CB1AA9900F48B96 /* RecordFetchTests.swift in Sources */,
56AFCA411CB1AA9900F48B96 /* StatementColumnConvertibleTests.swift in Sources */,
@@ -3383,6 +3413,7 @@
5672DE5D1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */,
56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */,
56AFCA511CB1AA9900F48B96 /* ManagedDataControllerTests.swift in Sources */,
56FF45451D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */,
56AFCA521CB1AA9900F48B96 /* PersistableTests.swift in Sources */,
56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */,
56AFCA541CB1AA9900F48B96 /* MappingTests.swift in Sources */,
@@ -3447,6 +3478,7 @@
56AFCA8E1CB1ABC800F48B96 /* DatabaseCoderTests.swift in Sources */,
5657AB541D108BA9006283EF /* NSNumberTests.swift in Sources */,
56AFCA8F1CB1ABC800F48B96 /* CollationTests.swift in Sources */,
567E55F41D2BDDFF00CC6F79 /* EncryptionTests.swift in Sources */,
56AFCA901CB1ABC800F48B96 /* StatementColumnConvertibleFetchTests.swift in Sources */,
5690C33D1D23E7D200E59934 /* DateTests.swift in Sources */,
5672DE6C1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */,
@@ -3458,6 +3490,7 @@
56AFCAD91CB1AC5C00F48B96 /* EncryptionTests.swift in Sources */,
EE50758B1D00E617005D9C5B /* DatabaseValue+FoundationTests.swift in Sources */,
5657AB641D108BA9006283EF /* NSURLTests.swift in Sources */,
56FF455C1D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */,
56AFCA961CB1ABC800F48B96 /* RecordAwakeFromFetchTests.swift in Sources */,
56AFCA971CB1ABC800F48B96 /* DatabasePoolCollationTests.swift in Sources */,
5657AB5C1D108BA9006283EF /* NSStringTests.swift in Sources */,
@@ -3485,6 +3518,7 @@
569178421CED8E0D00E179EA /* FetchedRecordsControllerTests.swift in Sources */,
56A8C24B1D1918F10096E9D4 /* NSUUIDTests.swift in Sources */,
56AFCAAB1CB1ABC800F48B96 /* PersistableTests.swift in Sources */,
56FF45461D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */,
56AFCAAC1CB1ABC800F48B96 /* DatabaseValueConversionTests.swift in Sources */,
56AFCAAD1CB1ABC800F48B96 /* MappingTests.swift in Sources */,
5657AB441D108BA9006283EF /* NSDataTests.swift in Sources */,
@@ -3595,6 +3629,7 @@
files = (
56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */,
56F26C1C1CEE3F32007969C4 /* AdapterRowTests.swift in Sources */,
56FF45441D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */,
56A238561B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */,
563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */,
56A238501B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
@@ -3679,6 +3714,7 @@
560C97C81BFD0B8400BF8471 /* FunctionTests.swift in Sources */,
56A2383A1B9C74A90082EB20 /* InMemoryDatabaseTests.swift in Sources */,
56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */,
56FF455A1D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */,
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */,
5605F1881C69111300235C62 /* StatementInformationTests.swift in Sources */,
569178491CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */,
@@ -3697,6 +3733,7 @@
56A2384F1B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
56A8C23F1D1918ED0096E9D4 /* NSUUIDTests.swift in Sources */,
5657AB561D108BA9006283EF /* NSStringTests.swift in Sources */,
56FF45561D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */,
561667011D08A49900ADD404 /* NSDecimalNumberTests.swift in Sources */,
569C1EB21CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */,
56A238451B9C74A90082EB20 /* DictionaryRowTests.swift in Sources */,
@@ -3730,6 +3767,7 @@
56A2385D1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */,
5657AB5E1D108BA9006283EF /* NSURLTests.swift in Sources */,
5672DE591CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */,
56FF45401D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */,
56A238431B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */,
56EB0AB21BCD787300A3DC55 /* DataMemoryTests.swift in Sources */,
5657AB461D108BA9006283EF /* NSNullTests.swift in Sources */,
@@ -3902,6 +3940,7 @@
files = (
F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */,
F3BA80C81CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */,
56FF45471D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */,
F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */,
F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */,
F3BA811E1CFB3063003DC1BA /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
@@ -3986,6 +4025,7 @@
F3BA81141CFB305E003DC1BA /* QueryInterfaceRequestTests.swift in Sources */,
F3BA81271CFB3063003DC1BA /* RecordEditedTests.swift in Sources */,
F3BA81081CFB3056003DC1BA /* DatabaseCoderTests.swift in Sources */,
56FF455D1D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */,
F3BA80C71CFB2FD8003DC1BA /* DatabaseQueueFileAttributesTests.swift in Sources */,
F3BA80C51CFB2FD8003DC1BA /* DatabaseQueueBackupTests.swift in Sources */,
F3BA80B31CFB2FC9003DC1BA /* InMemoryDatabaseTests.swift in Sources */,
@@ -4061,6 +4101,7 @@
F3BA812C1CFB3064003DC1BA /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
56A8C2451D1918EF0096E9D4 /* NSUUIDTests.swift in Sources */,
5657AB591D108BA9006283EF /* NSStringTests.swift in Sources */,
56FF45591D2CDA5200F21EF9 /* UniqueIndexTests.swift in Sources */,
561667041D08A49900ADD404 /* NSDecimalNumberTests.swift in Sources */,
F3BA80BF1CFB2FD2003DC1BA /* DatabasePoolBackupTests.swift in Sources */,
F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
@@ -4093,6 +4134,7 @@
F3BA811C1CFB305F003DC1BA /* SQLSupportTests.swift in Sources */,
5657AB611D108BA9006283EF /* NSURLTests.swift in Sources */,
F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */,
56FF45431D2C23BA00F21EF9 /* DeleteByKeyTests.swift in Sources */,
F3BA80F01CFB3017003DC1BA /* RowConvertibleTests.swift in Sources */,
F3BA80A71CFB2F9D003DC1BA /* MappingTests.swift in Sources */,
5657AB491D108BA9006283EF /* NSNullTests.swift in Sources */,
+57 -12
View File
@@ -768,17 +768,6 @@ extension Database {
// =========================================================================
// MARK: - Database Schema
/// The protocol for schema cache.
///
/// This protocol must not contain values that are valid for a single connection
/// only, because several connections can share the same schema cache.
protocol DatabaseSchemaCache {
mutating func clear()
func primaryKey(_ tableName: String) -> PrimaryKey??
mutating func set(primaryKey: PrimaryKey?, for tableName: String)
}
extension Database {
/// Clears the database schema cache.
@@ -901,6 +890,50 @@ extension Database {
return primaryKey
}
/// The indexes on table named `tableName`; returns the empty array if the
/// table does not exist.
///
/// Note: SQLite defines no index for INTEGER PRIMARY KEY columns: this
/// method does not return any index that represents this unique constraint.
///
/// If you want to know if a set of columns uniquely identify a row, prefer
/// columns(_:uniquelyIdentifyRowsIn:) instead.
func indexes(on tableName: String) -> [IndexInfo] {
if let indexes = schemaCache.indexes(on: tableName) {
return indexes
}
let indexes = Row.fetch(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 columns = Row.fetch(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.map { ($0.value(atIndex: 0) as Int, $0.value(atIndex: 2) as String) }
.sorted { $0.0 < $1.0 }
.map { $0.1 }
return IndexInfo(name: indexName, columns: columns, unique: unique)
}
schemaCache.set(indexes: indexes, forTableName: tableName)
return indexes
}
/// True if a set of columns uniquely identify a row, that is to say if
/// there is a unique index on those columns, or if the column is the
/// INTEGER PRIMARY KEY.
func columns<T: Sequence where T.Iterator.Element == String>(_ columns: T, uniquelyIdentifyRowsIn tableName: String) throws -> Bool {
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
let columns = Set(columns)
if indexes(on: tableName).contains({ index in index.isUnique && Set(index.columns) == columns }) {
return true
}
if columns.count == 1,
let rowIDColumnName = primaryKey?.rowIDColumn
where rowIDColumnName == columns.first! {
return true
}
return false
}
// CREATE TABLE persons (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
@@ -927,6 +960,18 @@ extension Database {
primaryKeyIndex = row.value(named: "pk")
}
}
struct IndexInfo {
let name: String
let columns: [String]
let isUnique: Bool
init(name: String, columns: [String], unique: Bool) {
self.name = name
self.columns = columns
self.isUnique = unique
}
}
}
/// You get primary keys from table names, with the Database.primaryKey(_)
@@ -1038,7 +1083,7 @@ final class StatementCompilationObserver {
let observerPointer = unsafeBitCast(self, to: UnsafeMutablePointer<Void>.self)
sqlite3_set_authorizer(database.sqliteConnection, { (observerPointer, actionCode, CString1, CString2, CString3, CString4) -> Int32 in
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:
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)
observer.invalidatesDatabaseSchemaCache = true
case SQLITE_READ:
+35 -4
View File
@@ -1,21 +1,44 @@
/// The protocol for schema cache.
///
/// This protocol must not contain values that are valid for a single connection
/// only, because several connections can share the same schema cache.
///
/// Statements can't be cached here, for example.
protocol DatabaseSchemaCache {
mutating func clear()
func primaryKey(_ tableName: String) -> PrimaryKey??
mutating func set(primaryKey: PrimaryKey?, for tableName: String)
func indexes(on tableName: String) -> [Database.IndexInfo]?
mutating func set(indexes: [Database.IndexInfo], forTableName tableName: String)
}
/// A thread-unsafe database schema cache
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
private var primaryKeys: [String: PrimaryKey?] = [:]
private var indexes: [String: [Database.IndexInfo]] = [:]
func clear() {
primaryKeys = [:]
indexes = [:]
}
func primaryKey(_ tableName: String) -> PrimaryKey?? {
guard let pk = primaryKeys[tableName] else {
return nil
}
return pk
return primaryKeys[tableName]
}
func set(primaryKey: PrimaryKey?, for tableName: String) {
primaryKeys[tableName] = primaryKey
}
func indexes(on tableName: String) -> [Database.IndexInfo]? {
return indexes[tableName]
}
func set(indexes: [Database.IndexInfo], forTableName tableName: String) {
self.indexes[tableName] = indexes
}
}
/// A thread-safe database schema cache
@@ -33,4 +56,12 @@ final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
func set(primaryKey: PrimaryKey?, for tableName: String) {
cache.write { $0.set(primaryKey: primaryKey, for: tableName) }
}
func indexes(on tableName: String) -> [Database.IndexInfo]? {
return cache.read { $0.indexes(on: tableName) }
}
func set(indexes: [Database.IndexInfo], forTableName tableName: String) {
cache.write { $0.set(indexes: indexes, forTableName: tableName) }
}
}
+2 -9
View File
@@ -86,15 +86,8 @@ extension Sequence where Iterator.Element: Equatable {
}
extension Sequence {
/// Return true if one element matches the predicate
func any(_ predicate: (Iterator.Element) -> Bool) -> Bool {
for element in self where predicate(element) { return true }
return false
}
func all(_ predicate: (Iterator.Element) -> Bool) -> Bool {
for element in self where !predicate(element) { return false }
return true
func all(predicate: @noescape (Self.Iterator.Element) throws -> Bool) rethrows -> Bool {
return try !contains { try !predicate($0) }
}
}
+2 -2
View File
@@ -548,14 +548,14 @@ private class FetchedChangesController<Record: RowConvertible, T> {
tableViewChanges = changes
} else {
// Look for a row difference
guard fetchedItems.count != strongObserver.items.count || zip(fetchedItems, strongObserver.items).any({ (fetchedItem, item) in fetchedItem.row != item.row }) else {
guard fetchedItems.count != strongObserver.items.count || zip(fetchedItems, strongObserver.items).contains({ (fetchedItem, item) in fetchedItem.row != item.row }) else {
return
}
tableViewChanges = nil
}
#else
// Look for a row difference
guard fetchedItems.count != strongObserver.items.count || zip(fetchedItems, strongObserver.items).any({ (fetchedItem, item) in fetchedItem.row != item.row }) else {
guard fetchedItems.count != strongObserver.items.count || zip(fetchedItems, strongObserver.items).contains({ (fetchedItem, item) in fetchedItem.row != item.row }) else {
return
}
#endif
+187 -29
View File
@@ -1,3 +1,15 @@
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#endif
#endif
/// Types that adopt TableMapping declare a particular relationship with
/// a database table.
///
@@ -15,7 +27,7 @@ public protocol TableMapping {
extension RowConvertible where Self: TableMapping {
// MARK: - Single-Column Primary Key
// MARK: - Fetching by Single-Column Primary Key
/// Returns a sequence of records, given their primary keys.
///
@@ -28,7 +40,7 @@ extension RowConvertible where Self: TableMapping {
/// - keys: A sequence of primary keys.
/// - returns: A sequence of records.
public static func fetch<Sequence: Swift.Sequence where Sequence.Iterator.Element: DatabaseValueConvertible>(_ db: Database, keys: Sequence) -> DatabaseSequence<Self> {
guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else {
guard let statement = try! makeFetchByPrimaryKeyStatement(db, keys: keys) else {
return DatabaseSequence.makeEmptySequence(inDatabase: db)
}
return fetch(statement)
@@ -45,7 +57,7 @@ extension RowConvertible where Self: TableMapping {
/// - keys: A sequence of primary keys.
/// - returns: An array of records.
public static func fetchAll<Sequence: Swift.Sequence where Sequence.Iterator.Element: DatabaseValueConvertible>(_ db: Database, keys: Sequence) -> [Self] {
guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else {
guard let statement = try! makeFetchByPrimaryKeyStatement(db, keys: keys) else {
return []
}
return fetchAll(statement)
@@ -63,45 +75,118 @@ extension RowConvertible where Self: TableMapping {
guard let key = key else {
return nil
}
return fetchOne(fetchByPrimaryKeyStatement(db, values: [key])!)
return try! fetchOne(makeFetchByPrimaryKeyStatement(db, keys: [key])!)
}
// Returns "SELECT * FROM table WHERE id IN (?,?,?)"
//
// Returns nil if values is empty.
private static func fetchByPrimaryKeyStatement<Sequence: Swift.Sequence where Sequence.Iterator.Element: DatabaseValueConvertible>(_ db: Database, values: Sequence) -> SelectStatement? {
private static func makeFetchByPrimaryKeyStatement<Sequence: Swift.Sequence where Sequence.Iterator.Element: DatabaseValueConvertible>(_ db: Database, keys: Sequence) throws -> SelectStatement? {
// Fail early if database table does not exist.
let databaseTableName = self.databaseTableName()
let primaryKey = try! db.primaryKey(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!
let values = Array(values)
switch values.count {
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 * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
let statement = try! db.makeSelectStatement(sql)
statement.arguments = StatementArguments(values)
let statement = try db.makeSelectStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
case let count:
// SELECT * FROM table WHERE id IN (?,?,?)
let valuesSQL = databaseQuestionMarks(count: count)
let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(valuesSQL))"
let statement = try! db.makeSelectStatement(sql)
statement.arguments = StatementArguments(values)
let keysSQL = databaseQuestionMarks(count: count)
let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))"
let statement = try db.makeSelectStatement(sql)
statement.arguments = StatementArguments(keys)
return statement
}
}
}
extension TableMapping {
// MARK: - Deleting by Single-Column Primary Key
// MARK: - Other Keys
/// Delete records identified by their primary keys.
///
/// 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
public static func deleteAll<Sequence: Swift.Sequence where Sequence.Iterator.Element: DatabaseValueConvertible>(_ db: Database, keys: Sequence) throws -> Int {
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.
///
/// try Person.deleteOne(db, key: 123)
///
/// - parameters:
/// - db: A database connection.
/// - key: A primary key value.
/// - returns: Whether a database row was deleted.
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 where Sequence.Iterator.Element: DatabaseValueConvertible>(_ db: Database, keys: Sequence) throws -> UpdateStatement? {
// 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!
let keys = Array(keys)
switch keys.count {
case 0:
// Avoid performing useless DELETE
return nil
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
}
}
}
extension RowConvertible where Self: TableMapping {
// MARK: - Fetching by Key
/// Returns a sequence of records, given an array of key dictionaries.
///
@@ -114,7 +199,7 @@ extension RowConvertible where Self: TableMapping {
/// - keys: An array of key dictionaries.
/// - returns: A sequence of records.
public static func fetch(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> DatabaseSequence<Self> {
guard let statement = fetchByKeyStatement(db, keys: keys) else {
guard let statement = try! makeFetchByKeyStatement(db, keys: keys) else {
return DatabaseSequence.makeEmptySequence(inDatabase: db)
}
return fetch(statement)
@@ -131,7 +216,7 @@ extension RowConvertible where Self: TableMapping {
/// - keys: An array of key dictionaries.
/// - returns: An array of records.
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> [Self] {
guard let statement = fetchByKeyStatement(db, keys: keys) else {
guard let statement = try! makeFetchByKeyStatement(db, keys: keys) else {
return []
}
return fetchAll(statement)
@@ -146,35 +231,38 @@ extension RowConvertible where Self: TableMapping {
/// - key: A dictionary of values.
/// - returns: An optional record.
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) -> Self? {
return fetchOne(fetchByKeyStatement(db, keys: [key])!)
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.
private static func fetchByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> SelectStatement? {
// NOTE: this method *was* slow to compile
// https://medium.com/swift-programming/speeding-up-slow-swift-build-times-922feeba5780#.s77wmh4h0
// 586.8ms /Users/groue/Documents/git/groue/GRDB.swift/GRDB/Record/TableMapping.swift:163:25 @warn_unused_result private static func fetchByKeyStatement(db: Database, keys: [[String : DatabaseValueConvertible?]]) -> SelectStatement?
// Fixes are marked with "## Slow Compile Fix (Swift 2.2.x):"
//
// 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 = dictionary.keys
guard try db.columns(columns, uniquelyIdentifyRowsIn: databaseTableName) else {
if fatalErrorOnMissingUniqueIndex {
fatalError("table \(databaseTableName) has no unique index on column(s) \(columns.joined(separator: ", "))")
} else {
throw DatabaseError(code: SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.joined(separator: ", "))")
}
}
arguments.append(contentsOf: dictionary.values)
// ## Slow Compile Fix (Swift 2.2.x):
// TODO: Check if Swift 3 compiler fixes this line's slow compilation time:
//whereClauses.append("(" + dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" }.joinWithSeparator(" AND ") + ")") // Original, Slow To Compile
whereClauses.append("(" + (dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
whereClauses.append("(" + (columns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
}
let databaseTableName = self.databaseTableName()
let whereClause = whereClauses.joined(separator: " OR ")
let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
let statement = try! db.makeSelectStatement(sql)
@@ -182,3 +270,73 @@ extension RowConvertible where Self: TableMapping {
return statement
}
}
extension TableMapping {
// MARK: - Deleting by Key
/// Delete records, given an array of key dictionaries.
///
/// try Person.deleteAll(db, keys: [["name": "Arthur"], ["name": "Barbara"]])
///
/// - parameters:
/// - db: A database connection.
/// - keys: An array of key dictionaries.
/// - returns: The number of deleted rows
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 key dictionary.
///
/// Person.deleteOne(db, key: ["name": Arthur"])
///
/// - parameters:
/// - db: A database connection.
/// - key: A dictionary of values.
/// - returns: Whether a database row was deleted.
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 = ?) ...
//
// 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 = dictionary.keys
guard try db.columns(columns, uniquelyIdentifyRowsIn: databaseTableName) else {
if fatalErrorOnMissingUniqueIndex {
fatalError("table \(databaseTableName) has no unique index on column(s) \(columns.joined(separator: ", "))")
} else {
throw DatabaseError(code: SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.joined(separator: ", "))")
}
}
arguments.append(contentsOf: dictionary.values)
whereClauses.append("(" + (columns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
}
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
}
}
+53 -19
View File
@@ -25,7 +25,7 @@ You should give it a try.
---
The Swift3 branch has no version. It is currently synced with v0.73.0 of the Swift 2.2 [main branch](https://github.com/groue/GRDB.swift).
The Swift3 branch has no version. It is currently synced with v0.74.0 of the Swift 2.2 [main branch](https://github.com/groue/GRDB.swift).
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
@@ -280,7 +280,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Structs/Configuration.html) for more details.
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Structs/Configuration.html) for more details.
## Database Pools
@@ -360,7 +360,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Structs/Configuration.html) for more details.
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -1442,10 +1442,10 @@ for person in Person.fetch(db, sql, adapter: adapter) {
For more information about row adapters, see the documentation of:
- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters
- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Structs/ColumnMapping.html): a row adapter that renames row columns
- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row
- [VariantRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Structs/VariantRowAdapter.html): the row adapter that groups several adapters together to define named variants
- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters
- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Structs/ColumnMapping.html): a row adapter that renames row columns
- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row
- [VariantRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Structs/VariantRowAdapter.html): the row adapter that groups several adapters together to define named variants
## Raw SQLite Pointers
@@ -1710,23 +1710,35 @@ Adopting types can be fetched without SQL, using the [query interface](#the-quer
let paris = PointOfInterest.filter(nameColumn == "Paris").fetchOne(db)
```
You can also fetch records according to their primary key:
You can also fetch and delete records according to their primary key:
```swift
// SELECT * FROM persons WHERE id = 1
// Fetch:
Person.fetchOne(db, key: 1) // Person?
// SELECT * FROM persons WHERE id IN (1, 2, 3)
Person.fetchAll(db, keys: [1, 2, 3]) // [Person]
// SELECT * FROM persons WHERE isoCode = 'FR'
Country.fetchOne(db, key: "FR") // Country?
// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
Country.fetchAll(db, keys: ["FR", "US"]) // [Country]
// SELECT * FROM citizenships WHERE personID = 1 AND countryISOCode = 'FR'
// Use a dictionary for composite primary keys:
Citizenship.fetchOne(db, key: ["personID": 1, "countryISOCode": "FR"]) // Citizenship?
// Delete records:
try Person.deleteOne(db, key: 1)
try Country.deleteAll(db, keys: ["FR", "US"])
```
When given dictionaries, `fetchOne`, `deleteOne`, `fetchAll` and `deleteAll` accept any set of columns that uniquely identify rows. These are the primary key columns, or any columns involved in a unique index:
```swift
// CREATE TABLE persons (
// id INTEGER PRIMARY KEY, -- can fetch and delete by id
// email TEXT UNIQUE, -- can fetch and delete by email
// name TEXT -- nope
// )
Person.fetchOne(db, key: ["id": 1]) // Person?
Person.fetchOne(db, key: ["email": "arthur@example.com"]) // Person?
Person.fetchOne(db, key: ["name": "Arthur"]) // fatal error: table persons has no unique index on column name.
```
@@ -2957,9 +2969,9 @@ When you create a controller, you can give it a serial dispatch queue. The contr
**GRDB can encrypt your database with [SQLCipher](http://sqlcipher.net).**
In the [installation](#installation) phase, use the GRDBCipher framework instead of GRDB. CocoaPods is not supported.
In the [installation](#installation) phase, don't use the GRDB framework, and use the GRDBCipher framework instead. CocoaPods is not supported. The manual installation needs you to download the embedded copy of SQLCipher with the `git submodule update --init` command.
Set the `passphrase` property of the database configuration before opening your [database connection](#database-connections):
**You create and open an encrypted database** by providing a passphrase to your [database connection](#database-connections):
```swift
import GRDBCipher
@@ -2969,12 +2981,34 @@ configuration.passphrase = "secret"
let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
```
You can change the passphrase of an encrypted database:
**You can change the passphrase** of an already encrypted database:
```swift
try dbQueue.changePassphrase("newSecret")
```
Providing a passphrase won't encrypt a clear-text database that already exists, though. SQLCipher can't do that, and you will get an error instead: `SQLite error 26: file is encrypted or is not a database`.
**To encrypt an existing clear-text database**, you have to create a new and empty encrypted database, and copy the content of the clear-text database in it. The technique to do that is [documented](https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868/1) by SQLCipher. With GRDB, it gives:
```swift
// The clear-text database
let clearDBQueue = try DatabaseQueue(path: "/path/to/clear.db")
// The encrypted database, at some distinct location:
var configuration = Configuration()
configuration.passphrase = "secret"
let encryptedDBQueue = try DatabaseQueue(path: "/path/to/encrypted.db", configuration: config)
try clearDBQueue.inDatabase { db in
try db.execute("ATTACH DATABASE ? AS encrypted KEY ?", arguments: [encryptedDBQueue.path, "secret"])
try db.execute("SELECT sqlcipher_export('encrypted')")
try db.execute("DETACH DATABASE encrypted")
}
// Now the copy is done, and the clear-text database can be deleted.
```
## Backup
@@ -3306,7 +3340,7 @@ let count2 = dbQueue.inDatabase { db in
SQLite concurrency is a wiiide topic.
First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.73.0/Protocols/DatabaseWriter.html) protocols, so that you can write code that targets both classes.
First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.74.0/Protocols/DatabaseWriter.html) protocols, so that you can write code that targets both classes.
If the built-in queues and pools do not fit your needs, or if you can not guarantee that a single queue or pool is accessing your database file, you may have a look at:
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>0.73.0</string>
<string>0.74.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+6 -1
View File
@@ -19,6 +19,11 @@
- [ ] In-memory DatabasePool (https://www.sqlite.org/inmemorydb.html). Unfortunately, a shared cache is not enough. Since SQLite does not provide WAL mode for in-memory databases, it's easy to get "database is locked" errors. A WAL database on a RAM disk looks out of reach. Possible solution: have one writer that is exclusive with the readers.
Not sure
- [ ] Support for NSColor/UIColor. Beware UIColor components can go beyond [0, 1.0] in iOS10.
Require changes in the Swift language:
- [ ] Specific and optimized Optional<StatementColumnConvertible>.fetch... methods when http://openradar.appspot.com/22852669 is fixed.
@@ -39,4 +44,4 @@ Reading list:
- List of documentation keywords: https://swift.org/documentation/api-design-guidelines.html#special-instructions
- https://www.zetetic.net/sqlcipher/
- https://sqlite.org/sharedcache.html
- Amazing tip from Xcode labs: add a EXCLUDED_SOURCE_FILE_NAMES build setting to conditionally exclude sources for different configuration: https://twitter.com/zats/status/743862987602026496
- Amazing tip from Xcode labs: add a EXCLUDED_SOURCE_FILE_NAMES build setting to conditionally exclude sources for different configuration: https://twitter.com/zats/status/74386298602026496
@@ -14,31 +14,49 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, email TEXT UNIQUE, foo INT, bar DOUBLE)")
try db.execute("CREATE INDEX foobar ON items(foo, bar)")
}
dbPool.write { db in
// Assert that the writer cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
}
dbPool.read { db in
// Assert that a reader cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
}
try dbPool.read { db in
// Warm cache in a reader
let primaryKey = try db.primaryKey("items")!
XCTAssertEqual(primaryKey.rowIDColumn, "id")
let indexes = db.indexes(on: "items")
XCTAssertEqual(indexes.count, 2)
for index in indexes {
switch index.name {
case "foobar":
XCTAssertEqual(index.columns, ["foo", "bar"])
XCTAssertFalse(index.isUnique)
default:
XCTAssertEqual(index.columns, ["email"])
XCTAssertTrue(index.isUnique)
}
}
// Assert that reader cache is warmed
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil)
}
dbPool.write { db in
// Assert that writer cache is warmed
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil)
}
try dbPool.write { db in
@@ -47,11 +65,13 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
// Assert that the writer cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
}
dbPool.read { db in
// Assert that a reader cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
}
try dbPool.read { db in
+104
View File
@@ -0,0 +1,104 @@
import XCTest
#if USING_SQLCIPHER
@testable import GRDBCipher
#elseif USING_CUSTOMSQLITE
@testable import GRDBCustomSQLite
#else
@testable import GRDB
#endif
private struct Person : RowConvertible, TableMapping {
static func databaseTableName() -> String {
return "persons"
}
init(row: Row) {
}
}
private struct Citizenship : RowConvertible, TableMapping {
static func databaseTableName() -> String {
return "citizenships"
}
init(row: Row) {
}
}
class UniqueIndexTests: GRDBTestCase {
func testColumnsThatUniquelyIdentityRows() {
assertNoError { db in
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
try XCTAssertTrue(db.columns(["id"], uniquelyIdentifyRowsIn: "persons"))
try XCTAssertTrue(db.columns(["email"], uniquelyIdentifyRowsIn: "persons"))
try XCTAssertFalse(db.columns([], uniquelyIdentifyRowsIn: "persons"))
try XCTAssertFalse(db.columns(["name"], uniquelyIdentifyRowsIn: "persons"))
try XCTAssertFalse(db.columns(["id", "email"], uniquelyIdentifyRowsIn: "persons"))
try db.execute("CREATE TABLE citizenships (personId INTEGER NOT NULL, countryIsoCode TEXT NOT NULL, PRIMARY KEY (personId, countryIsoCode))")
try XCTAssertTrue(db.columns(["personId", "countryIsoCode"], uniquelyIdentifyRowsIn: "citizenships"))
try XCTAssertTrue(db.columns(["countryIsoCode", "personId"], uniquelyIdentifyRowsIn: "citizenships"))
try XCTAssertFalse(db.columns([], uniquelyIdentifyRowsIn: "persons"))
try XCTAssertFalse(db.columns(["personId"], uniquelyIdentifyRowsIn: "persons"))
try XCTAssertFalse(db.columns(["countryIsoCode"], uniquelyIdentifyRowsIn: "persons"))
}
}
}
func testFetchOneRequiresUniqueIndex() {
assertNoError { db in
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
_ = try Person.makeFetchByKeyStatement(db, keys: [["id": nil]])
_ = try Person.makeFetchByKeyStatement(db, keys: [["email": nil]])
do {
_ = try Person.makeFetchByKeyStatement(db, keys: [["id": nil, "email": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 21) // SQLITE_MISUSE
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) id, email")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) id, email")
}
do {
_ = try Person.makeFetchByKeyStatement(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 21) // SQLITE_MISUSE
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) name")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) name")
}
}
}
}
func testDeleteOneRequiresUniqueIndex() {
assertNoError { db in
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
_ = try Person.makeDeleteByKeyStatement(db, keys: [["id": nil]])
_ = try Person.makeDeleteByKeyStatement(db, keys: [["email": nil]])
do {
_ = try Person.makeDeleteByKeyStatement(db, keys: [["id": nil, "email": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 21) // SQLITE_MISUSE
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) id, email")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) id, email")
}
do {
_ = try Person.makeDeleteByKeyStatement(db, keys: [["name": nil]], fatalErrorOnMissingUniqueIndex: false)
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 21) // SQLITE_MISUSE
XCTAssertEqual(error.message!, "table persons has no unique index on column(s) name")
XCTAssertEqual(error.description, "SQLite error 21: table persons has no unique index on column(s) name")
}
}
}
}
}
@@ -374,6 +374,15 @@ class EncryptionTests: GRDBTestCase {
}
dbConfiguration.passphrase = "secret"
do {
try makeDatabaseQueue("plaintext.sqlite")
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 26) // SQLITE_NOTADB
XCTAssertEqual(error.message!, "file is encrypted or is not a database")
XCTAssertTrue(error.sql == nil)
XCTAssertEqual(error.description, "SQLite error 26: file is encrypted or is not a database")
}
let encryptedDBQueue = try makeDatabaseQueue(filename: "encrypted.sqlite")
try plainTextDBQueue.inDatabase { db in
+124
View File
@@ -0,0 +1,124 @@
import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct Person : TableMapping {
static func databaseTableName() -> String {
return "persons"
}
}
private struct Citizenship : TableMapping {
static func databaseTableName() -> String {
return "citizenships"
}
}
class DeleteByKeyTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
try db.execute("CREATE TABLE citizenships (personId INTEGER NOT NULL, countryIsoCode TEXT NOT NULL, PRIMARY KEY (personId, countryIsoCode))")
}
}
func testSingleColumnPrimaryKey() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Person.deleteOne(db, key: 1)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1")
XCTAssertFalse(deleted)
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
deleted = try Person.deleteOne(db, key: 1)
XCTAssertTrue(deleted)
XCTAssertEqual(Person.fetchCount(db), 0)
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"])
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"])
let deletedCount = try Person.deleteAll(db, keys: [2, 3, 4])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (2,3,4)")
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(Person.fetchCount(db), 1)
}
}
}
func testMultipleColumnPrimaryKey() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Citizenship.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"citizenships\" WHERE (\"personId\" = 1 AND \"countryIsoCode\" = 'FR')")
XCTAssertFalse(deleted)
try db.execute("INSERT INTO citizenships (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "FR"])
deleted = try Citizenship.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"])
XCTAssertTrue(deleted)
XCTAssertEqual(Citizenship.fetchCount(db), 0)
try db.execute("INSERT INTO citizenships (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "FR"])
try db.execute("INSERT INTO citizenships (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "US"])
try db.execute("INSERT INTO citizenships (personId, countryIsoCode) VALUES (?, ?)", arguments: [2, "US"])
let deletedCount = try Citizenship.deleteAll(db, keys: [["personId": 1, "countryIsoCode": "FR"], ["personId": 1, "countryIsoCode": "US"], ["personId": 1, "countryIsoCode": "DE"]])
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(Citizenship.fetchCount(db), 1)
}
}
}
func testUniqueIndex() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Person.deleteOne(db, key: ["email": "arthur@example.com"])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (\"email\" = 'arthur@example.com')")
XCTAssertFalse(deleted)
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
deleted = try Person.deleteOne(db, key: ["email": "arthur@example.com"])
XCTAssertTrue(deleted)
XCTAssertEqual(Person.fetchCount(db), 0)
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"])
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"])
let deletedCount = try Person.deleteAll(db, keys: [["email": "arthur@example.com"], ["email": "barbara@example.com"], ["email": "david@example.com"]])
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(Person.fetchCount(db), 1)
}
}
}
func testImplicitUniqueIndexOnSingleColumnPrimaryKey() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Person.deleteOne(db, key: ["id": 1])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (\"id\" = 1)")
XCTAssertFalse(deleted)
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
deleted = try Person.deleteOne(db, key: ["id": 1])
XCTAssertTrue(deleted)
XCTAssertEqual(Person.fetchCount(db), 0)
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"])
try db.execute("INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"])
let deletedCount = try Person.deleteAll(db, keys: [["id": 2], ["id": 3], ["id": 4]])
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(Person.fetchCount(db), 1)
}
}
}
}
+11 -7
View File
@@ -10,16 +10,19 @@ import XCTest
// Item has no primary key.
private class Item : Record {
var name: String?
var email: String?
init(name: String? = nil) {
init(name: String? = nil, email: String? = nil) {
self.name = name
self.email = email
super.init()
}
static func setup(inDatabase db: Database) throws {
try db.execute(
"CREATE TABLE items (" +
"name NOT NULL" +
"name TEXT," +
"email TEXT UNIQUE" +
")")
}
@@ -31,11 +34,12 @@ private class Item : Record {
required init(row: Row) {
name = row.value(named: "name")
email = row.value(named: "email")
super.init(row: row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["name": name]
return ["name": name, "email": email]
}
}
@@ -84,15 +88,15 @@ class PrimaryKeyNoneTests: GRDBTestCase {
// MARK: - Select
func testSelectWithKey() {
func testFetchOneWithKey() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Item(name: "Table")
let record = Item(email: "item@example.com")
try record.insert(db)
let fetchedRecord = Item.fetchOne(db, key: ["name": record.name])!
XCTAssertTrue(fetchedRecord.name == record.name)
let fetchedRecord = Item.fetchOne(db, key: ["email": record.email])!
XCTAssertTrue(fetchedRecord.email == record.email)
}
}
}