diff --git a/CHANGELOG.md b/CHANGELOG.md index 44b390710..df1080eed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,13 +1,43 @@ Release Notes ============= -## Next Version +## 0.77.0 + +Released July 28, 2016 **New** -- `Database.indexes(on:)` returns the indexes defined on a database table +- `Database.indexes(on:)` returns the indexes defined on a database table. + - `Database.table(_:hasUniqueKey:)` returns true if a sequence of columns uniquely identifies a row, that is to say if the columns are the primary key, or if there is a unique index on them. +- MutablePersistable types, including Record subclasses, support partial updates: + + ```swift + try person.update(db) // Full update + try person.update(db, columns: ["name"]) // Only updates the name column + ``` + +**Breaking Changes** + +- MutablePersistable `update` and `performUpdate` methods have changed their signatures. You only have to care about this change if you customize the protocol `update` method. + + ```diff + protocol MutablePersistable : TableMapping { + -func update(db: Database) throws + +func update(db: Database, columns: Set) throws + } + + extension MutablePersistable { + func update(db: Database) throws + +func update(db: Database, columns: Set) throws + +func update(db: Database, columns: S) throws + +func update(db: Database, columns: S) throws + -func performUpdate(db: Database) throws + +func performUpdate(db: Database, columns: Set) throws + } + ``` + ## 0.76.0 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 2f1c18387..09e21b62e 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '0.76.0' + s.version = '0.77.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' diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 79ab6bfea..e2e6bfe45 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -438,6 +438,14 @@ 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 */; }; + 567A80531D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A80591D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.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 */; }; @@ -608,14 +616,6 @@ 56A8C24C1D1918F10096E9D4 /* UUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* UUIDTests.swift */; }; 56A8C24D1D1918F30096E9D4 /* NSUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C2361D1914790096E9D4 /* NSUUIDTests.swift */; }; 56A8C24E1D1918F30096E9D4 /* UUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* UUIDTests.swift */; }; - 56AF74621D41FB89005E9FF3 /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */; }; - 56AF74631D41FB89005E9FF3 /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */; }; - 56AF74641D41FB89005E9FF3 /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */; }; - 56AF74651D41FB89005E9FF3 /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */; }; - 56AF74661D41FB89005E9FF3 /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */; }; - 56AF74671D41FB89005E9FF3 /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */; }; - 56AF74681D41FB89005E9FF3 /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */; }; - 56AF74691D41FB89005E9FF3 /* TableIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */; }; 56AF746B1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; 56AF746C1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; 56AF746D1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; @@ -1415,6 +1415,7 @@ 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueBackupTests.swift; sourceTree = ""; }; 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 567404871CEF84C8003ED5CC /* RowAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapter.swift; sourceTree = ""; }; + 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 5683C2681B4D445E00296494 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.4.sdk/usr/lib/libsqlite3.dylib; sourceTree = DEVELOPER_DIR; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 568BE5191CB035A900270F93 /* sqlite3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sqlite3.h; path = SQLCipher/src/sqlite3.h; sourceTree = ""; }; @@ -1479,7 +1480,6 @@ 56A8C21E1D1914110096E9D4 /* UUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUIDTests.swift; sourceTree = ""; }; 56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = ""; }; 56A8C2361D1914790096E9D4 /* NSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSUUIDTests.swift; sourceTree = ""; }; - 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableIndexTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56AFCA7F1CB1AA9900F48B96 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -1978,9 +1978,9 @@ isa = PBXGroup; children = ( 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, + 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */, 56A238141B9C74A90082EB20 /* InMemoryDatabaseTests.swift */, 567156151CB142AA007DC145 /* ReadOnlyDatabaseTests.swift */, - 56AF74611D41FB89005E9FF3 /* TableIndexTests.swift */, ); path = Database; sourceTree = ""; @@ -3185,10 +3185,10 @@ 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, 560FC58A1CB00B880014AA8E /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* SavepointTests.swift in Sources */, + 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 560FC58B1CB00B880014AA8E /* DatabaseValueTests.swift in Sources */, 565049061CE32543000A97D8 /* FetchedRecordsControllerTests.swift in Sources */, 567156171CB142AA007DC145 /* ReadOnlyDatabaseTests.swift in Sources */, - 56AF74631D41FB89005E9FF3 /* TableIndexTests.swift in Sources */, 560FC58D1CB00B880014AA8E /* Row+FoundationTests.swift in Sources */, 56A4CDB11D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 567156141CB141D0007DC145 /* InMemoryDatabaseTests.swift in Sources */, @@ -3300,13 +3300,13 @@ 567156451CB16729007DC145 /* DatabasePoolConcurrencyTests.swift in Sources */, 5690C3391D23E7D200E59934 /* DateTests.swift in Sources */, 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */, + 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 567156471CB16729007DC145 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 565049071CE32543000A97D8 /* FetchedRecordsControllerTests.swift in Sources */, 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, 5671564A1CB16729007DC145 /* ReadOnlyDatabaseTests.swift in Sources */, 5671564B1CB16729007DC145 /* Row+FoundationTests.swift in Sources */, 56A8C2431D1918EE0096E9D4 /* NSUUIDTests.swift in Sources */, - 56AF74641D41FB89005E9FF3 /* TableIndexTests.swift in Sources */, 5671564C1CB16729007DC145 /* InMemoryDatabaseTests.swift in Sources */, 56A4CDB21D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 5671564D1CB16729007DC145 /* PrimaryKeyRowIDTests.swift in Sources */, @@ -3460,7 +3460,6 @@ 56AFCA571CB1AA9900F48B96 /* TransactionObserverTests.swift in Sources */, 56AF74701D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 5690C33C1D23E7D200E59934 /* DateTests.swift in Sources */, - 56AF74671D41FB89005E9FF3 /* TableIndexTests.swift in Sources */, 56AFCA581CB1AA9900F48B96 /* Row+FoundationTests.swift in Sources */, 569178411CED8E0C00E179EA /* FetchedRecordsControllerTests.swift in Sources */, 56AFCA5A1CB1AA9900F48B96 /* RecordSubClassTests.swift in Sources */, @@ -3498,6 +3497,7 @@ 56AFCA721CB1AA9900F48B96 /* FunctionTests.swift in Sources */, 56AFCA731CB1AA9900F48B96 /* InMemoryDatabaseTests.swift in Sources */, 56AFCA741CB1AA9900F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, + 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 56AFCA751CB1AA9900F48B96 /* CGFloatTests.swift in Sources */, 56AFCA761CB1AA9900F48B96 /* StatementInformationTests.swift in Sources */, 5691784A1CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, @@ -3563,7 +3563,6 @@ 5657AB441D108BA9006283EF /* NSDataTests.swift in Sources */, 56AF74711D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56AFCAAE1CB1ABC800F48B96 /* RawRepresentableTests.swift in Sources */, - 56AF74681D41FB89005E9FF3 /* TableIndexTests.swift in Sources */, 56AFCAAF1CB1ABC800F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCAB01CB1ABC800F48B96 /* TransactionObserverTests.swift in Sources */, 56AFCAB11CB1ABC800F48B96 /* Row+FoundationTests.swift in Sources */, @@ -3601,6 +3600,7 @@ 56AFCACC1CB1ABC800F48B96 /* InMemoryDatabaseTests.swift in Sources */, 56AFCACD1CB1ABC800F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, 56AFCACE1CB1ABC800F48B96 /* CGFloatTests.swift in Sources */, + 567A80591D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 56AFCACF1CB1ABC800F48B96 /* StatementInformationTests.swift in Sources */, 56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */, 565EFAF41D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, @@ -3722,13 +3722,13 @@ 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */, 5690C33B1D23E7D200E59934 /* DateTests.swift in Sources */, 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */, + 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 569178391CED8E0A00E179EA /* FetchedRecordsControllerTests.swift in Sources */, 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, 56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */, 567156181CB142AA007DC145 /* ReadOnlyDatabaseTests.swift in Sources */, 56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */, 56A8C2471D1918F00096E9D4 /* NSUUIDTests.swift in Sources */, - 56AF74661D41FB89005E9FF3 /* TableIndexTests.swift in Sources */, 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */, 56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, @@ -3792,6 +3792,7 @@ 56A238631B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift in Sources */, 569531341C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */, 56A238591B9C74A90082EB20 /* PrimaryKeySingleTests.swift in Sources */, + 567A80531D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 56EE573D1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift in Sources */, 56A238651B9C74A90082EB20 /* RecordFetchTests.swift in Sources */, 569531371C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */, @@ -3826,7 +3827,6 @@ 56A2383D1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */, 565D5D711BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */, 56C3F7531CF9F12400F6A361 /* SavepointTests.swift in Sources */, - 56AF74621D41FB89005E9FF3 /* TableIndexTests.swift in Sources */, 565049051CE32543000A97D8 /* FetchedRecordsControllerTests.swift in Sources */, 567156161CB142AA007DC145 /* ReadOnlyDatabaseTests.swift in Sources */, 56A238571B9C74A90082EB20 /* PrimaryKeyRowIDTests.swift in Sources */, @@ -4038,6 +4038,7 @@ F3BA81031CFB303D003DC1BA /* FetchedRecordsControlleriOSTests.swift in Sources */, F3BA80B71CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, 5690C33E1D23E7D200E59934 /* DateTests.swift in Sources */, + 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, F3BA81211CFB3063003DC1BA /* PrimaryKeyNoneTests.swift in Sources */, F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, F3BA80FE1CFB3024003DC1BA /* TransactionObserverTests.swift in Sources */, @@ -4045,7 +4046,6 @@ F3BA80BD1CFB2FD1003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */, 56A8C24D1D1918F30096E9D4 /* NSUUIDTests.swift in Sources */, - 56AF74691D41FB89005E9FF3 /* TableIndexTests.swift in Sources */, F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, @@ -4166,6 +4166,7 @@ F3BA811D1CFB305F003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, F3BA80C21CFB2FD2003DC1BA /* DatabasePoolFileAttributesTests.swift in Sources */, + 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, F3BA81301CFB3064003DC1BA /* PrimaryKeyRowIDTests.swift in Sources */, F3BA80AB1CFB2FA6003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */, F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, @@ -4200,7 +4201,6 @@ F3BA80C01CFB2FD2003DC1BA /* DatabasePoolCollationTests.swift in Sources */, F3BA80C31CFB2FD2003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */, - 56AF74651D41FB89005E9FF3 /* TableIndexTests.swift in Sources */, F3BA81321CFB3064003DC1BA /* PrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, F3BA81051CFB3046003DC1BA /* FetchedRecordsControllerTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ab627a97c..d6787c194 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -831,30 +831,20 @@ extension Database { // 1 | firstName | TEXT | 0 | NULL | 0 | // 2 | lastName | TEXT | 0 | NULL | 0 | - if #available(iOS 8.2, OSX 10.10, *) { } else { - // Work around a bug in SQLite where PRAGMA table_info would - // return a result even after the table was deleted. - if !tableExists(tableName) { - throw DatabaseError(message: "no such table: \(tableName)") - } - } - let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") - guard columnInfos.count > 0 else { - throw DatabaseError(message: "no such table: \(tableName)") - } + let columns = try self.columns(in: tableName) let primaryKey: PrimaryKey? - let pkColumnInfos = columnInfos + let pkColumns = columns .filter { $0.primaryKeyIndex > 0 } .sorted { $0.primaryKeyIndex < $1.primaryKeyIndex } - switch pkColumnInfos.count { + switch pkColumns.count { case 0: // No primary key column primaryKey = nil case 1: // Single column - let pkColumnInfo = pkColumnInfos.first! + let pkColumn = pkColumns.first! // https://www.sqlite.org/lang_createtable.html: // @@ -876,20 +866,68 @@ extension Database { // // FIXME: We ignore the exception, and consider all INTEGER primary // keys as aliases for the rowid: - if pkColumnInfo.type.uppercased() == "INTEGER" { - primaryKey = .rowID(pkColumnInfo.name) + if pkColumn.type.uppercased() == "INTEGER" { + primaryKey = .rowID(pkColumn.name) } else { - primaryKey = .regular([pkColumnInfo.name]) + primaryKey = .regular([pkColumn.name]) } default: // Multi-columns primary key - primaryKey = .regular(pkColumnInfos.map { $0.name }) + primaryKey = .regular(pkColumns.map { $0.name }) } schemaCache.set(primaryKey: primaryKey, for: tableName) return primaryKey } + /// The columns in table named `tableName`. + /// + /// - throws: A DatabaseError if table does not exist. + func columns(in tableName: String) throws -> [ColumnInfo] { + if let columns = schemaCache.columns(in: tableName) { + return columns + } + + // https://www.sqlite.org/pragma.html + // + // > PRAGMA database.table_info(table-name); + // > + // > This pragma returns one row for each column in the named table. + // > Columns in the result set include the column name, data type, + // > whether or not the column can be NULL, and the default value for + // > the column. The "pk" column in the result set is zero for columns + // > that are not part of the primary key, and is the index of the + // > column in the primary key for columns that are part of the primary + // > key. + // + // CREATE TABLE persons ( + // id INTEGER PRIMARY KEY, + // firstName TEXT, + // lastName TEXT) + // + // PRAGMA table_info("persons") + // + // 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 | + + if #available(iOS 8.2, OSX 10.10, *) { } else { + // Work around a bug in SQLite where PRAGMA table_info would + // return a result even after the table was deleted. + if !tableExists(tableName) { + throw DatabaseError(message: "no such table: \(tableName)") + } + } + let columns = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") + guard columns.count > 0 else { + throw DatabaseError(message: "no such table: \(tableName)") + } + + schemaCache.set(columns: columns, forTableName: tableName) + return columns + } + /// The indexes on table named `tableName`; returns the empty array if the /// table does not exist. /// @@ -898,19 +936,19 @@ extension Database { /// /// If you want to know if a set of columns uniquely identify a row, prefer /// table(_:hasUniqueKey:) instead. - public func indexes(on tableName: String) -> [TableIndex] { + public 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 -> TableIndex in + 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 TableIndex(name: indexName, columns: columns, unique: unique) + return IndexInfo(name: indexName, columns: columns, unique: unique) } schemaCache.set(indexes: indexes, forTableName: tableName) @@ -934,6 +972,10 @@ extension Database { return false } +} + +/// A column of a table +struct ColumnInfo : RowConvertible { // CREATE TABLE persons ( // id INTEGER PRIMARY KEY, // firstName TEXT, @@ -945,27 +987,25 @@ extension Database { // 0 | id | INTEGER | 0 | NULL | 1 | // 1 | firstName | TEXT | 0 | NULL | 0 | // 2 | lastName | TEXT | 0 | NULL | 0 | - private struct ColumnInfo : RowConvertible { - let name: String - let type: String - let notNull: Bool - let defaultDatabaseValue: DatabaseValue - let primaryKeyIndex: Int - - init(row: Row) { - name = row.value(named: "name") - type = row.value(named: "type") - notNull = row.value(named: "notnull") - defaultDatabaseValue = row.databaseValue(named: "dflt_value")! - primaryKeyIndex = row.value(named: "pk") - } + let name: String + let type: String + let notNull: Bool + let defaultDatabaseValue: DatabaseValue + let primaryKeyIndex: Int + + init(row: Row) { + name = row.value(named: "name") + type = row.value(named: "type") + notNull = row.value(named: "notnull") + defaultDatabaseValue = row.databaseValue(named: "dflt_value")! + primaryKeyIndex = row.value(named: "pk") } } /// An index on a database table. /// /// See `Database.indexes(on:)` -public struct TableIndex { +public struct IndexInfo { /// The name of the index public let name: String diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 88b4b8292..152ec3df8 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -9,18 +9,23 @@ protocol DatabaseSchemaCache { func primaryKey(_ tableName: String) -> PrimaryKey?? mutating func set(primaryKey: PrimaryKey?, for tableName: String) - - func indexes(on tableName: String) -> [TableIndex]? - mutating func set(indexes: [TableIndex], forTableName tableName: String) + + func columns(in tableName: String) -> [ColumnInfo]? + mutating func set(columns: [ColumnInfo], forTableName tableName: String) + + func indexes(on tableName: String) -> [IndexInfo]? + mutating func set(indexes: [IndexInfo], forTableName tableName: String) } /// A thread-unsafe database schema cache final class SimpleDatabaseSchemaCache: DatabaseSchemaCache { private var primaryKeys: [String: PrimaryKey?] = [:] - private var indexes: [String: [TableIndex]] = [:] + private var columns: [String: [ColumnInfo]] = [:] + private var indexes: [String: [IndexInfo]] = [:] func clear() { primaryKeys = [:] + columns = [:] indexes = [:] } @@ -32,11 +37,19 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache { primaryKeys[tableName] = primaryKey } - func indexes(on tableName: String) -> [TableIndex]? { + func columns(in tableName: String) -> [ColumnInfo]? { + return columns[tableName] + } + + func set(columns: [ColumnInfo], forTableName tableName: String) { + self.columns[tableName] = columns + } + + func indexes(on tableName: String) -> [IndexInfo]? { return indexes[tableName] } - func set(indexes: [TableIndex], forTableName tableName: String) { + func set(indexes: [IndexInfo], forTableName tableName: String) { self.indexes[tableName] = indexes } } @@ -57,11 +70,19 @@ final class SharedDatabaseSchemaCache: DatabaseSchemaCache { cache.write { $0.set(primaryKey: primaryKey, for: tableName) } } - func indexes(on tableName: String) -> [TableIndex]? { + func columns(in tableName: String) -> [ColumnInfo]? { + return cache.read { $0.columns(in: tableName) } + } + + func set(columns: [ColumnInfo], forTableName tableName: String) { + cache.write { $0.set(columns: columns, forTableName: tableName) } + } + + func indexes(on tableName: String) -> [IndexInfo]? { return cache.read { $0.indexes(on: tableName) } } - func set(indexes: [TableIndex], forTableName tableName: String) { + func set(indexes: [IndexInfo], forTableName tableName: String) { cache.write { $0.set(indexes: indexes, forTableName: tableName) } } } diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 633679445..6ec74806c 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -116,10 +116,11 @@ public protocol MutablePersistable : TableMapping { /// that they invoke the performUpdate() method. /// /// - 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. - func update(_ db: Database) throws + func update(_ db: Database, columns: Set) throws /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. @@ -187,9 +188,47 @@ public extension MutablePersistable { /// Executes an UPDATE statement. /// - /// The default implementation for update() invokes performUpdate(). + /// - parameter db: A database connection. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. + func update(_ db: Database, columns: Set) throws { + try performUpdate(db, columns: columns) + } + + /// Executes an UPDATE statement. + /// + /// - parameter db: A database connection. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. + func update(_ db: Database, columns: S) throws { + try update(db, columns: Set(columns.map { $0.name })) + } + + /// Executes an UPDATE statement. + /// + /// - parameter db: A database connection. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. + func update(_ db: Database, columns: S) throws { + try update(db, columns: Set(columns)) + } + + /// Executes an UPDATE statement that updates all table columns. + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. func update(_ db: Database) throws { - try performUpdate(db) + let databaseTableName = self.dynamicType.databaseTableName + let columns = try db.columns(in: databaseTableName) + try update(db, columns: Set(columns.map { $0.name })) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in @@ -252,8 +291,14 @@ public extension MutablePersistable { /// that adopt MutablePersistable can invoke performUpdate() in their /// implementation of update(). They should not provide their own /// implementation of performUpdate(). - func performUpdate(_ db: Database) throws { - try DataMapper(db, self).updateStatement().execute() + /// + /// - parameter db: A database connection. + /// - parameter columns: The columns to update. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.NotFound is thrown if the primary key does not + /// match any row in the database. + func performUpdate(_ db: Database, columns: Set) throws { + try DataMapper(db, self).updateStatement(columns: columns).execute() if db.changesCount == 0 { throw PersistenceError.recordNotFound(self) } @@ -499,14 +544,17 @@ final class DataMapper { return statement } - func updateStatement() -> UpdateStatement { + func updateStatement(columns: Set) -> UpdateStatement { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey?.columns ?? [] let primaryKeyValues = databaseValues(for: primaryKeyColumns, inDictionary: persistentDictionary) GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "record can not be identified. persistentDictionary must contain non-nil value(s) for the key(s) \(primaryKeyColumns.joined(separator: ","))") - // Update everything but primary key - var updatedColumns = persistentDictionary.keys.removing(contentsOf: primaryKeyColumns) + // Don't update primary key columns + var updatedColumns = Array(persistentDictionary.keys) + .map { $0.lowercased() } + .filter { (lowercaseKey: String) in columns.contains { $0.lowercased() == lowercaseKey } } + .filter { (lowercaseKey: String) in !primaryKeyColumns.contains { $0.lowercased() == lowercaseKey } } if updatedColumns.isEmpty { // IMPLEMENTATION NOTE // diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 6e198f024..bc8b6e097 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -249,13 +249,14 @@ public class Record : RowConvertible, TableMapping, Persistable { /// 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. - public func update(_ db: Database) throws { + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + public func update(_ db: Database, columns: Set) throws { // The simplest code would be: // - // try performUpdate(db) + // try performUpdate(db, columns: columns) // hasPersistentChangedValues = false // // But this triggers two calls to persistentDictionary, and this is both @@ -265,7 +266,7 @@ public class Record : RowConvertible, TableMapping, Persistable { // So let's provide our custom implementation of insert, which uses the // same persistentDictionary for both update, and change tracking. let dataMapper = DataMapper(db, self) - try dataMapper.updateStatement().execute() + try dataMapper.updateStatement(columns: columns).execute() if db.changesCount == 0 { throw PersistenceError.recordNotFound(self) } diff --git a/README.md b/README.md index ccd749537..6baa80245 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-3-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) ========== -GRDB.swift is an SQLite toolkit for Swift 3.0 Preview 3 (July 18, 2016). +GRDB.swift is a Swift application toolkit that provides access to SQLite databases. + +It targets Swift 3.0 Preview 3 (July 18, 2016). It ships with a **low-level SQLite API**, and high-level tools that help dealing with databases: @@ -19,13 +21,13 @@ More than a set of tools that leverage SQLite abilities, GRDB is also: - **Safer**: read the blog post [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) - **Faster**: see [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) - Well documented & tested -- Suited for experienced SQLite users as well as beginners. -You should give it a try. +For a general overview of how a protocol-oriented library impacts database acesses, have a look at [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3). + --- -The Swift3 branch has no version. It is currently synced with v0.76.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.77.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. @@ -105,11 +107,11 @@ try dbQueue.inDatabase { db in isFavorite: false, coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) - try berlin.insert(dbQueue) + try berlin.insert(db) berlin.id // some value berlin.isFavorite = true - try berlin.update(dbQueue) + try berlin.update(db) // Fetch [PointOfInterest] from SQL let pois = PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests") @@ -280,7 +282,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/Configuration.html) for more details. ## Database Pools @@ -360,7 +362,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -677,28 +679,27 @@ case .blob(let data): print("Data: \(data)") } ``` -You can extract [values](#values) (Bool, Int, String, Date, Swift enums, etc.) from DatabaseValue, just like you do from [rows](#column-values): +You can extract [values](#values) (Bool, Int, String, Date, Swift enums, etc.) from DatabaseValue with the [DatabaseValueConvertible.fromDatabaseValue()](#custom-value-types) method: ```swift let dbv = row.databaseValue(named: "bookCount") -let bookCount: Int = dbv.value() -let bookCount64: Int64 = dbv.value() -let hasBooks: Bool = dbv.value() // false when 0 +let bookCount = Int.fromDatabaseValue(dbv) // Int? +let bookCount64 = Int64.fromDatabaseValue(dbv) // Int64? +let hasBooks = Bool.fromDatabaseValue(dbv) // Bool?, false when 0 let dbv = row.databaseValue(named: "date") -let string: String = dbv.value() // "2015-09-11 18:14:15.123" -let date: Date = dbv.value() // Date -self.date = dbv.value() // Depends on the type of the property. +let string = String.fromDatabaseValue(dbv) // "2015-09-11 18:14:15.123" +let date = NSDate.fromDatabaseValue(dbv) // NSDate? ``` -Invalid conversions from non-NULL values raise a fatal error. This fatal error can be avoided with the [DatabaseValueConvertible.fromDatabaseValue()](#custom-value-types) method: +`fromDatabaseValue` returns nil for invalid conversions: ```swift let row = Row.fetchOne(db, "SELECT 'foo'")! let dbv = row.databaseValue(at: 0) -let string = dbv.value() as String // "foo" -let date = dbv.value() as Date? // fatal error: could not convert "foo" to Date. -let date = Date.fromDatabaseValue(dbv) // nil +let string = String.fromDatabaseValue(dbv) // "foo" +let int = Int.fromDatabaseValue(dbv) // nil +let date = NSDate.fromDatabaseValue(dbv) // nil ``` @@ -719,7 +720,7 @@ for (columnName, databaseValue) in row { let row = Row(["name": "foo", "date": nil]) ``` -Yet rows are not real dictionaries, because they may contain duplicate keys: +Yet rows are not real dictionaries: they are ordered, and may contain duplicate keys: ```swift let row = Row.fetchOne(db, "SELECT 1 AS foo, 2 AS foo")! @@ -1297,7 +1298,7 @@ GRDB provides four high-level methods as well: ```swift db.tableExists("persons") // Bool, true if the table exists -db.indexes(on: "persons") // [TableIndex], the indexes defined on the table +db.indexes(on: "persons") // [IndexInfo], the indexes defined on the table try db.table("persons", hasUniqueKey: ["id"]) // Bool, true if column(s) is a unique key try db.primaryKey("persons") // PrimaryKey? ``` @@ -1444,10 +1445,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.76.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters -- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/ColumnMapping.html): a row adapter that renames row columns -- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row -- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes +- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters +- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/ColumnMapping.html): a row adapter that renames row columns +- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row +- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes ## Raw SQLite Pointers @@ -1518,10 +1519,19 @@ On top of the SQLite API described above, GRDB provides a toolkit for applicatio ## Records -**On top of the [SQLite API](#sqlite-api), GRDB provides protocols and a class** that help manipulating database rows as regular objects named "records". +**On top of the [SQLite API](#sqlite-api), GRDB provides protocols and a class** that help manipulating database rows as regular objects named "records": + +```swift +if let poi = PointOfInterest.fetchOne(db, key: 1) { + poi.isFavorite = true + try poi.update(db) +} +``` Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the `Record` class, and get the full toolkit in one go: fetching methods, persistence methods, and changes tracking. +> :point_up: **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, and do not auto-update. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. + #### Inserting Records @@ -1824,11 +1834,12 @@ paris.id // some value [Record](#record-class) subclasses and types that adopt [Persistable](#persistable-protocol) are given default implementations for methods that insert, update, and delete: ```swift -try pointOfInterest.insert(db) // INSERT -try pointOfInterest.update(db) // UPDATE -try pointOfInterest.save(db) // Inserts or updates -try pointOfInterest.delete(db) // DELETE -pointOfInterest.exists(db) // Bool +try pointOfInterest.insert(db) // INSERT +try pointOfInterest.update(db) // UPDATE +try pointOfInterest.update(db, columns: ...) // UPDATE +try pointOfInterest.save(db) // Inserts or updates +try pointOfInterest.delete(db) // DELETE +pointOfInterest.exists(db) // Bool ``` - `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. @@ -1880,9 +1891,9 @@ struct Link : Persistable { try performInsert(db) } - func update(_ db: Database) throws { + func update(_ db: Database, columns: Set) throws { try validate() - try performUpdate(db) + try performUpdate(db, columns: columns) } func validate() throws { @@ -3358,7 +3369,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.76.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.76.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.76.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.77.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.77.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: diff --git a/Support/Info.plist b/Support/Info.plist index 1a9f30e9f..0564988c3 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.76.0 + 0.77.0 CFBundleSignature ???? CFBundleVersion diff --git a/Tests/Private/DatabasePoolSchemaCacheTests.swift b/Tests/Private/DatabasePoolSchemaCacheTests.swift index 50e51c5b5..c48c8fd7d 100644 --- a/Tests/Private/DatabasePoolSchemaCacheTests.swift +++ b/Tests/Private/DatabasePoolSchemaCacheTests.swift @@ -21,12 +21,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { dbPool.write { db in // Assert that the writer cache is empty XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) + XCTAssertTrue(db.schemaCache.columns(in: "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.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) } @@ -35,6 +37,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { let primaryKey = try db.primaryKey("items")! XCTAssertEqual(primaryKey.rowIDColumn, "id") + let columns = try db.columns(in: "items") + XCTAssertEqual(columns.count, 4) + // TODO: test more properties + XCTAssertEqual(columns[0].name, "id") + XCTAssertEqual(columns[1].name, "email") + XCTAssertEqual(columns[2].name, "foo") + XCTAssertEqual(columns[3].name, "bar") + let indexes = db.indexes(on: "items") XCTAssertEqual(indexes.count, 2) for index in indexes { @@ -50,12 +60,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { // Assert that reader cache is warmed XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) + XCTAssertTrue(db.schemaCache.columns(in: "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.columns(in: "items") != nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) } @@ -65,12 +77,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { // Assert that the writer cache is empty XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) + XCTAssertTrue(db.schemaCache.columns(in: "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.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) } diff --git a/Tests/Public/Core/Database/TableIndexTests.swift b/Tests/Public/Core/Database/IndexInfoTests.swift similarity index 98% rename from Tests/Public/Core/Database/TableIndexTests.swift rename to Tests/Public/Core/Database/IndexInfoTests.swift index 5cc617a10..32f7dda84 100644 --- a/Tests/Public/Core/Database/TableIndexTests.swift +++ b/Tests/Public/Core/Database/IndexInfoTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -class TableIndexTests: GRDBTestCase { +class IndexInfoTests: GRDBTestCase { func testIndexes() { assertNoError { db in diff --git a/Tests/Public/Core/Persistable/MutablePersistableTests.swift b/Tests/Public/Core/Persistable/MutablePersistableTests.swift index 657e51a42..40b205b5e 100644 --- a/Tests/Public/Core/Persistable/MutablePersistableTests.swift +++ b/Tests/Public/Core/Persistable/MutablePersistableTests.swift @@ -63,9 +63,9 @@ private struct MutablePersistableCustomizedCountry : MutablePersistable { try performInsert(db) } - func update(_ db: Database) throws { + func update(_ db: Database, columns: Set) throws { willUpdate() - try performUpdate(db) + try performUpdate(db, columns: columns) } mutating func save(_ db: Database) throws { @@ -143,6 +143,54 @@ class MutablePersistableTests: GRDBTestCase { } } + func testPartialUpdateMutablePersistablePerson() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.insert(db) + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.insert(db) + + do { + person1.name = "Craig" + try person1.update(db, columns: [String]()) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + + do { + person1.name = "Craig" + try person1.update(db, columns: [SQLColumn("name")]) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + + do { + person1.name = "David" + try person1.update(db, columns: ["age"]) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + } + func testSaveMutablePersistablePerson() { assertNoError { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/Public/Core/Persistable/PersistableTests.swift b/Tests/Public/Core/Persistable/PersistableTests.swift index 8b702e2b0..509eeba9b 100644 --- a/Tests/Public/Core/Persistable/PersistableTests.swift +++ b/Tests/Public/Core/Persistable/PersistableTests.swift @@ -71,9 +71,9 @@ private struct PersistableCustomizedCountry : Persistable { try performInsert(db) } - func update(_ db: Database) throws { + func update(_ db: Database, columns: Set) throws { willUpdate() - try performUpdate(db) + try performUpdate(db, columns: columns) } func save(_ db: Database) throws { @@ -199,6 +199,54 @@ class PersistableTests: GRDBTestCase { } } + func testPartialUpdatePersistablePersonClass() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person1.insert(db) + let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + try person2.insert(db) + + do { + person1.name = "Craig" + try person1.update(db, columns: [String]()) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + + do { + person1.name = "Craig" + try person1.update(db, columns: [SQLColumn("name")]) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + + do { + person1.name = "David" + try person1.update(db, columns: ["age"]) + + let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Craig") + XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") + } + } + } + } + func testSavePersistablePersonClass() { assertNoError { let dbQueue = try makeDatabaseQueue() @@ -312,6 +360,42 @@ class PersistableTests: GRDBTestCase { } } + func testPartialUpdatePersistableCountry() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.insert(db) + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.insert(db) + + do { + country1.name = "France Métropolitaine" + try country1.update(db, columns: [String]()) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + + do { + country1.name = "France Métropolitaine" + try country1.update(db, columns: [SQLColumn("name")]) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + } + func testSavePersistableCountry() { assertNoError { let dbQueue = try makeDatabaseQueue() @@ -468,6 +552,53 @@ class PersistableTests: GRDBTestCase { } } + func testPartialUpdatePersistableCustomizedCountry() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(db) + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(db) + + country1.name = "France Métropolitaine" + try country1.update(db, columns: ["name"]) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(db, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + } + func testSavePersistableCustomizedCountry() { assertNoError { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/Public/Record/RecordSubClassTests.swift b/Tests/Public/Record/RecordSubClassTests.swift index 2c4388ab9..498e704a4 100644 --- a/Tests/Public/Record/RecordSubClassTests.swift +++ b/Tests/Public/Record/RecordSubClassTests.swift @@ -104,9 +104,9 @@ private class PersonWithOverrides : Person { try super.insert(db) } - override func update(_ db: Database) throws { + override func update(_ db: Database, columns: Set) throws { lastSavingMethod = .update - try super.update(db) + try super.update(db, columns: columns) } }