diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e43a9a82..6521ccf45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,169 @@ Release Notes ============= +## 0.51.2 + +Released March 14, 2016 + +**Fixed** + +- A race condition that could prevent `Configuration.fileAttributes` to apply to some database files. + + +## 0.51.1 + +Released March 13, 2016 + +Nothing new, but performance improvements + + +## 0.51.0 + +Released March 13, 2016 + +**New** + +- Support for file attributes + + ```swift + var config = Configuration() + config.fileAttributes = [NSFileProtectionKey: NSFileProtectionComplete] + let dbPool = DatabasePool(path: ".../db.sqlite", configuration: config) + ``` + + GRDB will take care of applying them to the database file and all its derivatives (`-wal` and `-shm` files created by the [WAL mode](https://www.sqlite.org/wal.html), as well as [temporary files](https://www.sqlite.org/tempfiles.html)). + + +## 0.50.1 + +Released March 12, 2016 + +**Fixed** + +- A database connection won't close as long as there is a database sequence being iterated. + + +## 0.50.0 + +Released March 12, 2016 + +**New** + +- Database updates no longer need to be executed in a closure: + + ```swift + // Before: + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE ...") + let person = Person(...) + try person.insert(db) + } + + // New: + try dbQueue.execute("CREATE TABLE ...") + let person = Person(...) + try person.insert(dbQueue) + ``` + +- DatabaseQueue and DatabasePool both adopt the new [DatabaseReader](https://github.com/groue/GRDB.swift/tree/master/GRDB/Core/DatabaseReader.swift) and [DatabaseWriter](https://github.com/groue/GRDB.swift/tree/master/GRDB/Core/DatabaseWriter.swift) protocols. + + +**Breaking Changes** + +- The following methods have changed their signatures: + + ```swift + protocol MutablePersistable { + mutating func insert(db: DatabaseWriter) throws + func update(db: DatabaseWriter) throws + mutating func save(db: DatabaseWriter) throws + func delete(db: DatabaseWriter) throws -> Bool + func exists(db: DatabaseReader) -> Bool + } + + protocol Persistable { + func insert(db: DatabaseWriter) throws + func save(db: DatabaseWriter) throws + } + + class Record { + func insert(db: DatabaseWriter) throws + func update(db: DatabaseWriter) throws + func save(db: DatabaseWriter) throws + func delete(db: DatabaseWriter) throws -> Bool + func exists(db: DatabaseReader) -> Bool + } + ``` + + +## 0.49.0 + +Released March 11, 2016 + +**New** + +- Read-only database pools grant you with concurrent reads on a database, without activating the WAL mode. +- All fetchable types can now be fetched directly from database queues and pools: + + ```swift + // Before: + let persons = dbQueue.inDatabase { db in + Person.fetchAll(db) + } + + // New: + let persons = Person.fetchAll(dbQueue) + ``` + +**Breaking Changes** + +- [Transaction observers](https://github.com/groue/GRDB.swift#database-changes-observation) are no longer added to Database instances, but to DatabaseQueue and DatabasePool. + + +## 0.48.0 + +Released March 10, 2016 + +**New** + +- `DatabaseQueue.releaseMemory()` and `DatabasePool.releaseMemory()` claim non-essential memory ([documentation](https://github.com/groue/GRDB.swift#memory-management)) + +**Breaking Changes** + +- Custom [functions](https://github.com/groue/GRDB.swift#custom-sql-functions) and [collations](https://github.com/groue/GRDB.swift#string-comparison) are no longer added to Database instances, but to DatabaseQueue and DatabasePool. + + +## 0.47.0 + +Released March 10, 2016 + +**New** + +- Support for concurrent accesses to the database, using the SQLite [WAL Mode](https://www.sqlite.org/wal.html). ([documentation](https://github.com/groue/GRDB.swift#database-pools)) + + +## 0.46.0 + +Released March 5, 2016 + +**New** + +- Improved counting support in the query interface ([documentation](https://github.com/groue/GRDB.swift#fetching-aggregated-values)) + +**Breaking Changes** + +- Swift enums that behave like other database values now need to declare `DatabaseValueConvertible` adoption. The `DatabaseIntRepresentable`, `DatabaseInt32Representable`, `DatabaseInt64Representable` and `DatabaseStringRepresentable` protocols have been removed ([documentation](https://github.com/groue/GRDB.swift#swift-enums)) + + +## 0.45.1 + +Released February 11, 2016 + +**Fixed** + +- [iOS7 demo application](https://github.com/groue/GRDB.swift/tree/master/DemoApps/GRDBDemoiOS7) builds again. + + ## 0.45.0 Released February 9, 2016 diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index 02fa87682..4bf67794e 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -17,6 +17,22 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDele return true } + + func applicationDidReceiveMemoryWarning(application: UIApplication) { + // Release as much memory as possible. + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { + dbQueue.releaseMemory() + } + } + + func applicationDidEnterBackground(application: UIApplication) { + let task = application.beginBackgroundTaskWithExpirationHandler(nil) + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { + // Release as much memory as possible. + dbQueue.releaseMemory() + application.endBackgroundTask(task) + } + } // MARK: - Split view diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift index dd12a9ce7..e9de5ae1f 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift @@ -35,10 +35,7 @@ func setupDatabase() { let collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in return (lhs as NSString).localizedCaseInsensitiveCompare(rhs) } - - dbQueue.inDatabase { db in - db.addCollation(collation) - } + dbQueue.addCollation(collation) // Use DatabaseMigrator to setup the database diff --git a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7.xcodeproj/project.pbxproj b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7.xcodeproj/project.pbxproj index b5c384c7a..788336347 100644 --- a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7.xcodeproj/project.pbxproj +++ b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7.xcodeproj/project.pbxproj @@ -7,6 +7,44 @@ objects = { /* Begin PBXBuildFile section */ + 560A37E01C91391800949E71 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B31C91391800949E71 /* Configuration.swift */; }; + 560A37E11C91391800949E71 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B41C91391800949E71 /* Database.swift */; }; + 560A37E21C91391800949E71 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B51C91391800949E71 /* DatabaseError.swift */; }; + 560A37E31C91391800949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B61C91391800949E71 /* DatabasePool.swift */; }; + 560A37E41C91391800949E71 /* DatabaseQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B71C91391800949E71 /* DatabaseQueue.swift */; }; + 560A37E51C91391800949E71 /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B81C91391800949E71 /* DatabaseSchemaCache.swift */; }; + 560A37E61C91391800949E71 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B91C91391800949E71 /* DatabaseValue.swift */; }; + 560A37E71C91391800949E71 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BA1C91391800949E71 /* DatabaseValueConvertible.swift */; }; + 560A37E81C91391800949E71 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BB1C91391800949E71 /* Row.swift */; }; + 560A37E91C91391800949E71 /* SerializedDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BC1C91391800949E71 /* SerializedDatabase.swift */; }; + 560A37EA1C91391800949E71 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BD1C91391800949E71 /* Statement.swift */; }; + 560A37EB1C91391800949E71 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BE1C91391800949E71 /* StatementColumnConvertible.swift */; }; + 560A37EC1C91391800949E71 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C11C91391800949E71 /* CGFloat.swift */; }; + 560A37ED1C91391800949E71 /* DatabaseCoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C31C91391800949E71 /* DatabaseCoder.swift */; }; + 560A37EE1C91391800949E71 /* DatabaseDateComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C41C91391800949E71 /* DatabaseDateComponents.swift */; }; + 560A37EF1C91391800949E71 /* DatabaseValue+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C51C91391800949E71 /* DatabaseValue+Foundation.swift */; }; + 560A37F01C91391800949E71 /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C61C91391800949E71 /* NSData.swift */; }; + 560A37F11C91391800949E71 /* NSDate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C71C91391800949E71 /* NSDate.swift */; }; + 560A37F21C91391800949E71 /* NSNull.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C81C91391800949E71 /* NSNull.swift */; }; + 560A37F31C91391800949E71 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C91C91391800949E71 /* NSNumber.swift */; }; + 560A37F41C91391800949E71 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CA1C91391800949E71 /* NSString.swift */; }; + 560A37F51C91391800949E71 /* NSURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CB1C91391800949E71 /* NSURL.swift */; }; + 560A37F61C91391800949E71 /* Row+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CC1C91391800949E71 /* Row+Foundation.swift */; }; + 560A37F71C91391800949E71 /* StatementArguments+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CD1C91391800949E71 /* StatementArguments+Foundation.swift */; }; + 560A37F81C91391800949E71 /* RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CF1C91391800949E71 /* RawRepresentable.swift */; }; + 560A37F91C91391800949E71 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D01C91391800949E71 /* StandardLibrary.swift */; }; + 560A37FA1C91391800949E71 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D11C91391800949E71 /* Utils.swift */; }; + 560A37FB1C91391800949E71 /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D31C91391800949E71 /* FetchRequest.swift */; }; + 560A37FC1C91391800949E71 /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D41C91391800949E71 /* SQLCollation.swift */; }; + 560A37FD1C91391800949E71 /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D51C91391800949E71 /* SQLFunction.swift */; }; + 560A37FE1C91391800949E71 /* SQLOperator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D61C91391800949E71 /* SQLOperator.swift */; }; + 560A37FF1C91391800949E71 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D71C91391800949E71 /* SQLSelectQuery.swift */; }; + 560A38001C91391800949E71 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D91C91391800949E71 /* DatabaseMigrator.swift */; }; + 560A38011C91391800949E71 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DA1C91391800949E71 /* Migration.swift */; }; + 560A38021C91391800949E71 /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DC1C91391800949E71 /* Persistable.swift */; }; + 560A38031C91391800949E71 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DD1C91391800949E71 /* Record.swift */; }; + 560A38041C91391800949E71 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DE1C91391800949E71 /* RowConvertible.swift */; }; + 560A38051C91391800949E71 /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DF1C91391800949E71 /* TableMapping.swift */; }; 562FF9951BCE8FA400759400 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9941BCE8FA400759400 /* AppDelegate.swift */; }; 562FF9971BCE8FA400759400 /* PersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9961BCE8FA400759400 /* PersonsViewController.swift */; }; 562FF99A1BCE8FA400759400 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 562FF9981BCE8FA400759400 /* Main.storyboard */; }; @@ -15,45 +53,51 @@ 562FF9EC1BCE903D00759400 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 562FF9EB1BCE903D00759400 /* libsqlite3.tbd */; }; 562FF9EF1BCE912C00759400 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */; }; 562FF9F21BCE914E00759400 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9F11BCE914E00759400 /* Person.swift */; }; + 563363C81C942CAE000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C71C942CAE000BE133 /* DatabaseReader.swift */; }; + 563363CA1C942CB4000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C91C942CB4000BE133 /* DatabaseWriter.swift */; }; + 563363F01C95A41B000BE133 /* DatabaseStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363EF1C95A41B000BE133 /* DatabaseStore.swift */; }; 566A20F31C58A4B300C5A218 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F21C58A4B300C5A218 /* AppDatabase.swift */; }; - 566A21271C58A54F00C5A218 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F61C58A54F00C5A218 /* Configuration.swift */; }; - 566A21281C58A54F00C5A218 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F71C58A54F00C5A218 /* Database.swift */; }; - 566A21291C58A54F00C5A218 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F81C58A54F00C5A218 /* DatabaseError.swift */; }; - 566A212A1C58A54F00C5A218 /* DatabaseQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F91C58A54F00C5A218 /* DatabaseQueue.swift */; }; - 566A212B1C58A54F00C5A218 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FA1C58A54F00C5A218 /* DatabaseValue.swift */; }; - 566A212C1C58A54F00C5A218 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FC1C58A54F00C5A218 /* DatabaseValueConvertible.swift */; }; - 566A212D1C58A54F00C5A218 /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FD1C58A54F00C5A218 /* Persistable.swift */; }; - 566A212E1C58A54F00C5A218 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FE1C58A54F00C5A218 /* RowConvertible.swift */; }; - 566A212F1C58A54F00C5A218 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FF1C58A54F00C5A218 /* SQLiteStatementConvertible.swift */; }; - 566A21301C58A54F00C5A218 /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21001C58A54F00C5A218 /* TableMapping.swift */; }; - 566A21311C58A54F00C5A218 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21011C58A54F00C5A218 /* Row.swift */; }; - 566A21321C58A54F00C5A218 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21021C58A54F00C5A218 /* Statement.swift */; }; - 566A21331C58A54F00C5A218 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21031C58A54F00C5A218 /* Utils.swift */; }; - 566A21341C58A54F00C5A218 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21051C58A54F00C5A218 /* CGFloat.swift */; }; - 566A21351C58A54F00C5A218 /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21071C58A54F00C5A218 /* FetchRequest.swift */; }; - 566A21361C58A54F00C5A218 /* Collation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21091C58A54F00C5A218 /* Collation.swift */; }; - 566A21371C58A54F00C5A218 /* Function.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210A1C58A54F00C5A218 /* Function.swift */; }; - 566A21381C58A54F00C5A218 /* Operator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210B1C58A54F00C5A218 /* Operator.swift */; }; - 566A21391C58A54F00C5A218 /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210C1C58A54F00C5A218 /* SQLQuery.swift */; }; - 566A213A1C58A54F00C5A218 /* DatabaseCoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210E1C58A54F00C5A218 /* DatabaseCoder.swift */; }; - 566A213B1C58A54F00C5A218 /* DatabaseDateComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210F1C58A54F00C5A218 /* DatabaseDateComponents.swift */; }; - 566A213C1C58A54F00C5A218 /* DatabaseValue+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21101C58A54F00C5A218 /* DatabaseValue+Foundation.swift */; }; - 566A213D1C58A54F00C5A218 /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21111C58A54F00C5A218 /* NSData.swift */; }; - 566A213E1C58A54F00C5A218 /* NSDate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21121C58A54F00C5A218 /* NSDate.swift */; }; - 566A213F1C58A54F00C5A218 /* NSNull.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21131C58A54F00C5A218 /* NSNull.swift */; }; - 566A21401C58A54F00C5A218 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21141C58A54F00C5A218 /* NSNumber.swift */; }; - 566A21411C58A54F00C5A218 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21151C58A54F00C5A218 /* NSString.swift */; }; - 566A21421C58A54F00C5A218 /* NSURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21161C58A54F00C5A218 /* NSURL.swift */; }; - 566A21431C58A54F00C5A218 /* Row+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21171C58A54F00C5A218 /* Row+Foundation.swift */; }; - 566A21441C58A54F00C5A218 /* StatementArguments+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21181C58A54F00C5A218 /* StatementArguments+Foundation.swift */; }; - 566A21471C58A54F00C5A218 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */; }; - 566A21481C58A54F00C5A218 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A211F1C58A54F00C5A218 /* Migration.swift */; }; - 566A214A1C58A54F00C5A218 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21231C58A54F00C5A218 /* Record.swift */; }; - 566A214B1C58A54F00C5A218 /* RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21251C58A54F00C5A218 /* RawRepresentable.swift */; }; - 566A214C1C58A54F00C5A218 /* StandardLibraryTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 560A37B31C91391800949E71 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = ""; }; + 560A37B41C91391800949E71 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = ""; }; + 560A37B51C91391800949E71 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = ""; }; + 560A37B61C91391800949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; + 560A37B71C91391800949E71 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = ""; }; + 560A37B81C91391800949E71 /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = ""; }; + 560A37B91C91391800949E71 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = ""; }; + 560A37BA1C91391800949E71 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; + 560A37BB1C91391800949E71 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = ""; }; + 560A37BC1C91391800949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; + 560A37BD1C91391800949E71 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = ""; }; + 560A37BE1C91391800949E71 /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; + 560A37C11C91391800949E71 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = ""; }; + 560A37C31C91391800949E71 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = ""; }; + 560A37C41C91391800949E71 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = ""; }; + 560A37C51C91391800949E71 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = ""; }; + 560A37C61C91391800949E71 /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; + 560A37C71C91391800949E71 /* NSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDate.swift; sourceTree = ""; }; + 560A37C81C91391800949E71 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = ""; }; + 560A37C91C91391800949E71 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = ""; }; + 560A37CA1C91391800949E71 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = ""; }; + 560A37CB1C91391800949E71 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = ""; }; + 560A37CC1C91391800949E71 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = ""; }; + 560A37CD1C91391800949E71 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = ""; }; + 560A37CF1C91391800949E71 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = ""; }; + 560A37D01C91391800949E71 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; + 560A37D11C91391800949E71 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; + 560A37D31C91391800949E71 /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; + 560A37D41C91391800949E71 /* SQLCollation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollation.swift; sourceTree = ""; }; + 560A37D51C91391800949E71 /* SQLFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunction.swift; sourceTree = ""; }; + 560A37D61C91391800949E71 /* SQLOperator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperator.swift; sourceTree = ""; }; + 560A37D71C91391800949E71 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = ""; }; + 560A37D91C91391800949E71 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = ""; }; + 560A37DA1C91391800949E71 /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; + 560A37DC1C91391800949E71 /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; + 560A37DD1C91391800949E71 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; + 560A37DE1C91391800949E71 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; + 560A37DF1C91391800949E71 /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; 562FF9911BCE8FA400759400 /* GRDBDemoiOS7.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoiOS7.app; sourceTree = BUILT_PRODUCTS_DIR; }; 562FF9941BCE8FA400759400 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 562FF9961BCE8FA400759400 /* PersonsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersonsViewController.swift; sourceTree = ""; }; @@ -65,42 +109,10 @@ 562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = ""; }; 562FF9F11BCE914E00759400 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = ""; }; 562FF9F41BCE930C00759400 /* GRDBDemoiOS7-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBDemoiOS7-Bridging-Header.h"; sourceTree = ""; }; + 563363C71C942CAE000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; + 563363C91C942CB4000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; + 563363EF1C95A41B000BE133 /* DatabaseStore.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseStore.swift; sourceTree = ""; }; 566A20F21C58A4B300C5A218 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; - 566A20F61C58A54F00C5A218 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = ""; }; - 566A20F71C58A54F00C5A218 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = ""; }; - 566A20F81C58A54F00C5A218 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = ""; }; - 566A20F91C58A54F00C5A218 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = ""; }; - 566A20FA1C58A54F00C5A218 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = ""; }; - 566A20FC1C58A54F00C5A218 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; - 566A20FD1C58A54F00C5A218 /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; - 566A20FE1C58A54F00C5A218 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; - 566A20FF1C58A54F00C5A218 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = ""; }; - 566A21001C58A54F00C5A218 /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; - 566A21011C58A54F00C5A218 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = ""; }; - 566A21021C58A54F00C5A218 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = ""; }; - 566A21031C58A54F00C5A218 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; - 566A21051C58A54F00C5A218 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = ""; }; - 566A21071C58A54F00C5A218 /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; - 566A21091C58A54F00C5A218 /* Collation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Collation.swift; sourceTree = ""; }; - 566A210A1C58A54F00C5A218 /* Function.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Function.swift; sourceTree = ""; }; - 566A210B1C58A54F00C5A218 /* Operator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Operator.swift; sourceTree = ""; }; - 566A210C1C58A54F00C5A218 /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = ""; }; - 566A210E1C58A54F00C5A218 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = ""; }; - 566A210F1C58A54F00C5A218 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = ""; }; - 566A21101C58A54F00C5A218 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = ""; }; - 566A21111C58A54F00C5A218 /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; - 566A21121C58A54F00C5A218 /* NSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDate.swift; sourceTree = ""; }; - 566A21131C58A54F00C5A218 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = ""; }; - 566A21141C58A54F00C5A218 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = ""; }; - 566A21151C58A54F00C5A218 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = ""; }; - 566A21161C58A54F00C5A218 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = ""; }; - 566A21171C58A54F00C5A218 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = ""; }; - 566A21181C58A54F00C5A218 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = ""; }; - 566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = ""; }; - 566A211F1C58A54F00C5A218 /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; - 566A21231C58A54F00C5A218 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; - 566A21251C58A54F00C5A218 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = ""; }; - 566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibraryTypes.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -115,6 +127,107 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 560A37B21C91391800949E71 /* Core */ = { + isa = PBXGroup; + children = ( + 560A37B31C91391800949E71 /* Configuration.swift */, + 560A37B41C91391800949E71 /* Database.swift */, + 560A37B51C91391800949E71 /* DatabaseError.swift */, + 560A37B61C91391800949E71 /* DatabasePool.swift */, + 560A37B71C91391800949E71 /* DatabaseQueue.swift */, + 563363C71C942CAE000BE133 /* DatabaseReader.swift */, + 560A37B81C91391800949E71 /* DatabaseSchemaCache.swift */, + 563363EF1C95A41B000BE133 /* DatabaseStore.swift */, + 560A37B91C91391800949E71 /* DatabaseValue.swift */, + 560A37BA1C91391800949E71 /* DatabaseValueConvertible.swift */, + 563363C91C942CB4000BE133 /* DatabaseWriter.swift */, + 560A37BB1C91391800949E71 /* Row.swift */, + 560A37BC1C91391800949E71 /* SerializedDatabase.swift */, + 560A37BD1C91391800949E71 /* Statement.swift */, + 560A37BE1C91391800949E71 /* StatementColumnConvertible.swift */, + 560A37BF1C91391800949E71 /* Support */, + 560A37D11C91391800949E71 /* Utils.swift */, + ); + path = Core; + sourceTree = ""; + }; + 560A37BF1C91391800949E71 /* Support */ = { + isa = PBXGroup; + children = ( + 560A37C01C91391800949E71 /* CoreGraphics */, + 560A37C21C91391800949E71 /* Foundation */, + 560A37CE1C91391800949E71 /* StandardLibrary */, + ); + path = Support; + sourceTree = ""; + }; + 560A37C01C91391800949E71 /* CoreGraphics */ = { + isa = PBXGroup; + children = ( + 560A37C11C91391800949E71 /* CGFloat.swift */, + ); + path = CoreGraphics; + sourceTree = ""; + }; + 560A37C21C91391800949E71 /* Foundation */ = { + isa = PBXGroup; + children = ( + 560A37C31C91391800949E71 /* DatabaseCoder.swift */, + 560A37C41C91391800949E71 /* DatabaseDateComponents.swift */, + 560A37C51C91391800949E71 /* DatabaseValue+Foundation.swift */, + 560A37C61C91391800949E71 /* NSData.swift */, + 560A37C71C91391800949E71 /* NSDate.swift */, + 560A37C81C91391800949E71 /* NSNull.swift */, + 560A37C91C91391800949E71 /* NSNumber.swift */, + 560A37CA1C91391800949E71 /* NSString.swift */, + 560A37CB1C91391800949E71 /* NSURL.swift */, + 560A37CC1C91391800949E71 /* Row+Foundation.swift */, + 560A37CD1C91391800949E71 /* StatementArguments+Foundation.swift */, + ); + path = Foundation; + sourceTree = ""; + }; + 560A37CE1C91391800949E71 /* StandardLibrary */ = { + isa = PBXGroup; + children = ( + 560A37CF1C91391800949E71 /* RawRepresentable.swift */, + 560A37D01C91391800949E71 /* StandardLibrary.swift */, + ); + path = StandardLibrary; + sourceTree = ""; + }; + 560A37D21C91391800949E71 /* FetchRequest */ = { + isa = PBXGroup; + children = ( + 560A37D31C91391800949E71 /* FetchRequest.swift */, + 560A37D41C91391800949E71 /* SQLCollation.swift */, + 560A37D51C91391800949E71 /* SQLFunction.swift */, + 560A37D61C91391800949E71 /* SQLOperator.swift */, + 560A37D71C91391800949E71 /* SQLSelectQuery.swift */, + ); + path = FetchRequest; + sourceTree = ""; + }; + 560A37D81C91391800949E71 /* Migrations */ = { + isa = PBXGroup; + children = ( + 560A37D91C91391800949E71 /* DatabaseMigrator.swift */, + 560A37DA1C91391800949E71 /* Migration.swift */, + ); + path = Migrations; + sourceTree = ""; + }; + 560A37DB1C91391800949E71 /* Record */ = { + isa = PBXGroup; + children = ( + 560A37DC1C91391800949E71 /* Persistable.swift */, + 560A37DD1C91391800949E71 /* Record.swift */, + 560A37DE1C91391800949E71 /* RowConvertible.swift */, + 560A37DF1C91391800949E71 /* TableMapping.swift */, + ); + path = Record; + sourceTree = ""; + }; 562FF9881BCE8FA400759400 = { isa = PBXGroup; children = ( @@ -139,7 +252,7 @@ 562FF9F01BCE913900759400 /* Controllers */, 562FF9F31BCE915B00759400 /* Models */, 562FF9A61BCE8FB000759400 /* Resources */, - 562FF9ED1BCE904D00759400 /* Libraries */, + 562FF9ED1BCE904D00759400 /* GRDB */, 562FF9A71BCE8FB600759400 /* Supporting Files */, ); path = GRDBDemoiOS7; @@ -164,13 +277,13 @@ name = "Supporting Files"; sourceTree = ""; }; - 562FF9ED1BCE904D00759400 /* Libraries */ = { + 562FF9ED1BCE904D00759400 /* GRDB */ = { isa = PBXGroup; children = ( 562FF9EB1BCE903D00759400 /* libsqlite3.tbd */, 566A20F41C58A54F00C5A218 /* GRDB */, ); - name = Libraries; + name = GRDB; sourceTree = ""; }; 562FF9F01BCE913900759400 /* Controllers */ = { @@ -193,118 +306,15 @@ 566A20F41C58A54F00C5A218 /* GRDB */ = { isa = PBXGroup; children = ( - 566A20F51C58A54F00C5A218 /* Core */, - 566A21041C58A54F00C5A218 /* CoreGraphics */, - 566A21061C58A54F00C5A218 /* FetchRequest */, - 566A210D1C58A54F00C5A218 /* Foundation */, - 566A211D1C58A54F00C5A218 /* Migrations */, - 566A21221C58A54F00C5A218 /* Record */, - 566A21241C58A54F00C5A218 /* Swift */, + 560A37B21C91391800949E71 /* Core */, + 560A37D21C91391800949E71 /* FetchRequest */, + 560A37D81C91391800949E71 /* Migrations */, + 560A37DB1C91391800949E71 /* Record */, ); name = GRDB; path = ../../../GRDB; sourceTree = ""; }; - 566A20F51C58A54F00C5A218 /* Core */ = { - isa = PBXGroup; - children = ( - 566A20F61C58A54F00C5A218 /* Configuration.swift */, - 566A20F71C58A54F00C5A218 /* Database.swift */, - 566A20F81C58A54F00C5A218 /* DatabaseError.swift */, - 566A20F91C58A54F00C5A218 /* DatabaseQueue.swift */, - 566A20FA1C58A54F00C5A218 /* DatabaseValue.swift */, - 566A20FB1C58A54F00C5A218 /* Protocols */, - 566A21011C58A54F00C5A218 /* Row.swift */, - 566A21021C58A54F00C5A218 /* Statement.swift */, - 566A21031C58A54F00C5A218 /* Utils.swift */, - ); - path = Core; - sourceTree = ""; - }; - 566A20FB1C58A54F00C5A218 /* Protocols */ = { - isa = PBXGroup; - children = ( - 566A20FC1C58A54F00C5A218 /* DatabaseValueConvertible.swift */, - 566A20FD1C58A54F00C5A218 /* Persistable.swift */, - 566A20FE1C58A54F00C5A218 /* RowConvertible.swift */, - 566A20FF1C58A54F00C5A218 /* SQLiteStatementConvertible.swift */, - 566A21001C58A54F00C5A218 /* TableMapping.swift */, - ); - path = Protocols; - sourceTree = ""; - }; - 566A21041C58A54F00C5A218 /* CoreGraphics */ = { - isa = PBXGroup; - children = ( - 566A21051C58A54F00C5A218 /* CGFloat.swift */, - ); - path = CoreGraphics; - sourceTree = ""; - }; - 566A21061C58A54F00C5A218 /* FetchRequest */ = { - isa = PBXGroup; - children = ( - 566A21071C58A54F00C5A218 /* FetchRequest.swift */, - 566A21081C58A54F00C5A218 /* SQLSupport */, - ); - path = FetchRequest; - sourceTree = ""; - }; - 566A21081C58A54F00C5A218 /* SQLSupport */ = { - isa = PBXGroup; - children = ( - 566A21091C58A54F00C5A218 /* Collation.swift */, - 566A210A1C58A54F00C5A218 /* Function.swift */, - 566A210B1C58A54F00C5A218 /* Operator.swift */, - 566A210C1C58A54F00C5A218 /* SQLQuery.swift */, - ); - path = SQLSupport; - sourceTree = ""; - }; - 566A210D1C58A54F00C5A218 /* Foundation */ = { - isa = PBXGroup; - children = ( - 566A210E1C58A54F00C5A218 /* DatabaseCoder.swift */, - 566A210F1C58A54F00C5A218 /* DatabaseDateComponents.swift */, - 566A21101C58A54F00C5A218 /* DatabaseValue+Foundation.swift */, - 566A21111C58A54F00C5A218 /* NSData.swift */, - 566A21121C58A54F00C5A218 /* NSDate.swift */, - 566A21131C58A54F00C5A218 /* NSNull.swift */, - 566A21141C58A54F00C5A218 /* NSNumber.swift */, - 566A21151C58A54F00C5A218 /* NSString.swift */, - 566A21161C58A54F00C5A218 /* NSURL.swift */, - 566A21171C58A54F00C5A218 /* Row+Foundation.swift */, - 566A21181C58A54F00C5A218 /* StatementArguments+Foundation.swift */, - ); - path = Foundation; - sourceTree = ""; - }; - 566A211D1C58A54F00C5A218 /* Migrations */ = { - isa = PBXGroup; - children = ( - 566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */, - 566A211F1C58A54F00C5A218 /* Migration.swift */, - ); - path = Migrations; - sourceTree = ""; - }; - 566A21221C58A54F00C5A218 /* Record */ = { - isa = PBXGroup; - children = ( - 566A21231C58A54F00C5A218 /* Record.swift */, - ); - path = Record; - sourceTree = ""; - }; - 566A21241C58A54F00C5A218 /* Swift */ = { - isa = PBXGroup; - children = ( - 566A21251C58A54F00C5A218 /* RawRepresentable.swift */, - 566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */, - ); - path = Swift; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -375,46 +385,52 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 566A21381C58A54F00C5A218 /* Operator.swift in Sources */, - 566A21411C58A54F00C5A218 /* NSString.swift in Sources */, - 566A21401C58A54F00C5A218 /* NSNumber.swift in Sources */, - 566A21351C58A54F00C5A218 /* FetchRequest.swift in Sources */, - 566A21271C58A54F00C5A218 /* Configuration.swift in Sources */, + 560A37FB1C91391800949E71 /* FetchRequest.swift in Sources */, + 560A37EC1C91391800949E71 /* CGFloat.swift in Sources */, + 560A38011C91391800949E71 /* Migration.swift in Sources */, + 560A37EB1C91391800949E71 /* StatementColumnConvertible.swift in Sources */, + 560A37EF1C91391800949E71 /* DatabaseValue+Foundation.swift in Sources */, + 560A37E01C91391800949E71 /* Configuration.swift in Sources */, + 560A37E91C91391800949E71 /* SerializedDatabase.swift in Sources */, 562FF9EF1BCE912C00759400 /* PersonEditionViewController.swift in Sources */, + 563363F01C95A41B000BE133 /* DatabaseStore.swift in Sources */, + 560A38051C91391800949E71 /* TableMapping.swift in Sources */, + 560A37E71C91391800949E71 /* DatabaseValueConvertible.swift in Sources */, + 560A37E31C91391800949E71 /* DatabasePool.swift in Sources */, 562FF9971BCE8FA400759400 /* PersonsViewController.swift in Sources */, - 566A214B1C58A54F00C5A218 /* RawRepresentable.swift in Sources */, + 560A37E51C91391800949E71 /* DatabaseSchemaCache.swift in Sources */, + 560A37E41C91391800949E71 /* DatabaseQueue.swift in Sources */, + 560A37F11C91391800949E71 /* NSDate.swift in Sources */, 562FF9F21BCE914E00759400 /* Person.swift in Sources */, - 566A212B1C58A54F00C5A218 /* DatabaseValue.swift in Sources */, + 560A37F01C91391800949E71 /* NSData.swift in Sources */, 562FF9951BCE8FA400759400 /* AppDelegate.swift in Sources */, - 566A213C1C58A54F00C5A218 /* DatabaseValue+Foundation.swift in Sources */, - 566A212D1C58A54F00C5A218 /* Persistable.swift in Sources */, - 566A21421C58A54F00C5A218 /* NSURL.swift in Sources */, - 566A21441C58A54F00C5A218 /* StatementArguments+Foundation.swift in Sources */, - 566A212E1C58A54F00C5A218 /* RowConvertible.swift in Sources */, - 566A21481C58A54F00C5A218 /* Migration.swift in Sources */, - 566A21291C58A54F00C5A218 /* DatabaseError.swift in Sources */, - 566A21281C58A54F00C5A218 /* Database.swift in Sources */, - 566A212C1C58A54F00C5A218 /* DatabaseValueConvertible.swift in Sources */, - 566A21331C58A54F00C5A218 /* Utils.swift in Sources */, - 566A214A1C58A54F00C5A218 /* Record.swift in Sources */, - 566A21321C58A54F00C5A218 /* Statement.swift in Sources */, - 566A21391C58A54F00C5A218 /* SQLQuery.swift in Sources */, - 566A21301C58A54F00C5A218 /* TableMapping.swift in Sources */, - 566A21431C58A54F00C5A218 /* Row+Foundation.swift in Sources */, - 566A214C1C58A54F00C5A218 /* StandardLibraryTypes.swift in Sources */, - 566A21341C58A54F00C5A218 /* CGFloat.swift in Sources */, - 566A21361C58A54F00C5A218 /* Collation.swift in Sources */, - 566A21311C58A54F00C5A218 /* Row.swift in Sources */, - 566A212A1C58A54F00C5A218 /* DatabaseQueue.swift in Sources */, - 566A213E1C58A54F00C5A218 /* NSDate.swift in Sources */, - 566A212F1C58A54F00C5A218 /* SQLiteStatementConvertible.swift in Sources */, + 560A37FC1C91391800949E71 /* SQLCollation.swift in Sources */, + 560A37F71C91391800949E71 /* StatementArguments+Foundation.swift in Sources */, + 560A37EE1C91391800949E71 /* DatabaseDateComponents.swift in Sources */, + 560A37ED1C91391800949E71 /* DatabaseCoder.swift in Sources */, + 560A37E61C91391800949E71 /* DatabaseValue.swift in Sources */, + 560A37F31C91391800949E71 /* NSNumber.swift in Sources */, + 560A37FF1C91391800949E71 /* SQLSelectQuery.swift in Sources */, + 560A37F41C91391800949E71 /* NSString.swift in Sources */, + 560A37E21C91391800949E71 /* DatabaseError.swift in Sources */, + 560A38041C91391800949E71 /* RowConvertible.swift in Sources */, + 560A37F91C91391800949E71 /* StandardLibrary.swift in Sources */, + 563363CA1C942CB4000BE133 /* DatabaseWriter.swift in Sources */, + 560A37FA1C91391800949E71 /* Utils.swift in Sources */, + 560A37F61C91391800949E71 /* Row+Foundation.swift in Sources */, + 560A37FD1C91391800949E71 /* SQLFunction.swift in Sources */, + 560A37FE1C91391800949E71 /* SQLOperator.swift in Sources */, + 560A37F21C91391800949E71 /* NSNull.swift in Sources */, + 560A37E11C91391800949E71 /* Database.swift in Sources */, + 560A37E81C91391800949E71 /* Row.swift in Sources */, + 560A38021C91391800949E71 /* Persistable.swift in Sources */, + 560A37F51C91391800949E71 /* NSURL.swift in Sources */, + 560A37F81C91391800949E71 /* RawRepresentable.swift in Sources */, + 560A38001C91391800949E71 /* DatabaseMigrator.swift in Sources */, 566A20F31C58A4B300C5A218 /* AppDatabase.swift in Sources */, - 566A213F1C58A54F00C5A218 /* NSNull.swift in Sources */, - 566A213A1C58A54F00C5A218 /* DatabaseCoder.swift in Sources */, - 566A213B1C58A54F00C5A218 /* DatabaseDateComponents.swift in Sources */, - 566A213D1C58A54F00C5A218 /* NSData.swift in Sources */, - 566A21371C58A54F00C5A218 /* Function.swift in Sources */, - 566A21471C58A54F00C5A218 /* DatabaseMigrator.swift in Sources */, + 560A37EA1C91391800949E71 /* Statement.swift in Sources */, + 560A38031C91391800949E71 /* Record.swift in Sources */, + 563363C81C942CAE000BE133 /* DatabaseReader.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index b81f911d2..797088e12 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,8 +1,8 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '0.45.0' + s.version = '0.51.2' s.license = { :type => 'MIT', :file => 'LICENSE' } - s.summary = 'Versatile SQLite toolkit for Swift.' + s.summary = 'A versatile SQLite toolkit for Swift, with WAL mode support.' s.homepage = 'https://github.com/groue/GRDB.swift' s.author = { 'Gwendal Roué' => 'gr@pierlis.com' } s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 07d4df835..c64fddacb 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -35,8 +35,8 @@ 5605F1721C672E4000235C62 /* RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* RawRepresentable.swift */; }; 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; - 5605F1871C69111300235C62 /* SelectStatementSourceTablesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* SelectStatementSourceTablesTests.swift */; }; - 5605F1881C69111300235C62 /* SelectStatementSourceTablesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* SelectStatementSourceTablesTests.swift */; }; + 5605F1871C69111300235C62 /* StatementInformationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementInformationTests.swift */; }; + 5605F1881C69111300235C62 /* StatementInformationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* StatementInformationTests.swift */; }; 5605F18D1C6B1A8700235C62 /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollation.swift */; }; 5605F18E1C6B1A8700235C62 /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollation.swift */; }; 5605F18F1C6B1A8700235C62 /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */; }; @@ -48,8 +48,13 @@ 5606AF911C0ED37000D20487 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; }; 5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; - 560B3FAC1C19E01000C58EC7 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */; }; - 560B3FAD1C19E01000C58EC7 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */; }; + 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; + 560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; + 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */; }; + 560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */; }; + 560A37AB1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; + 560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; + 560A37AF1C90A8D800949E71 /* DatabasePoolCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AE1C90A8D800949E71 /* DatabasePoolCrashTests.swift */; }; 560C97C71BFD0B8400BF8471 /* FunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */; }; 560C97C81BFD0B8400BF8471 /* FunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */; }; 560C97DA1C0E22D300BF8471 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86191BA988F2001F9168 /* FMDatabase.m */; }; @@ -86,6 +91,39 @@ 56300B791C53F592005A543B /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* FetchRequest.swift */; }; 56300B851C54DC95005A543B /* Record+FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+FetchRequestTests.swift */; }; 56300B861C54DC95005A543B /* Record+FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+FetchRequestTests.swift */; }; + 563363AF1C933FF8000BE133 /* DatabaseMutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* DatabaseMutablePersistableTests.swift */; }; + 563363B01C933FF8000BE133 /* DatabaseMutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* DatabaseMutablePersistableTests.swift */; }; + 563363B11C933FF8000BE133 /* DatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* DatabasePersistableTests.swift */; }; + 563363B21C933FF8000BE133 /* DatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* DatabasePersistableTests.swift */; }; + 563363B31C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AB1C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift */; }; + 563363B41C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AB1C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift */; }; + 563363B51C933FF8000BE133 /* DatabasePoolPersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AC1C933FF8000BE133 /* DatabasePoolPersistableTests.swift */; }; + 563363B61C933FF8000BE133 /* DatabasePoolPersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AC1C933FF8000BE133 /* DatabasePoolPersistableTests.swift */; }; + 563363B71C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AD1C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift */; }; + 563363B81C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AD1C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift */; }; + 563363B91C933FF8000BE133 /* DatabaseQueuePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AE1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift */; }; + 563363BA1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AE1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift */; }; + 563363BD1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; + 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; + 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; + 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; + 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; }; + 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; }; + 563363D01C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; + 563363D11C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; + 563363D51C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; }; + 563363D61C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; }; + 563363D81C95787F000BE133 /* DatabaseStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D71C95787F000BE133 /* DatabaseStore.swift */; }; + 563363D91C95787F000BE133 /* DatabaseStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D71C95787F000BE133 /* DatabaseStore.swift */; }; + 563363DC1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363DB1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift */; }; + 563363DD1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363DB1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift */; }; + 563363DF1C959295000BE133 /* DatabasePoolFileAttributesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363DE1C959295000BE133 /* DatabasePoolFileAttributesTests.swift */; }; + 563363E01C959295000BE133 /* DatabasePoolFileAttributesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363DE1C959295000BE133 /* DatabasePoolFileAttributesTests.swift */; }; + 563363F21C95F654000BE133 /* RealmSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 563363F11C95F654000BE133 /* RealmSwift.framework */; }; + 563363F41C95F6EB000BE133 /* Realm.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 563363F31C95F6EB000BE133 /* Realm.framework */; }; + 563363F61C96052E000BE133 /* Realm.framework in CopyFiles */ = {isa = PBXBuildFile; fileRef = 563363F31C95F6EB000BE133 /* Realm.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + 563363F71C96052E000BE133 /* RealmSwift.framework in CopyFiles */ = {isa = PBXBuildFile; fileRef = 563363F11C95F654000BE133 /* RealmSwift.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + 563363F91C960711000BE133 /* PerformanceRealmTests.realm in Resources */ = {isa = PBXBuildFile; fileRef = 563363F81C960711000BE133 /* PerformanceRealmTests.realm */; }; 563445051C4A7FD7003D3DC6 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; }; 563445061C4A7FD7003D3DC6 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; }; 564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; }; @@ -93,9 +131,6 @@ 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56553C121C3E906C00522B5C /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; }; 56553C131C3E906C00522B5C /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC3773F319C8CBB3004FCF85 /* GRDB.framework */; }; - 56553C1A1C3E91BC00522B5C /* CrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CB92EC1BA453E500DFD5FC /* CrashTests.swift */; }; - 5658420E1C1A1C820099FE88 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */; }; - 5658420F1C1A1C820099FE88 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */; }; 565B0FEF1BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; 565D5D711BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */; }; @@ -103,6 +138,23 @@ 565D5D741BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; 5683C2691B4D445E00296494 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5683C2681B4D445E00296494 /* libsqlite3.dylib */; }; + 569531091C9067DC00CF1A2B /* DatabaseQueueCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */; }; + 5695310A1C9067DC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */; }; + 5695310B1C9067DC00CF1A2B /* GRDBCrashTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */; }; + 5695310C1C9067DC00CF1A2B /* MigrationCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FE1C9067CC00CF1A2B /* MigrationCrashTests.swift */; }; + 5695310D1C9067DC00CF1A2B /* RecordCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FF1C9067CC00CF1A2B /* RecordCrashTests.swift */; }; + 5695310E1C9067DC00CF1A2B /* StatementColumnConvertibleCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531001C9067CC00CF1A2B /* StatementColumnConvertibleCrashTests.swift */; }; + 5695310F1C9067DC00CF1A2B /* StatementCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531011C9067CC00CF1A2B /* StatementCrashTests.swift */; }; + 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; + 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; + 569531261C9087B600CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */; }; + 569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */; }; + 569531291C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; }; + 5695312A1C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; }; + 569531341C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */; }; + 569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */; }; + 569531371C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; }; + 569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; }; 56A238371B9C74A90082EB20 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 56A238391B9C74A90082EB20 /* InMemoryDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* InMemoryDatabaseTests.swift */; }; @@ -176,8 +228,6 @@ 56A238B71B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */; }; 56A5E4091BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; }; 56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */; }; - 56AC8CCE1BA3F2AD009E4319 /* ConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AC8CCD1BA3F2AD009E4319 /* ConcurrencyTests.swift */; }; - 56AC8CCF1BA3F2AD009E4319 /* ConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AC8CCD1BA3F2AD009E4319 /* ConcurrencyTests.swift */; }; 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; 56B7F42F1BE14CD700E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; 56B7F4371BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4361BE4C11200E39BBF /* DatabaseCoderTests.swift */; }; @@ -208,6 +258,10 @@ 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56E8CE101BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift */; }; 56E8CE111BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift */; }; + 56EA86941C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; + 56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; + 56EA869E1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; + 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56EB0AB21BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* NSDataMemoryTests.swift */; }; 56EB0AB31BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* NSDataMemoryTests.swift */; }; 56EE573D1BB317B7007A6A95 /* SQLiteStatementConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* SQLiteStatementConversionTests.swift */; }; @@ -300,6 +354,20 @@ }; /* End PBXContainerItemProxy section */ +/* Begin PBXCopyFilesBuildPhase section */ + 563363F51C960513000BE133 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + 563363F61C96052E000BE133 /* Realm.framework in CopyFiles */, + 563363F71C96052E000BE133 /* RealmSwift.framework in CopyFiles */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + /* Begin PBXFileReference section */ 5605F1491C672E4000235C62 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = ""; }; 5605F14B1C672E4000235C62 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = ""; }; @@ -315,13 +383,16 @@ 5605F1551C672E4000235C62 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = ""; }; 5605F1571C672E4000235C62 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = ""; }; 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; - 5605F1861C69111300235C62 /* SelectStatementSourceTablesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SelectStatementSourceTablesTests.swift; sourceTree = ""; }; + 5605F1861C69111300235C62 /* StatementInformationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementInformationTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollation.swift; sourceTree = ""; }; 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunction.swift; sourceTree = ""; }; 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperator.swift; sourceTree = ""; }; 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; - 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = ""; }; + 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; + 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; + 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolConcurrencyTests.swift; sourceTree = ""; }; + 560A37AE1C90A8D800949E71 /* DatabasePoolCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolCrashTests.swift; sourceTree = ""; }; 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionTests.swift; sourceTree = ""; }; 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; @@ -336,14 +407,42 @@ 56300B6A1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+FetchRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+FetchRequestTests.swift"; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* DatabaseMutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMutablePersistableTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* DatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistableTests.swift; sourceTree = ""; }; + 563363AB1C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolMutablePersistableTests.swift; sourceTree = ""; }; + 563363AC1C933FF8000BE133 /* DatabasePoolPersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolPersistableTests.swift; sourceTree = ""; }; + 563363AD1C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueMutablePersistableTests.swift; sourceTree = ""; }; + 563363AE1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueuePersistableTests.swift; sourceTree = ""; }; + 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; + 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; + 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; + 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReleaseMemoryTests.swift; sourceTree = ""; }; + 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; + 563363D71C95787F000BE133 /* DatabaseStore.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseStore.swift; sourceTree = ""; }; + 563363DB1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueFileAttributesTests.swift; sourceTree = ""; }; + 563363DE1C959295000BE133 /* DatabasePoolFileAttributesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolFileAttributesTests.swift; sourceTree = ""; }; + 563363F11C95F654000BE133 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = Realm/RealmSwift.framework; sourceTree = ""; }; + 563363F31C95F6EB000BE133 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = Realm/Realm.framework; sourceTree = ""; }; + 563363F81C960711000BE133 /* PerformanceRealmTests.realm */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceRealmTests.realm; sourceTree = ""; }; 563445041C4A7FD7003D3DC6 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollationTests.swift; sourceTree = ""; }; 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.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; }; + 569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueCrashTests.swift; sourceTree = ""; }; + 569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleCrashTests.swift; sourceTree = ""; }; + 569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBCrashTestCase.swift; sourceTree = ""; }; + 569530FE1C9067CC00CF1A2B /* MigrationCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MigrationCrashTests.swift; sourceTree = ""; }; + 569530FF1C9067CC00CF1A2B /* RecordCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordCrashTests.swift; sourceTree = ""; }; + 569531001C9067CC00CF1A2B /* StatementColumnConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleCrashTests.swift; sourceTree = ""; }; + 569531011C9067CC00CF1A2B /* StatementCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementCrashTests.swift; sourceTree = ""; }; + 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = ""; }; + 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueSchemaCacheTests.swift; sourceTree = ""; }; + 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolSchemaCacheTests.swift; sourceTree = ""; }; + 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolCollationTests.swift; sourceTree = ""; }; + 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolFunctionTests.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; 56A238141B9C74A90082EB20 /* InMemoryDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InMemoryDatabaseTests.swift; sourceTree = ""; }; 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = ""; }; @@ -381,7 +480,6 @@ 56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTimestampTests.swift; sourceTree = ""; }; 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordWithColumnNameManglingTests.swift; sourceTree = ""; }; - 56AC8CCD1BA3F2AD009E4319 /* ConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConcurrencyTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4361BE4C11200E39BBF /* DatabaseCoderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoderTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; @@ -406,7 +504,6 @@ 56CA21B91BB3FCF7009A04C5 /* NSDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDataTests.swift; sourceTree = ""; }; 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = SQLite.xcodeproj; path = SQLite.swift/SQLite.xcodeproj; sourceTree = ""; }; 56CA22211BB41565009A04C5 /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceTests.swift; sourceTree = ""; }; - 56CB92EC1BA453E500DFD5FC /* CrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CrashTests.swift; sourceTree = ""; }; 56DBEC341C19A0020093A2EE /* CHANGELOG.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = CHANGELOG.md; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; 56DE7B231C412F7E00861EB8 /* InsertPositionalValuesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertPositionalValuesTests.swift; sourceTree = ""; }; @@ -423,6 +520,8 @@ 56E5D7F91B4D422D00430942 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; + 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* NSDataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDataMemoryTests.swift; sourceTree = ""; }; 56EE573C1BB317B7007A6A95 /* SQLiteStatementConversionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConversionTests.swift; sourceTree = ""; }; 56F0B98D1B6001C600A2F135 /* NSDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDateComponentsTests.swift; sourceTree = ""; }; @@ -448,6 +547,8 @@ 560C98121C0E22D300BF8471 /* SQLite.framework in Frameworks */, 560C98131C0E22D300BF8471 /* libsqlite3.tbd in Frameworks */, 560C98141C0E22D300BF8471 /* GRDB.framework in Frameworks */, + 563363F41C95F6EB000BE133 /* Realm.framework in Frameworks */, + 563363F21C95F654000BE133 /* RealmSwift.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -551,11 +652,27 @@ path = TransactionObserver; sourceTree = ""; }; + 560A37A91C90084600949E71 /* DatabasePool */ = { + isa = PBXGroup; + children = ( + 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */, + 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */, + 563363DE1C959295000BE133 /* DatabasePoolFileAttributesTests.swift */, + 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */, + 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */, + ); + path = DatabasePool; + sourceTree = ""; + }; 560B3FA41C19DFF800C58EC7 /* Persistable */ = { isa = PBXGroup; children = ( - 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */, - 5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */, + 563363A91C933FF8000BE133 /* DatabaseMutablePersistableTests.swift */, + 563363AA1C933FF8000BE133 /* DatabasePersistableTests.swift */, + 563363AB1C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift */, + 563363AC1C933FF8000BE133 /* DatabasePoolPersistableTests.swift */, + 563363AD1C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift */, + 563363AE1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift */, ); path = Persistable; sourceTree = ""; @@ -601,6 +718,15 @@ path = FetchRequest; sourceTree = ""; }; + 563363BB1C93FD32000BE133 /* DatabaseQueue */ = { + isa = PBXGroup; + children = ( + 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */, + 563363DB1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift */, + ); + path = DatabaseQueue; + sourceTree = ""; + }; 564A50BF1BFF4B6E00B3A3A2 /* Collation */ = { isa = PBXGroup; children = ( @@ -609,11 +735,30 @@ path = Collation; sourceTree = ""; }; + 569530FA1C9067CC00CF1A2B /* Crash */ = { + isa = PBXGroup; + children = ( + 560A37AE1C90A8D800949E71 /* DatabasePoolCrashTests.swift */, + 569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */, + 569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */, + 569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */, + 569530FE1C9067CC00CF1A2B /* MigrationCrashTests.swift */, + 569530FF1C9067CC00CF1A2B /* RecordCrashTests.swift */, + 569531001C9067CC00CF1A2B /* StatementColumnConvertibleCrashTests.swift */, + 569531011C9067CC00CF1A2B /* StatementCrashTests.swift */, + ); + path = Crash; + sourceTree = ""; + }; 569978D31B539038005EBEED /* Private */ = { isa = PBXGroup; children = ( + 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */, + 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */, + 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */, + 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */, 56EB0AB11BCD787300A3DC55 /* NSDataMemoryTests.swift */, - 5605F1861C69111300235C62 /* SelectStatementSourceTablesTests.swift */, + 5605F1861C69111300235C62 /* StatementInformationTests.swift */, ); path = Private; sourceTree = ""; @@ -621,7 +766,6 @@ 569978D41B539038005EBEED /* Public */ = { isa = PBXGroup; children = ( - 56CB92EC1BA453E500DFD5FC /* CrashTests.swift */, 56A238111B9C74A90082EB20 /* Core */, 56B7F4281BE149F600E39BBF /* CoreGraphics */, 56300B5C1C53C38F005A543B /* FetchRequest */, @@ -637,10 +781,12 @@ isa = PBXGroup; children = ( 564A50BF1BFF4B6E00B3A3A2 /* Collation */, - 56AC8CCC1BA3F267009E4319 /* Concurrency */, 56A238121B9C74A90082EB20 /* Database */, 56A238151B9C74A90082EB20 /* DatabaseError */, + 560A37A91C90084600949E71 /* DatabasePool */, + 563363BB1C93FD32000BE133 /* DatabaseQueue */, 560B3FA41C19DFF800C58EC7 /* Persistable */, + 56EA86921C91DFDA002BB4DF /* DatabaseReader */, 56A238171B9C74A90082EB20 /* DatabaseValue */, 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */, 560C97BF1BFD0B5B00BF8471 /* Function */, @@ -680,12 +826,12 @@ 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */ = { isa = PBXGroup; children = ( + 56A2381C1B9C74A90082EB20 /* RawRepresentableTests.swift */, 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */, 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */, 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */, 56A2381A1B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift */, 56CA21B91BB3FCF7009A04C5 /* NSDataTests.swift */, - 56A2381C1B9C74A90082EB20 /* RawRepresentableTests.swift */, ); path = DatabaseValueConvertible; sourceTree = ""; @@ -754,14 +900,20 @@ 56A238701B9C75030082EB20 /* Configuration.swift */, 56A238711B9C75030082EB20 /* Database.swift */, 56A238731B9C75030082EB20 /* DatabaseError.swift */, + 560A37A31C8F625000949E71 /* DatabasePool.swift */, 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, + 563363BF1C942C04000BE133 /* DatabaseReader.swift */, + 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, + 563363D71C95787F000BE133 /* DatabaseStore.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, + 563363C31C942C37000BE133 /* DatabaseWriter.swift */, 56A238761B9C75030082EB20 /* Row.swift */, + 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */, 56A238781B9C75030082EB20 /* Statement.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, - 563445041C4A7FD7003D3DC6 /* Utils.swift */, 5605F1471C672E4000235C62 /* Support */, + 563445041C4A7FD7003D3DC6 /* Utils.swift */, ); path = Core; sourceTree = ""; @@ -786,14 +938,6 @@ path = Record; sourceTree = ""; }; - 56AC8CCC1BA3F267009E4319 /* Concurrency */ = { - isa = PBXGroup; - children = ( - 56AC8CCD1BA3F2AD009E4319 /* ConcurrencyTests.swift */, - ); - path = Concurrency; - sourceTree = ""; - }; 56B7F4281BE149F600E39BBF /* CoreGraphics */ = { isa = PBXGroup; children = ( @@ -808,6 +952,7 @@ 56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */, 56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */, 56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */, + 563363F81C960711000BE133 /* PerformanceRealmTests.realm */, 56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */, 56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */, 56DE7B2B1C41311900861EB8 /* FetchRecordTests.swift */, @@ -816,6 +961,8 @@ 56BB86121BA9886D001F9168 /* InsertRecordTests.swift */, 56CA22211BB41565009A04C5 /* PerformanceTests.swift */, 56DE7B341C42B37E00861EB8 /* CoreData.framework */, + 563363F31C95F6EB000BE133 /* Realm.framework */, + 563363F11C95F654000BE133 /* RealmSwift.framework */, 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */, 56BB86171BA988F2001F9168 /* fmdb */, ); @@ -868,6 +1015,14 @@ path = GRDBOSX; sourceTree = ""; }; + 56EA86921C91DFDA002BB4DF /* DatabaseReader */ = { + isa = PBXGroup; + children = ( + 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + ); + path = DatabaseReader; + sourceTree = ""; + }; 56EE573B1BB317B7007A6A95 /* SQLiteStatementConvertible */ = { isa = PBXGroup; children = ( @@ -902,6 +1057,7 @@ isa = PBXGroup; children = ( 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, + 569530FA1C9067CC00CF1A2B /* Crash */, 56FC78631BBAEB6D00CA1285 /* Experimental */, 56BB86101BA9886D001F9168 /* Performance */, 569978D31B539038005EBEED /* Private */, @@ -1007,6 +1163,7 @@ 560C97D41C0E22D300BF8471 /* Sources */, 560C98111C0E22D300BF8471 /* Frameworks */, 560C98151C0E22D300BF8471 /* Resources */, + 563363F51C960513000BE133 /* CopyFiles */, ); buildRules = ( ); @@ -1199,6 +1356,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 563363F91C960711000BE133 /* PerformanceRealmTests.realm in Resources */, 560C98161C0E22D300BF8471 /* PerformanceTests.sqlite in Resources */, 56DE7B371C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite in Resources */, ); @@ -1266,8 +1424,15 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 5695310C1C9067DC00CF1A2B /* MigrationCrashTests.swift in Sources */, + 569531091C9067DC00CF1A2B /* DatabaseQueueCrashTests.swift in Sources */, + 5695310D1C9067DC00CF1A2B /* RecordCrashTests.swift in Sources */, + 5695310E1C9067DC00CF1A2B /* StatementColumnConvertibleCrashTests.swift in Sources */, + 5695310A1C9067DC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift in Sources */, + 5695310F1C9067DC00CF1A2B /* StatementCrashTests.swift in Sources */, + 5695310B1C9067DC00CF1A2B /* GRDBCrashTestCase.swift in Sources */, + 560A37AF1C90A8D800949E71 /* DatabasePoolCrashTests.swift in Sources */, 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */, - 56553C1A1C3E91BC00522B5C /* CrashTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1284,6 +1449,9 @@ 5605F1901C6B1A8700235C62 /* SQLFunction.swift in Sources */, 5605F1721C672E4000235C62 /* RawRepresentable.swift in Sources */, 563445061C4A7FD7003D3DC6 /* Utils.swift in Sources */, + 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, + 563363D91C95787F000BE133 /* DatabaseStore.swift in Sources */, + 560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5605F16A1C672E4000235C62 /* NSString.swift in Sources */, 5605F16E1C672E4000235C62 /* Row+Foundation.swift in Sources */, @@ -1295,11 +1463,14 @@ 5605F15C1C672E4000235C62 /* DatabaseCoder.swift in Sources */, 5605F16C1C672E4000235C62 /* NSURL.swift in Sources */, 56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */, + 560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5605F1941C6B1A8700235C62 /* SQLSelectQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, + 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, + 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */, 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, @@ -1320,8 +1491,8 @@ 56A238601B9C74A90082EB20 /* RecordDescriptionTests.swift in Sources */, 56300B861C54DC95005A543B /* Record+FetchRequestTests.swift in Sources */, 56A238561B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */, + 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56A238501B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */, - 56AC8CCF1BA3F2AD009E4319 /* ConcurrencyTests.swift in Sources */, 56A238461B9C74A90082EB20 /* DictionaryRowTests.swift in Sources */, 56B7F4381BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */, 564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */, @@ -1330,40 +1501,55 @@ 56A2384A1B9C74A90082EB20 /* SelectStatementTests.swift in Sources */, 56A2384C1B9C74A90082EB20 /* UpdateStatementTests.swift in Sources */, 56A2384E1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */, + 563363B61C933FF8000BE133 /* DatabasePoolPersistableTests.swift in Sources */, 56A238641B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift in Sources */, + 569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */, 56A2385A1B9C74A90082EB20 /* PrimaryKeySingleTests.swift in Sources */, 56A238661B9C74A90082EB20 /* RecordFetchTests.swift in Sources */, 56EE573E1BB317B7007A6A95 /* SQLiteStatementConversionTests.swift in Sources */, + 569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */, + 563363B81C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift in Sources */, 56A238481B9C74A90082EB20 /* DetachedRowTests.swift in Sources */, + 569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56A238541B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift in Sources */, 56FDECE31BB32DFD009AD709 /* MetalRowTests.swift in Sources */, + 563363B41C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift in Sources */, 56DE7B121C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */, 56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */, + 563363B01C933FF8000BE133 /* DatabaseMutablePersistableTests.swift in Sources */, 56300B621C53C42C005A543B /* RowConvertible+FetchRequestTests.swift in Sources */, + 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, + 563363E01C959295000BE133 /* DatabasePoolFileAttributesTests.swift in Sources */, 56EB0AB31BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */, 56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 56FC78691BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */, + 563363B21C933FF8000BE133 /* DatabasePersistableTests.swift in Sources */, 56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */, - 5658420F1C1A1C820099FE88 /* MutablePersistableTests.swift in Sources */, 56FC78671BBAEB8C00CA1285 /* MappingTests.swift in Sources */, 56A238441B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */, + 560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */, 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */, 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */, + 563363BA1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift in Sources */, 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, 56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */, + 56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */, 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */, 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56A238581B9C74A90082EB20 /* PrimaryKeyRowIDTests.swift in Sources */, 56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */, + 5695312A1C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */, 56A2385C1B9C74A90082EB20 /* PrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, + 563363D61C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, + 563363D11C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56A238521B9C74A90082EB20 /* MinimalPrimaryKeySingleTests.swift in Sources */, + 563363DD1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift in Sources */, 56CA21BB1BB3FCF7009A04C5 /* NSDataTests.swift in Sources */, 56A238B71B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 56300B6C1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift in Sources */, - 560B3FAD1C19E01000C58EC7 /* PersistableTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* NSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 56300B5F1C53C38F005A543B /* FetchRequestTests.swift in Sources */, @@ -1372,7 +1558,7 @@ 56A2383A1B9C74A90082EB20 /* InMemoryDatabaseTests.swift in Sources */, 56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */, 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */, - 5605F1881C69111300235C62 /* SelectStatementSourceTablesTests.swift in Sources */, + 5605F1881C69111300235C62 /* StatementInformationTests.swift in Sources */, 56E5D8181B4D435D00430942 /* GRDBTestCase.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1384,9 +1570,9 @@ 5614DEF81BAA1B43003163B3 /* DatabaseValueConversionTests.swift in Sources */, 56300B851C54DC95005A543B /* Record+FetchRequestTests.swift in Sources */, 56A2385F1B9C74A90082EB20 /* RecordDescriptionTests.swift in Sources */, + 563363BD1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56A238551B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */, 56A2384F1B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */, - 56AC8CCE1BA3F2AD009E4319 /* ConcurrencyTests.swift in Sources */, 56A238451B9C74A90082EB20 /* DictionaryRowTests.swift in Sources */, 56A238491B9C74A90082EB20 /* SelectStatementTests.swift in Sources */, 56B7F4371BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */, @@ -1394,31 +1580,46 @@ 564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */, 56A2384B1B9C74A90082EB20 /* UpdateStatementTests.swift in Sources */, 56A2384D1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */, + 563363B51C933FF8000BE133 /* DatabasePoolPersistableTests.swift in Sources */, 56A238631B9C74A90082EB20 /* RecordAwakeFromFetchTests.swift in Sources */, + 569531341C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */, 56A238591B9C74A90082EB20 /* PrimaryKeySingleTests.swift in Sources */, 56EE573D1BB317B7007A6A95 /* SQLiteStatementConversionTests.swift in Sources */, 56A238651B9C74A90082EB20 /* RecordFetchTests.swift in Sources */, + 569531371C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */, + 563363B71C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift in Sources */, 56A238471B9C74A90082EB20 /* DetachedRowTests.swift in Sources */, + 569531261C9087B600CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56FDECE21BB32DFD009AD709 /* MetalRowTests.swift in Sources */, 56A238531B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift in Sources */, + 563363DF1C959295000BE133 /* DatabasePoolFileAttributesTests.swift in Sources */, + 563363B31C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift in Sources */, 56DE7B111C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */, 56A238671B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */, + 563363AF1C933FF8000BE133 /* DatabaseMutablePersistableTests.swift in Sources */, 56300B611C53C42C005A543B /* RowConvertible+FetchRequestTests.swift in Sources */, + 56EA869E1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, 56A2385D1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 56A238431B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */, 56EB0AB21BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */, + 563363B11C933FF8000BE133 /* DatabasePersistableTests.swift in Sources */, 56FC78681BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */, - 5658420E1C1A1C820099FE88 /* MutablePersistableTests.swift in Sources */, 56FC78661BBAEB8C00CA1285 /* MappingTests.swift in Sources */, 56A238691B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, + 560A37AB1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */, 5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */, + 563363D01C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56A2383D1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */, + 563363B91C933FF8000BE133 /* DatabaseQueuePersistableTests.swift in Sources */, 565D5D711BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */, 56A238571B9C74A90082EB20 /* PrimaryKeyRowIDTests.swift in Sources */, + 56EA86941C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */, 56A238611B9C74A90082EB20 /* RecordEditedTests.swift in Sources */, 56A2385B1B9C74A90082EB20 /* PrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 565B0FEF1BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */, + 563363D51C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 56A2383F1B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 569531291C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */, 56E8CE0D1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56A2383B1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, 56E8CE101BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift in Sources */, @@ -1427,7 +1628,6 @@ 56A238B61B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */, 565D5D741BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 56300B6B1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift in Sources */, - 560B3FAC1C19E01000C58EC7 /* PersistableTests.swift in Sources */, 56F0B9911B6001C600A2F135 /* NSDateTests.swift in Sources */, 56A238371B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 56300B661C53C8A7005A543B /* FetchRequestTests.swift in Sources */, @@ -1436,8 +1636,9 @@ 56A238391B9C74A90082EB20 /* InMemoryDatabaseTests.swift in Sources */, 56A5E4091BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */, 56B7F42F1BE14CD700E39BBF /* CGFloatTests.swift in Sources */, - 5605F1871C69111300235C62 /* SelectStatementSourceTablesTests.swift in Sources */, + 5605F1871C69111300235C62 /* StatementInformationTests.swift in Sources */, 56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */, + 563363DC1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1454,6 +1655,9 @@ 5605F18F1C6B1A8700235C62 /* SQLFunction.swift in Sources */, 5605F1711C672E4000235C62 /* RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, + 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */, + 563363D81C95787F000BE133 /* DatabaseStore.swift in Sources */, + 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 5605F16D1C672E4000235C62 /* Row+Foundation.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, @@ -1465,11 +1669,14 @@ 5605F15B1C672E4000235C62 /* DatabaseCoder.swift in Sources */, 5605F16B1C672E4000235C62 /* NSURL.swift in Sources */, 560D924B1C672C4B00F4F92B /* TableMapping.swift in Sources */, + 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */, 5605F1931C6B1A8700235C62 /* SQLSelectQuery.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, + 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, + 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, @@ -1524,6 +1731,10 @@ buildSettings = { COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = dwarf; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Tests/Performance/Realm", + ); GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; @@ -1541,6 +1752,10 @@ COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Tests/Performance/Realm", + ); GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; diff --git a/GRDB.xcworkspace/contents.xcworkspacedata b/GRDB.xcworkspace/contents.xcworkspacedata index b3a1f576f..322c13a35 100644 --- a/GRDB.xcworkspace/contents.xcworkspacedata +++ b/GRDB.xcworkspace/contents.xcworkspacedata @@ -4,6 +4,12 @@ + + + + @@ -13,9 +19,6 @@ - - diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 54bf5f3ef..ce1983f51 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,6 +1,6 @@ import Foundation -/// Configure a DatabaseQueue +/// Configuration for a DatabaseQueue or DatabasePool. public struct Configuration { // MARK: - Misc options @@ -12,6 +12,21 @@ public struct Configuration { public var trace: TraceFunction? + // MARK: - File Attributes + + /// The file attributes that should be applied to the database files (see + /// `NSFileMnager.setAttributes(_,ofItemAtPath:)`). + /// + /// SQLite will create [temporary files](https://www.sqlite.org/tempfiles.html) + /// when it needs them. + /// + /// In WAL mode (see DatabasePool), SQLite will also eventually create + /// `-shm` and `-wal` files. + /// + /// GRDB will apply file attributes to all those files. + public var fileAttributes: [String: AnyObject]? = nil + + // MARK: - Transactions /// The default kind of transaction. @@ -21,18 +36,24 @@ public struct Configuration { // MARK: - Concurrency public var busyMode: BusyMode = .ImmediateError + + + // MARK: - Internal + var threadingMode: ThreadingMode = .Default + var SQLiteConnectionDidOpen: (() -> ())? + var SQLiteConnectionDidClose: (() -> ())? // MARK: - Factory Configuration /// Returns a factory configuration: /// - /// - foreignKeysEnabled: true /// - readonly: false + /// - fileAttributes: nil + /// - foreignKeysEnabled: true /// - trace: nil /// - defaultTransactionKind: .Immediate - /// - transactionObserver: nil /// - busyMode: .ImmediateError public init() { } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index c156e6662..529ea66f6 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -9,7 +9,8 @@ typealias SQLiteValue = COpaquePointer /// A Database connection. /// -/// You don't create a database directly. Instead, you use a DatabaseQueue: +/// You don't create a database directly. Instead, you use a DatabaseQueue, or +/// a DatabasePool: /// /// let dbQueue = DatabaseQueue(...) /// @@ -30,7 +31,7 @@ public final class Database { private var functions = Set() private var collations = Set() - private var schemaCache = DatabaseSchemaCache() + var schemaCache: DatabaseSchemaCacheType // internal so that it can be tested /// See setupTransactionHooks(), updateStatementDidFail(), updateStatementDidExecute() private var transactionState: TransactionState = .WaitForTransactionCompletion @@ -41,12 +42,13 @@ public final class Database { /// See setupBusyMode() private var busyCallback: BusyCallback? - /// The queue from which the database can be used. - /// See preconditionValidQueue(). - var databaseQueueID: DatabaseQueueID = nil + /// The value for the dispatch queue specific that holds the Database identity. + /// See preconditionValidQueue. + var dispatchQueueID: UnsafeMutablePointer = nil - init(path: String, configuration: Configuration) throws { + init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCacheType) throws { self.configuration = configuration + self.schemaCache = schemaCache // See https://www.sqlite.org/c3ref/open.html var sqliteConnection: SQLiteConnection = nil @@ -56,6 +58,8 @@ public final class Database { throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) } + configuration.SQLiteConnectionDidOpen?() + // Setup trace first, so that all queries, including initialization queries, are traced. setupTrace() @@ -63,19 +67,14 @@ public final class Database { setupBusyMode() } - // Initializes an in-memory database - convenience init(configuration: Configuration) { - try! self.init(path: ":memory:", configuration: configuration) - } - deinit { - if sqliteConnection != nil { - sqlite3_close(sqliteConnection) - } + configuration.SQLiteConnectionDidClose?() + sqlite3_close(sqliteConnection) } - func preconditionValidQueue() { - precondition(databaseQueueID == nil || databaseQueueID == dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") + func releaseMemory() { + sqlite3_db_release_memory(sqliteConnection) + schemaCache.clear() } private func setupForeignKeys() throws { @@ -120,7 +119,6 @@ public final class Database { } } - /// An SQLite threading mode. See https://www.sqlite.org/threadsafe.html. enum ThreadingMode { case Default @@ -183,6 +181,21 @@ public enum BusyMode { } +// ========================================================================= +// MARK: - SerializedDatabase Support + +extension Database { + + /// The key for the dispatch queue specific that holds the Database identity. + /// See preconditionValidQueue. + static let dispatchQueueIDKey = unsafeBitCast(Database.self, UnsafePointer.self) // some unique pointer + + func preconditionValidQueue() { + precondition(dispatchQueueID == nil || dispatchQueueID == dispatch_get_specific(Database.dispatchQueueIDKey), "Database was not used on the correct thread. If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") + } +} + + // ========================================================================= // MARK: - Statements @@ -190,7 +203,7 @@ extension Database { /// Returns a prepared statement that can be reused. /// - /// let statement = try db.selectStatement("SELECT * FROM persons WHERE age > ?") + /// let statement = try db.selectStatement("SELECT COUNT(*) FROM persons WHERE age > ?") /// let moreThanTwentyCount = Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])! /// @@ -204,12 +217,12 @@ extension Database { @warn_unused_result func cachedSelectStatement(sql: String) throws -> SelectStatement { - if let statement = schemaCache.selectStatement[sql] { + if let statement = schemaCache.selectStatement(sql: sql) { return statement } let statement = try selectStatement(sql) - schemaCache.selectStatement[sql] = statement + schemaCache.setSelectStatement(statement, forSQL: sql) return statement } @@ -231,12 +244,12 @@ extension Database { @warn_unused_result func cachedUpdateStatement(sql: String) throws -> UpdateStatement { - if let statement = schemaCache.updateStatement[sql] { + if let statement = schemaCache.updateStatement(sql: sql) { return statement } let statement = try updateStatement(sql) - schemaCache.updateStatement[sql] = statement + schemaCache.setUpdateStatement(statement, forSQL: sql) return statement } @@ -250,7 +263,7 @@ extension Database { /// "INSERT INTO persons (name) VALUES (?);" + /// "INSERT INTO persons (name) VALUES (?);" + /// "INSERT INTO persons (name) VALUES (?);", - /// arguments; ['Harry', 'Ron', 'Hermione']) + /// arguments; ['Arthur', 'Barbara', 'Craig']) /// /// This method may throw a DatabaseError. /// @@ -314,15 +327,15 @@ extension Database { // During the execution of sqlite3_prepare_v2, the observer listens to // authorization callbacks in order to observe schema changes. - let schemaChangeObserver = SchemaChangeObserver(self) - schemaChangeObserver.start() + let observer = StatementCompilationObserver(self) + observer.start() sqlCodeUnits.withUnsafeBufferPointer { codeUnits in let sqlStart = UnsafePointer(codeUnits.baseAddress) let sqlEnd = sqlStart + sqlCodeUnits.count var statementStart = sqlStart while statementStart < sqlEnd - 1 { - schemaChangeObserver.invalidatesDatabaseSchemaCache = false + observer.reset() var statementEnd: UnsafePointer = nil var sqliteStatement: SQLiteStatement = nil let code = sqlite3_prepare_v2(sqliteConnection, statementStart, -1, &sqliteStatement, &statementEnd) @@ -338,7 +351,7 @@ extension Database { } do { - let statement = UpdateStatement(database: self, sql: sql, sqliteStatement: sqliteStatement, invalidatesDatabaseSchemaCache: schemaChangeObserver.invalidatesDatabaseSchemaCache) + let statement = UpdateStatement(database: self, sql: sql, sqliteStatement: sqliteStatement, invalidatesDatabaseSchemaCache: observer.invalidatesDatabaseSchemaCache) try statement.execute(arguments: consumeArguments(statement)) } catch let statementError { error = statementError @@ -349,7 +362,7 @@ extension Database { } } - schemaChangeObserver.stop() + observer.stop() if let error = error { throw error @@ -507,7 +520,7 @@ extension Database { /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// db.addCollation(collation) - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard") public func addCollation(collation: DatabaseCollation) { collations.remove(collation) collations.insert(collation) @@ -548,7 +561,7 @@ public final class DatabaseCollation { /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// db.addCollation(collation) - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard") /// /// - parameters: /// - name: The function name. @@ -583,24 +596,17 @@ public func ==(lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { // ========================================================================= // MARK: - Database Schema -private struct DatabaseSchemaCache { - /// Table name -> Primary key - var primaryKey: [String: PrimaryKey] = [:] +protocol DatabaseSchemaCacheType { + mutating func clear() - // SQL -> Statement - var updateStatement: [String: UpdateStatement] = [:] - var selectStatement: [String: SelectStatement] = [:] + func primaryKey(tableName tableName: String) -> PrimaryKey? + mutating func setPrimaryKey(primaryKey: PrimaryKey, forTableName tableName: String) + + func updateStatement(sql sql: String) -> UpdateStatement? + mutating func setUpdateStatement(statement: UpdateStatement, forSQL sql: String) - mutating func clear() { - primaryKey = [:] - - // We do clear updateStatementCache and selectStatementCache despite - // the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html) - // because the automatic statement recompilation only happens a - // limited number of times. - updateStatement = [:] - selectStatement = [:] - } + func selectStatement(sql sql: String) -> SelectStatement? + mutating func setSelectStatement(statement: SelectStatement, forSQL sql: String) } extension Database { @@ -628,8 +634,10 @@ extension Database { /// Throws if table does not exist. /// /// This method is not thread-safe. + /// + /// - throws: A DatabaseError if table does not exist. func primaryKey(tableName: String) throws -> PrimaryKey { - if let primaryKey = schemaCache.primaryKey[tableName] { + if let primaryKey = schemaCache.primaryKey(tableName: tableName) { return primaryKey } @@ -705,7 +713,7 @@ extension Database { primaryKey = .Regular(pkColumnInfos.map { $0.name }) } - schemaCache.primaryKey[tableName] = primaryKey + schemaCache.setPrimaryKey(primaryKey, forTableName: tableName) return primaryKey } @@ -776,37 +784,15 @@ enum PrimaryKey { } } -// A class that uses sqlite3_set_authorizer to fetch the list of tables -// used by a select statement. -final class SourceTableObserver { - var sourceTables: Set = [] - let database: Database - - init(_ database: Database) { - self.database = database - } - - func start() { - let observerPointer = unsafeBitCast(self, UnsafeMutablePointer.self) - sqlite3_set_authorizer(database.sqliteConnection, { (observerPointer, actionCode, CString1, CString2, CString3, CString4) -> Int32 in - if actionCode == SQLITE_READ { - let observer = unsafeBitCast(observerPointer, SourceTableObserver.self) - observer.sourceTables.insert(String.fromCString(CString1)!) - } - return SQLITE_OK - }, observerPointer) - } - - func stop() { - sqlite3_set_authorizer(database.sqliteConnection, nil, nil) - } -} -// A class that uses sqlite3_set_authorizer to check if the database schema -// changes. -final class SchemaChangeObserver { - var invalidatesDatabaseSchemaCache: Bool = false +// ========================================================================= +// MARK: - StatementCompilationObserver + +// A class that uses sqlite3_set_authorizer to fetch information about a statement. +final class StatementCompilationObserver { let database: Database + var sourceTables: Set = [] + var invalidatesDatabaseSchemaCache = false init(_ database: Database) { self.database = database @@ -816,15 +802,12 @@ final class SchemaChangeObserver { let observerPointer = unsafeBitCast(self, UnsafeMutablePointer.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: - let observer = unsafeBitCast(observerPointer, SchemaChangeObserver.self) + case SQLITE_DROP_TABLE, SQLITE_DROP_TEMP_TABLE, SQLITE_DROP_TEMP_VIEW, SQLITE_DROP_VIEW, SQLITE_DETACH, SQLITE_ALTER_TABLE, SQLITE_DROP_VTABLE: + let observer = unsafeBitCast(observerPointer, StatementCompilationObserver.self) observer.invalidatesDatabaseSchemaCache = true + case SQLITE_READ: + let observer = unsafeBitCast(observerPointer, StatementCompilationObserver.self) + observer.sourceTables.insert(String.fromCString(CString1)!) default: break } @@ -835,6 +818,11 @@ final class SchemaChangeObserver { func stop() { sqlite3_set_authorizer(database.sqliteConnection, nil, nil) } + + func reset() { + sourceTables = [] + invalidatesDatabaseSchemaCache = false + } } @@ -864,7 +852,7 @@ extension Database { /// - block: A block that executes SQL statements and return either /// .Commit or .Rollback. /// - throws: The error thrown by the block. - public func inTransaction(kind: TransactionKind? = nil, block: () throws -> TransactionCompletion) throws { + public func inTransaction(kind: TransactionKind? = nil, @noescape _ block: () throws -> TransactionCompletion) throws { preconditionValidQueue() var completion: TransactionCompletion = .Rollback @@ -940,8 +928,8 @@ extension Database { /// Add a transaction observer, so that it gets notified of all /// database changes. /// - /// Database holds weak references to its transaction observers: they are - /// not retained, and stop getting notifications after they are deallocated. + /// The transaction observer is weakly referenced: it is not retained, and + /// stops getting notifications after it is deallocated. public func addTransactionObserver(transactionObserver: TransactionObserverType) { preconditionValidQueue() transactionObservers.append(WeakTransactionObserver(transactionObserver)) @@ -1163,3 +1151,70 @@ public struct DatabaseEvent { /// The rowID of the changed row. public let rowID: Int64 } + + +// ========================================================================= +// MARK: - DatabaseReader + +extension Database : DatabaseReader { + + // MARK: - Read From Database + + /// Evalutes the *block* argument in a deferred transaction, and returns + /// its result. + /// + /// This method is part of the DatabaseReader protocol adoption. + public func read(block: (db: Database) throws -> T) rethrows -> T { + // The isolation guarantees required by DatabaseReader.read require that + // we run the block in a transaction. + // + // Problem is, our inTransaction() method is declared as a `throws` + // function, not a `rethrows` function. + // + // We could update DatabaseReader and make the read() method `throws`. + // + // Instead we assume that read-only deferred transaction always + // succeeds: let's turn our throwing inTransaction() into a rethrowing + // function with this little trick: + func impl(@noescape block: (db: Database) throws -> T, onError: (ErrorType) throws -> ()) rethrows -> T { + var result: T? = nil + do { + try inTransaction(.Deferred) { + result = try block(db: self) + return .Commit + } + } catch { + try onError(error) + } + return result! + } + return try impl(block, onError: { throw $0 }) + } + + /// Evalutes the *block* argument and returns its result. + /// + /// This method is part of the DatabaseReader protocol adoption. + public func nonIsolatedRead(block: (db: Database) throws -> T) rethrows -> T { + // The isolation guarantees required by DatabaseReader.nonIsolatedRead + // are inherited from our wrapping DatabaseQueue or DatabasePool. + return try block(db: self) + } +} + + +// ========================================================================= +// MARK: - DatabaseWriter + +extension Database : DatabaseWriter { + + // MARK: - Writing in Database + + /// Evalutes the *block* argument and returns its result. + /// + /// This method is part of the DatabaseWriter protocol adoption. + public func write(block: (db: Database) throws -> T) rethrows -> T { + // The isolation guarantees required by DatabaseWriter.write are + // inherited from our wrapping DatabaseQueue or DatabasePool. + return try block(db: self) + } +} diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift new file mode 100644 index 000000000..5e4cc39f9 --- /dev/null +++ b/GRDB/Core/DatabasePool.swift @@ -0,0 +1,352 @@ +/// A DatabasePool grants concurrent accesses to an SQLite database. +public final class DatabasePool { + + // MARK: - Initializers + + /// Opens the SQLite database at path *path*. + /// + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// + /// Database connections get closed when the database pool gets deallocated. + /// + /// - parameters: + /// - path: The path to the database file. + /// - configuration: A configuration. + /// - maximumReaderCount: The maximum number of readers. Default is 5. + /// - throws: A DatabaseError whenever an SQLite error occurs. + public convenience init(path: String, configuration: Configuration = Configuration(), maximumReaderCount: Int = 5) throws { + precondition(maximumReaderCount > 1, "maximumReaderCount must be at least 1") + + // Database Store + let store = try DatabaseStore(path: path, attributes: configuration.fileAttributes) + + // Shared database schema cache + let databaseSchemaCache = SharedDatabaseSchemaCache() + + // Writer + let writer = try SerializedDatabase( + path: path, + configuration: configuration, + schemaCache: databaseSchemaCache) + + // Activate WAL Mode unless readonly + if !configuration.readonly { + let mode = writer.inDatabase { db in + String.fetchOne(db, "PRAGMA journal_mode=WAL") + } + guard mode == "wal" else { + throw DatabaseError(message: "could not activate WAL Mode at path: \(path)") + } + } + + self.init(path: path, configuration: configuration, maximumReaderCount: maximumReaderCount, databaseSchemaCache: databaseSchemaCache, writer: writer, store: store) + } + + + // MARK: - WAL Management + + /// Runs a WAL checkpoint + /// + /// See https://www.sqlite.org/wal.html and + /// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html) for + /// more information. + /// + /// - parameter kind: The checkpoint mode (default passive) + public func checkpoint(kind: CheckpointMode = .Passive) throws { + try writer.inDatabase { db in + // TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and + // check whether we need a busy handler on writer and/or readers + // when kind is not .Passive. + let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil) + guard code == SQLITE_OK else { + throw DatabaseError(code: code, message: db.lastErrorMessage, sql: nil) + } + } + } + + + // MARK: - Memory management + + /// Free as much memory as possible. + /// + /// This method blocks the current thread until all database accesses are completed. + public func releaseMemory() { + // TODO: test that this method blocks the current thread until all database accesses are completed. + writer.inDatabase { db in + db.releaseMemory() + } + + readerPool.forEach { reader in + reader.inDatabase { db in + db.releaseMemory() + } + } + + readerPool.clear() + } + + + // MARK: - Not public + + let store: DatabaseStore // Not private for tests that require syncing with the store + private let writer: SerializedDatabase + private let readerPool: Pool + + private var functions = Set() + private var collations = Set() + + private init(path: String, configuration: Configuration, maximumReaderCount: Int, databaseSchemaCache: DatabaseSchemaCacheType, writer: SerializedDatabase, store: DatabaseStore) { + self.store = store + self.writer = writer + self.readerPool = Pool(maximumCount: maximumReaderCount) + + var readerConfig = configuration + readerConfig.readonly = true + readerConfig.defaultTransactionKind = .Deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections. + + readerPool.makeElement = { [unowned self] in + let serializedDatabase = try! SerializedDatabase( + path: path, + configuration: readerConfig, + schemaCache: databaseSchemaCache) + + serializedDatabase.inDatabase { db in + for function in self.functions { + db.addFunction(function) + } + for collation in self.collations { + db.addCollation(collation) + } + } + + return serializedDatabase + } + } +} + +/// The available [checkpoint modes](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html). +public enum CheckpointMode: Int32 { + case Passive = 0 // SQLITE_CHECKPOINT_PASSIVE + case Full = 1 // SQLITE_CHECKPOINT_FULL + case Restart = 2 // SQLITE_CHECKPOINT_RESTART + case Truncate = 3 // SQLITE_CHECKPOINT_TRUNCATE +} + + +// ========================================================================= +// MARK: - DatabaseReader + +extension DatabasePool : DatabaseReader { + + // MARK: - Read From Database + + /// Synchronously executes a read-only block in a protected dispatch queue, + /// and returns its result. The block is wrapped in a transaction. + /// + /// let persons = dbPool.read { db in + /// Person.fetchAll(...) + /// } + /// + /// The block is completely isolated. Eventual concurrent database updates + /// are *not visible* inside the block: + /// + /// dbPool.read { db in + /// // Those two values are guaranteed to be equal, even if the + /// // `wines` table is modified between the two requests: + /// let count1 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count2 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// } + /// + /// dbPool.read { db in + /// // Now this value may be different: + /// let count = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + public func read(block: (db: Database) throws -> T) rethrows -> T { + // The block isolation comes from the DEFERRED transaction. + // See DatabasePoolTests.testReadMethodIsolationOfBlock(). + return try readerPool.get { reader in + try reader.inDatabase { db in + var result: T? = nil + try db.inTransaction(.Deferred) { + result = try block(db: db) + return .Commit + } + return result! + } + } + } + + /// Synchronously executes a read-only block in a protected dispatch queue, + /// and returns its result. + /// + /// let persons = dbPool.nonIsolatedRead { db in + /// Person.fetchAll(...) + /// } + /// + /// The block is not isolated from eventual concurrent database updates: + /// + /// dbPool.nonIsolatedRead { db in + /// // Those two values may be different because some other thread + /// // may have inserted or deleted a wine between the two requests: + /// let count1 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count2 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + public func nonIsolatedRead(block: (db: Database) throws -> T) rethrows -> T { + return try readerPool.get { reader in + try reader.inDatabase { db in + try block(db: db) + } + } + } + + + // MARK: - Functions + + /// Add or redefine an SQL function. + /// + /// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in + /// let dbv = databaseValues.first! + /// guard let int = dbv.value() as Int? else { + /// return nil + /// } + /// return int + 1 + /// } + /// dbPool.addFunction(fn) + /// dbPool.read { db in + /// Int.fetchOne(db, "SELECT succ(1)") // 2 + /// } + public func addFunction(function: DatabaseFunction) { + functions.remove(function) + functions.insert(function) + + writer.inDatabase { db in + db.addFunction(function) + } + + readerPool.forEach { reader in + reader.inDatabase { db in + db.addFunction(function) + } + } + } + + /// Remove an SQL function. + public func removeFunction(function: DatabaseFunction) { + functions.remove(function) + + writer.inDatabase { db in + db.removeFunction(function) + } + + readerPool.forEach { reader in + reader.inDatabase { db in + db.removeFunction(function) + } + } + } + + + // MARK: - Collations + + /// Add or redefine a collation. + /// + /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in + /// return (string1 as NSString).localizedStandardCompare(string2) + /// } + /// dbPool.addCollation(collation) + /// dbPool.write { db in + /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// } + public func addCollation(collation: DatabaseCollation) { + collations.remove(collation) + collations.insert(collation) + + writer.inDatabase { db in + db.addCollation(collation) + } + + readerPool.forEach { reader in + reader.inDatabase { db in + db.addCollation(collation) + } + } + } + + /// Remove a collation. + public func removeCollation(collation: DatabaseCollation) { + collations.remove(collation) + + writer.inDatabase { db in + db.removeCollation(collation) + } + + readerPool.forEach { reader in + reader.inDatabase { db in + db.removeCollation(collation) + } + } + } +} + + +// ========================================================================= +// MARK: - DatabaseWriter + +extension DatabasePool : DatabaseWriter { + + // MARK: - Writing in Database + + /// Synchronously executes an update block in a protected dispatch queue, + /// and returns its result. + /// + /// dbPool.write { db in + /// db.execute(...) + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + public func write(block: (db: Database) throws -> T) rethrows -> T { + return try writer.inDatabase(block) + } + + /// Synchronously executes a block in a protected dispatch queue, wrapped + /// inside a transaction. + /// + /// If the block throws an error, the transaction is rollbacked and the + /// error is rethrown. + /// + /// try dbPool.writeInTransaction { db in + /// db.execute(...) + /// return .Commit + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameters: + /// - kind: The transaction type (default nil). If nil, the transaction + /// type is configuration.defaultTransactionKind, which itself + /// defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html + /// for more information. + /// - block: A block that executes SQL statements and return either + /// .Commit or .Rollback. + /// - throws: The error thrown by the block. + public func writeInTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) rethrows { + try writer.inDatabase { db in + try db.inTransaction(kind) { + try block(db: db) + } + } + } +} diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 839e04705..b06693e78 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -1,13 +1,13 @@ import Foundation -/// A Database Queue serializes access to an SQLite database. +/// A DatabaseQueue serializes access to an SQLite database. public final class DatabaseQueue { // MARK: - Configuration /// The database configuration public var configuration: Configuration { - return database.configuration + return serializedDatabase.configuration } @@ -23,24 +23,17 @@ public final class DatabaseQueue { /// - path: The path to the database file. /// - configuration: A configuration. /// - throws: A DatabaseError whenever an SQLite error occurs. - public convenience init(path: String, var configuration: Configuration = Configuration()) throws { - // IMPLEMENTATION NOTE - // - // According to https://www.sqlite.org/threadsafe.html: - // - // > Multi-thread. In this mode, SQLite can be safely used by multiple - // > threads provided that no single database connection is used - // > simultaneously in two or more threads. - // > - // > Serialized. In serialized mode, SQLite can be safely used by - // > multiple threads with no restriction. - // > - // > The default mode is serialized. - // - // Since our database connection is only used via our serial dispatch - // queue, there is no purpose using the default serialized mode. - configuration.threadingMode = .MultiThread - try self.init(database: Database(path: path, configuration: configuration)) + public convenience init(path: String, configuration: Configuration = Configuration()) throws { + // Database Store + let store = try DatabaseStore(path: path, attributes: configuration.fileAttributes) + + // Database + let serializedDatabase = try SerializedDatabase( + path: path, + configuration: configuration, + schemaCache: DatabaseSchemaCache()) + + self.init(serializedDatabase: serializedDatabase, store: store) } /// Opens an in-memory SQLite database. @@ -50,35 +43,23 @@ public final class DatabaseQueue { /// Database memory is released when the database queue gets deallocated. /// /// - parameter configuration: A configuration. - public convenience init(var configuration: Configuration = Configuration()) { - configuration.threadingMode = .MultiThread // See IMPLEMENTATION NOTE in init(_:configuration:) - self.init(database: Database(configuration: configuration)) + public convenience init(configuration: Configuration = Configuration()) { + let serializedDatabase = try! SerializedDatabase( + path: ":memory:", + configuration: configuration, + schemaCache: DatabaseSchemaCache()) + + self.init(serializedDatabase: serializedDatabase, store: nil) } // MARK: - Database access - /// Synchronously executes a block in the database queue. - /// - /// dbQueue.inDatabase { db in - /// db.fetch(...) - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block. - public func inDatabase(block: (db: Database) throws -> Void) rethrows { - try inQueue { - try block(db: self.database) - } - } - - /// Synchronously executes a block in the database queue, and returns + /// Synchronously executes a block a protected dispatch queue, and returns /// its result. /// - /// let rows = dbQueue.inDatabase { db in - /// db.fetch(...) + /// let persons = dbQueue.inDatabase { db in + /// Person.fetchAll(...) /// } /// /// This method is *not* reentrant. @@ -86,13 +67,11 @@ public final class DatabaseQueue { /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func inDatabase(block: (db: Database) throws -> T) rethrows -> T { - return try inQueue { - try block(db: self.database) - } + return try serializedDatabase.inDatabase(block) } - /// Synchronously executes a block in the database queue, wrapped inside a - /// transaction. + /// Synchronously executes a block in a protected dispatch queue, wrapped + /// inside a transaction. /// /// If the block throws an error, the transaction is rollbacked and the /// error is rethrown. @@ -112,96 +91,146 @@ public final class DatabaseQueue { /// - block: A block that executes SQL statements and return either /// .Commit or .Rollback. /// - throws: The error thrown by the block. - public func inTransaction(kind: TransactionKind? = nil, block: (db: Database) throws -> TransactionCompletion) throws { - try inQueue { - try self.database.inTransaction(kind) { - try block(db: self.database) + public func inTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) throws { + try serializedDatabase.inDatabase { db in + try db.inTransaction(kind) { + try block(db: db) } } } + // MARK: - Memory management + + /// Free as much memory as possible. + /// + /// This method blocks the current thread until all database accesses are completed. + public func releaseMemory() { + serializedDatabase.inDatabase { db in + db.releaseMemory() + } + } + + // MARK: - Not public - /// The Database - private var database: Database + private let store: DatabaseStore? + + // https://www.sqlite.org/isolation.html + // + // > Within a single database connection X, a SELECT statement always + // > sees all changes to the database that are completed prior to the + // > start of the SELECT statement, whether committed or uncommitted. + // > And the SELECT statement obviously does not see any changes that + // > occur after the SELECT statement completes. But what about changes + // > that occur while the SELECT statement is running? What if a SELECT + // > statement is started and the sqlite3_step() interface steps through + // > roughly half of its output, then some UPDATE statements are run by + // > the application that modify the table that the SELECT statement is + // > reading, then more calls to sqlite3_step() are made to finish out + // > the SELECT statement? Will the later steps of the SELECT statement + // > see the changes made by the UPDATE or not? The answer is that this + // > behavior is undefined. + // + // This is why we use a serialized database: + private var serializedDatabase: SerializedDatabase - /// The dispatch queue - private let queue: dispatch_queue_t - - /// The key for the dispatch queue specific that holds the DatabaseQueue - /// identity. See databaseQueueID. - static let databaseQueueIDKey = unsafeBitCast(DatabaseQueue.self, UnsafePointer.self) // some unique pointer - - /// The value for the dispatch queue specific that holds the DatabaseQueue - /// identity. - /// - /// It helps: - /// - warning the user when he wraps calls to inDatabase() or - /// inTransaction(), which would create a deadlock - /// - warning the user the he uses a statement outside of the database - /// queue. - private lazy var databaseQueueID: DatabaseQueueID = { - unsafeBitCast(self, DatabaseQueueID.self) // pointer to self - }() - - init(database: Database) { - // IMPLEMENTATION NOTE - // - // https://www.sqlite.org/isolation.html - // - // > Within a single database connection X, a SELECT statement always - // > sees all changes to the database that are completed prior to the - // > start of the SELECT statement, whether committed or uncommitted. - // > And the SELECT statement obviously does not see any changes that - // > occur after the SELECT statement completes. But what about changes - // > that occur while the SELECT statement is running? What if a SELECT - // > statement is started and the sqlite3_step() interface steps through - // > roughly half of its output, then some UPDATE statements are run by - // > the application that modify the table that the SELECT statement is - // > reading, then more calls to sqlite3_step() are made to finish out - // > the SELECT statement? Will the later steps of the SELECT statement - // > see the changes made by the UPDATE or not? The answer is that this - // > behavior is undefined. - // - // This is why we use a serial queue: to avoid UPDATE to fuck up SELECT. - self.database = database - queue = dispatch_queue_create("com.github.groue.GRDB", nil) - dispatch_queue_set_specific(queue, DatabaseQueue.databaseQueueIDKey, databaseQueueID, nil) - database.databaseQueueID = databaseQueueID - } - - private func inQueue(block: () throws -> T) rethrows -> T { - // IMPLEMENTATION NOTE - // - // DatabaseQueue.inDatabase() and DatabaseQueue.inTransaction() are not - // reentrant. - // - // Avoiding dispatch_sync and calling block() right away if the specific - // is currently self.databaseQueueID looks like a promising solution: - // - // dbQueue.inDatabase { db in - // dbQueue.inDatabase { db in - // // Look, ma! I'm reentrant! - // } - // } - // - // However it does not survive this code, which deadlocks: - // - // let queue = dispatch_queue_create("...", nil) - // dbQueue.inDatabase { db in - // dispatch_sync(queue) { - // dbQueue.inDatabase { db in - // // Never run - // } - // } - // } - // - // I try not to ship half-baked solutions, so until a complete solution - // is found to this problem, I prefer totally disabling reentrancy. - precondition(databaseQueueID != dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.") - return try dispatchSync(queue, block: block) + init(serializedDatabase: SerializedDatabase, store: DatabaseStore?) { + self.store = store + self.serializedDatabase = serializedDatabase } } -typealias DatabaseQueueID = UnsafeMutablePointer + +// ========================================================================= +// MARK: - DatabaseReader + +extension DatabaseQueue : DatabaseReader { + + + // MARK: - Read From Database + + /// Alias for inDatabase + /// + /// This method is part of the DatabaseReader protocol adoption. + public func read(block: (db: Database) throws -> T) rethrows -> T { + return try inDatabase(block) + } + + /// Alias for inDatabase + /// + /// This method is part of the DatabaseReader protocol adoption. + public func nonIsolatedRead(block: (db: Database) throws -> T) rethrows -> T { + return try inDatabase(block) + } + + + // MARK: - Functions + + /// Add or redefine an SQL function. + /// + /// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in + /// let dbv = databaseValues.first! + /// guard let int = dbv.value() as Int? else { + /// return nil + /// } + /// return int + 1 + /// } + /// dbQueue.addFunction(fn) + /// dbQueue.inDatabase { db in + /// Int.fetchOne(db, "SELECT succ(1)") // 2 + /// } + public func addFunction(function: DatabaseFunction) { + inDatabase { db in + db.addFunction(function) + } + } + + /// Remove an SQL function. + public func removeFunction(function: DatabaseFunction) { + inDatabase { db in + db.removeFunction(function) + } + } + + + // MARK: - Collations + + /// Add or redefine a collation. + /// + /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in + /// return (string1 as NSString).localizedStandardCompare(string2) + /// } + /// dbQueue.addCollation(collation) + /// try dbQueue.inDatabase { db in + /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// } + public func addCollation(collation: DatabaseCollation) { + inDatabase { db in + db.addCollation(collation) + } + } + + /// Remove a collation. + public func removeCollation(collation: DatabaseCollation) { + inDatabase { db in + db.removeCollation(collation) + } + } +} + + +// ========================================================================= +// MARK: - DatabaseWriter + +extension DatabaseQueue : DatabaseWriter { + + // MARK: - Writing in Database + + /// Alias for inDatabase + /// + /// This method is part of the DatabaseWriter protocol adoption. + public func write(block: (db: Database) throws -> T) rethrows -> T { + return try inDatabase(block) + } +} diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift new file mode 100644 index 000000000..e74227bad --- /dev/null +++ b/GRDB/Core/DatabaseReader.swift @@ -0,0 +1,105 @@ +/// The protocol for all types that can fetch values from a database. +/// +/// It is adopted by DatabaseQueue, DatabasePool, and Database. +/// +/// You typically provide a DatabaseReader to fetching methods: +/// +/// let persons = Person.fetchAll(dbQueue) +/// let persons = Person.fetchAll(dbPool) +/// dbQueue.inDatabase { db in +/// let persons = Person.fetchAll(db) +/// } +/// +/// The protocol comes with isolation guarantees that describe the behavior of +/// adopting types in a multithreaded application. +/// +/// Types that adopt the protocol can provide stronger guarantees in practice. +/// For example, DatabaseQueue provides a stronger isolation level +/// than DatabasePool. +/// +/// **Warning**: Isolation guarantees stand as long as there is no external +/// connection to the database. Should you have to cope with external +/// connections, protect yourself with transactions, and be ready to setup a +/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). +public protocol DatabaseReader : class { + + // MARK: - Read From Database + + /// Synchronously executes a read-only block that takes a database + /// connection, and returns its result. + /// + /// The *block* argument is completely isolated. Eventual concurrent + /// database updates are *not visible* inside the block: + /// + /// reader.read { db in + /// // Those two values are guaranteed to be equal, even if the + /// // `wines` table is modified between the two requests: + /// let count1 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count2 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// } + /// + /// reader.read { db in + /// // Now this value may be different: + /// let count = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// } + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + func read(block: (db: Database) throws -> T) rethrows -> T + + /// Synchronously executes a read-only block that takes a database + /// connection, and returns its result. + /// + /// Individual statements executed in the *block* argument are executed + /// in isolation from eventual concurrent updates: + /// + /// reader.nonIsolatedRead { db in + /// // no external update can mess with this iteration: + /// for row in Row.fetch(db, ...) { ... } + /// } + /// + /// However, there is no guarantee that consecutive statements have the + /// same results: + /// + /// reader.nonIsolatedRead { db in + /// // Those two ints may be different: + /// let sql = "SELECT ..." + /// let int1 = Int.fetchOne(db, sql) + /// let int2 = Int.fetchOne(db, sql) + /// } + func nonIsolatedRead(block: (db: Database) throws -> T) rethrows -> T + + + // MARK: - Functions + + /// Add or redefine an SQL function. + /// + /// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in + /// let dbv = databaseValues.first! + /// guard let int = dbv.value() as Int? else { + /// return nil + /// } + /// return int + 1 + /// } + /// reader.addFunction(fn) + /// Int.fetchOne(reader, "SELECT succ(1)")! // 2 + func addFunction(function: DatabaseFunction) + + /// Remove an SQL function. + func removeFunction(function: DatabaseFunction) + + + // MARK: - Collations + + /// Add or redefine a collation. + /// + /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in + /// return (string1 as NSString).localizedStandardCompare(string2) + /// } + /// reader.addCollation(collation) + /// try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard") + func addCollation(collation: DatabaseCollation) + + /// Remove a collation. + func removeCollation(collation: DatabaseCollation) +} diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift new file mode 100644 index 000000000..0b7b26fe1 --- /dev/null +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -0,0 +1,74 @@ +/// An thread-unsafe database schema cache +class DatabaseSchemaCache: DatabaseSchemaCacheType { + private var primaryKeys: [String: PrimaryKey] = [:] + private var updateStatements: [String: UpdateStatement] = [:] + private var selectStatements: [String: SelectStatement] = [:] + + func clear() { + primaryKeys = [:] + + // We do clear updateStatementCache and selectStatementCache despite + // the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html) + // because the automatic statement recompilation only happens a + // limited number of times. + updateStatements = [:] + selectStatements = [:] + } + + func primaryKey(tableName tableName: String) -> PrimaryKey? { + return primaryKeys[tableName] + } + + func setPrimaryKey(primaryKey: PrimaryKey, forTableName tableName: String) { + primaryKeys[tableName] = primaryKey + } + + func updateStatement(sql sql: String) -> UpdateStatement? { + return updateStatements[sql] + } + + func setUpdateStatement(statement: UpdateStatement, forSQL sql: String) { + updateStatements[sql] = statement + } + + func selectStatement(sql sql: String) -> SelectStatement? { + return selectStatements[sql] + } + + func setSelectStatement(statement: SelectStatement, forSQL sql: String) { + selectStatements[sql] = statement + } +} + +/// A thread-safe database schema cache +struct SharedDatabaseSchemaCache: DatabaseSchemaCacheType { + private let cache = ReadWriteBox(DatabaseSchemaCache()) + + mutating func clear() { + cache.write { $0.clear() } + } + + func primaryKey(tableName tableName: String) -> PrimaryKey? { + return cache.read { $0.primaryKey(tableName: tableName) } + } + + mutating func setPrimaryKey(primaryKey: PrimaryKey, forTableName tableName: String) { + cache.write { $0.setPrimaryKey(primaryKey, forTableName: tableName) } + } + + func updateStatement(sql sql: String) -> UpdateStatement? { + return cache.read { $0.updateStatement(sql: sql) } + } + + mutating func setUpdateStatement(statement: UpdateStatement, forSQL sql: String) { + cache.write { $0.setUpdateStatement(statement, forSQL: sql) } + } + + func selectStatement(sql sql: String) -> SelectStatement? { + return cache.read { $0.selectStatement(sql: sql) } + } + + mutating func setSelectStatement(statement: SelectStatement, forSQL sql: String) { + cache.write { $0.setSelectStatement(statement, forSQL: sql) } + } +} diff --git a/GRDB/Core/DatabaseStore.swift b/GRDB/Core/DatabaseStore.swift new file mode 100644 index 000000000..502c874a9 --- /dev/null +++ b/GRDB/Core/DatabaseStore.swift @@ -0,0 +1,89 @@ +import Foundation + +/// DatabaseStore is responsible for applying Configuration.fileAttributes to +/// all database files (db.sqlite, db.sqlite-wal, db.sqlite-shm, +/// db.sqlite-journal, etc.) +class DatabaseStore { + private let source: dispatch_source_t? + private let queue: dispatch_queue_t? + + convenience init(path: String, attributes: [String: AnyObject]?) throws { + guard let attributes = attributes else { + self.init() + return + } + + let databaseFileName = (path as NSString).lastPathComponent + let directoryPath = (path as NSString).stringByDeletingLastPathComponent + + // We use a dispatch_source to monitor the contents of the database file + // parent directory, and apply file attributes. + // + // This require a file descriptor on the directory. + let directoryDescriptor = open(directoryPath, O_EVTONLY) + guard directoryDescriptor != -1 else { + // Let NSFileManager throw a nice NSError + try NSFileManager.defaultManager().contentsOfDirectoryAtPath(directoryPath) + // Come on, NSFileManager... OK just throw something that is somewhat relevant + throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, userInfo: nil) + } + + // Call the non-throwing initializer + self.init(directoryPath: directoryPath, databaseFileName: databaseFileName, directoryDescriptor: directoryDescriptor, attributes: attributes) + } + + private init() { + self.queue = nil + self.source = nil + } + + private init(directoryPath: String, databaseFileName: String, directoryDescriptor: CInt, attributes: [String: AnyObject]) { + let queue = dispatch_queue_create("com.groue.GRDB.DatabaseStore", nil) + let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(directoryDescriptor), DISPATCH_VNODE_WRITE, queue) + + // Configure dispatch source + dispatch_source_set_event_handler(source) { + // Directory has been modified: apply file attributes on unprocessed files + DatabaseStore.setFileAttributes( + directoryPath: directoryPath, + databaseFileName: databaseFileName, + attributes: attributes) + } + dispatch_source_set_cancel_handler(source) { + close(directoryDescriptor) + } + + self.queue = queue + self.source = source + + // Apply file attributes on existing files + DatabaseStore.setFileAttributes( + directoryPath: directoryPath, + databaseFileName: databaseFileName, + attributes: attributes) + + // Wait for directory modifications + dispatch_resume(source) + } + + deinit { + if let source = source { + dispatch_source_cancel(source) + } + } + + private static func setFileAttributes(directoryPath directoryPath: String, databaseFileName: String, attributes: [String: AnyObject]) { + let fm = NSFileManager.defaultManager() + let fileNames = try! fm.contentsOfDirectoryAtPath(directoryPath).filter({ $0.hasPrefix(databaseFileName) }) + for fileName in fileNames { + do { + try fm.setAttributes(attributes, ofItemAtPath: (directoryPath as NSString).stringByAppendingPathComponent(fileName)) + } catch let error as NSError { + guard error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError else { + try! { throw error }() + preconditionFailure() + } + } + } + } +} diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 52815e9d3..1bfe21a44 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -141,13 +141,13 @@ public extension DatabaseValueConvertible { /// let names = String.fetchAll(db, "SELECT name FROM ...") // [String] /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - returns: An array. @warn_unused_result - public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] { - return fetchAll(try! db.selectStatement(sql), arguments: arguments) + public static func fetchAll(db: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> [Self] { + return db.nonIsolatedRead { db in fetchAll(try! db.selectStatement(sql), arguments: arguments) } } /// Returns a single value fetched from an SQL query. @@ -158,13 +158,13 @@ public extension DatabaseValueConvertible { /// let name = String.fetchOne(db, "SELECT name FROM ...") // String? /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - returns: An optional value. @warn_unused_result - public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? { - return fetchOne(try! db.selectStatement(sql), arguments: arguments) + public static func fetchOne(db: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> Self? { + return db.nonIsolatedRead { db in fetchOne(try! db.selectStatement(sql), arguments: arguments) } } } @@ -219,8 +219,9 @@ public extension Optional where Wrapped: DatabaseValueConvertible { /// let statement = db.selectStatement("SELECT name FROM ...") /// let names = Optional.fetchAll(statement) // [String?] /// - /// - parameter statement: The statement to run. - /// - parameter arguments: Optional statement arguments. + /// - parameters: + /// - statement: The statement to run. + /// - arguments: Optional statement arguments. /// - returns: An array of optional values. @warn_unused_result public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Wrapped?] { @@ -246,9 +247,10 @@ public extension Optional where Wrapped: DatabaseValueConvertible { /// If the database is modified while the sequence is iterating, the /// remaining elements are undefined. /// - /// - parameter db: A Database. - /// - parameter sql: An SQL query. - /// - parameter arguments: Optional statement arguments. + /// - parameters: + /// - db: A Database. + /// - sql: An SQL query. + /// - arguments: Optional statement arguments. /// - returns: A sequence of optional values. @warn_unused_result public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence { @@ -259,12 +261,13 @@ public extension Optional where Wrapped: DatabaseValueConvertible { /// /// let names = String.fetchAll(db, "SELECT name FROM ...") // [String?] /// - /// - parameter db: A Database. - /// - parameter sql: An SQL query. - /// - parameter arguments: Optional statement arguments. + /// - parameters: + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). + /// - sql: An SQL query. + /// - parameter arguments: Optional statement arguments. /// - returns: An array of optional values. @warn_unused_result - public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Wrapped?] { - return fetchAll(try! db.selectStatement(sql), arguments: arguments) + public static func fetchAll(db: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> [Wrapped?] { + return db.nonIsolatedRead { db in fetchAll(try! db.selectStatement(sql), arguments: arguments) } } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift new file mode 100644 index 000000000..063ef9fe2 --- /dev/null +++ b/GRDB/Core/DatabaseWriter.swift @@ -0,0 +1,87 @@ +/// The protocol for all types that can update a database. +/// +/// It is adopted by DatabaseQueue, DatabasePool, and Database. +/// +/// let person = Person(...) +/// try person.insert(dbQueue) +/// try person.insert(dbPool) +/// try dbQueue.inDatabase { db in +/// try person.insert(db) +/// } +/// +/// The protocol comes with isolation guarantees that describe the behavior of +/// adopting types in a multithreaded application. +/// +/// Types that adopt the protocol can provide stronger guarantees in practice. +/// For example, DatabaseQueue provides a stronger isolation level +/// than DatabasePool. +/// +/// **Warning**: Isolation guarantees stand as long as there is no external +/// connection to the database. Should you have to cope with external +/// connections, protect yourself with transactions, and be ready to setup a +/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). +public protocol DatabaseWriter : DatabaseReader { + + // MARK: - Writing in Database + + /// Synchronously executes a block that takes a database connection, and + /// returns its result. + /// + /// The *block* argument is completely isolated. Eventual concurrent + /// database updates are postponed until the block has executed. + func write(block: (db: Database) throws -> T) rethrows -> T +} + +extension DatabaseWriter { + + // MARK: - Writing in Database + + /// Executes one or several SQL statements, separated by semi-colons. + /// + /// try writer.execute( + /// "INSERT INTO persons (name) VALUES (:name)", + /// arguments: ["name": "Arthur"]) + /// + /// try writer.execute( + /// "INSERT INTO persons (name) VALUES (?);" + + /// "INSERT INTO persons (name) VALUES (?);" + + /// "INSERT INTO persons (name) VALUES (?);", + /// arguments; ['Arthur', 'Barbara', 'Craig']) + /// + /// This method may throw a DatabaseError. + /// + /// See documentation of the write() method for information about the + /// isolation from concurrent database updates. + /// + /// - parameters: + /// - sql: An SQL query. + /// - arguments: Optional statement arguments. + /// - returns: A DatabaseChanges. + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func execute(sql: String, arguments: StatementArguments? = nil) throws -> DatabaseChanges { + return try write { db in + try db.execute(sql, arguments: arguments) + } + } + + + // MARK: - Transaction Observers + + /// Add a transaction observer, so that it gets notified of all + /// database changes. + /// + /// The transaction observer is weakly referenced: it is not retained, and + /// stops getting notifications after it is deallocated. + public func addTransactionObserver(transactionObserver: TransactionObserverType) { + write { db in + db.addTransactionObserver(transactionObserver) + } + } + + /// Remove a transaction observer. + public func removeTransactionObserver(transactionObserver: TransactionObserverType) { + write { db in + db.removeTransactionObserver(transactionObserver) + } + } +} diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index e071f3788..13d4596c9 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -7,12 +7,14 @@ public final class Row { /// Builds an empty row. public init() { + statementRef = nil sqliteStatement = nil impl = EmptyRowImpl() } /// Builds a row from a dictionary of values. public init(_ dictionary: [String: DatabaseValueConvertible?]) { + statementRef = nil sqliteStatement = nil impl = DictionaryRowImpl(dictionary: dictionary) } @@ -31,16 +33,34 @@ public final class Row { // MARK: - Not Public let impl: RowImpl + + /// Unless we are producing a row array, we use a single row when iterating a + /// statement: + /// + /// for row in Row.fetch(db, "SELECT ...") { ... } + /// for person in Person.fetch(db, "SELECT ...") { ... } + /// + /// This row keeps an unmanaged reference to the statement, and a handle to + /// the sqlite statement, so that we avoid many retain/release invocations. + /// + /// The statementRef is released in deinit. + let statementRef: Unmanaged? let sqliteStatement: SQLiteStatement + deinit { + statementRef?.release() + } + /// Builds a row from the an SQLite statement. /// /// The row is implemented on top of StatementRowImpl, which grants *direct* /// access to the SQLite statement. Iteration of the statement does modify /// the row. init(statement: SelectStatement) { + let statementRef = Unmanaged.passRetained(statement) // released in deinit + self.statementRef = statementRef self.sqliteStatement = statement.sqliteStatement - self.impl = StatementRowImpl(statement: statement) + self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statementRef: statementRef) } /// Builds a row from the *current state* of the SQLite statement. @@ -48,9 +68,21 @@ public final class Row { /// The row is implemented on top of StatementCopyRowImpl, which *copies* /// the values from the SQLite statement so that further iteration of the /// statement does not modify the row. - init(copiedFromStatement statement: SelectStatement) { + init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, statementRef: Unmanaged) { + self.statementRef = nil self.sqliteStatement = nil - self.impl = StatementCopyRowImpl(statement: statement) + self.impl = StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames) + } + + /// Builds a row from the *current state* of the SQLite statement. + /// + /// The row is implemented on top of StatementCopyRowImpl, which *copies* + /// the values from the SQLite statement so that further iteration of the + /// statement does not modify the row. + init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, columnNames: [String]) { + self.statementRef = nil + self.sqliteStatement = nil + self.impl = StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: columnNames) } } @@ -437,7 +469,9 @@ extension Row { public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence { // Metal rows can be reused. And reusing them yields better performance. let row = Row(statement: statement) - return statement.fetchSequence(arguments: arguments) { row } + return statement.fetchSequence(arguments: arguments) { + return row + } } /// Returns an array of rows fetched from a prepared statement. @@ -451,8 +485,10 @@ extension Row { /// - returns: An array of rows. @warn_unused_result public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Row] { + let sqliteStatement = statement.sqliteStatement + let columnNames = statement.columnNames let sequence = statement.fetchSequence(arguments: arguments) { - Row(copiedFromStatement: statement) + Row(copiedFromSQLiteStatement: sqliteStatement, columnNames: columnNames) } return Array(sequence) } @@ -468,8 +504,10 @@ extension Row { /// - returns: An optional row. @warn_unused_result public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Row? { + let sqliteStatement = statement.sqliteStatement + let columnNames = statement.columnNames let sequence = statement.fetchSequence(arguments: arguments) { - Row(copiedFromStatement: statement) + Row(copiedFromSQLiteStatement: sqliteStatement, columnNames: columnNames) } return sequence.generate().next() } @@ -519,13 +557,13 @@ extension Row { /// let rows = Row.fetchAll(db, "SELECT ...") /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - returns: An array of rows. @warn_unused_result - public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Row] { - return fetchAll(try! db.selectStatement(sql), arguments: arguments) + public static func fetchAll(db: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> [Row] { + return db.nonIsolatedRead { db in fetchAll(try! db.selectStatement(sql), arguments: arguments) } } /// Returns a single row fetched from an SQL query. @@ -533,13 +571,13 @@ extension Row { /// let row = Row.fetchOne(db, "SELECT ...") /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - returns: An optional row. @warn_unused_result - public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Row? { - return fetchOne(try! db.selectStatement(sql), arguments: arguments) + public static func fetchOne(db: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> Row? { + return db.nonIsolatedRead { db in fetchOne(try! db.selectStatement(sql), arguments: arguments) } } } @@ -549,7 +587,11 @@ extension Row : CollectionType { /// The number of columns in the row. public var count: Int { - return impl.count + let sqliteStatement = self.sqliteStatement + guard sqliteStatement != nil else { + return impl.count + } + return Int(sqlite3_column_count(sqliteStatement)) } /// Returns a *generator* over (ColumnName, DatabaseValue) pairs, from left @@ -678,15 +720,16 @@ private struct DictionaryRowImpl : RowImpl { } -/// See Row.init(copiedFromStatement:) +/// See Row.init(copiedFromStatementRef:sqliteStatement:) private struct StatementCopyRowImpl : RowImpl { - let databaseValues: [DatabaseValue] + let databaseValues: ContiguousArray let columnNames: [String] - init(statement: SelectStatement) { - let sqliteStatement = statement.sqliteStatement - self.databaseValues = (0.. let sqliteStatement: SQLiteStatement + let lowercaseColumnIndexes: [String: Int] - init(statement: SelectStatement) { - self.statement = statement - self.sqliteStatement = statement.sqliteStatement + init(sqliteStatement: SQLiteStatement, statementRef: Unmanaged) { + assert(sqliteStatement != nil) + self.statementRef = statementRef + self.sqliteStatement = sqliteStatement + // Optimize row.value(named: "...") + let lowercaseColumnNames = (0.. String { - return statement.columnNames[index] + return statementRef.takeUnretainedValue().columnNames[index] } // This method MUST be case-insensitive, and returns the index of the // leftmost column that matches *name*. func indexOfColumn(named name: String) -> Int? { - return statement.indexOfColumn(named: name) + if let index = lowercaseColumnIndexes[name] { + return index + } + return lowercaseColumnIndexes[name.lowercaseString] } func copy(row: Row) -> Row { - return Row(copiedFromStatement: statement) + return Row(copiedFromSQLiteStatement: sqliteStatement, statementRef: statementRef) } } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift new file mode 100644 index 000000000..1bc30127a --- /dev/null +++ b/GRDB/Core/SerializedDatabase.swift @@ -0,0 +1,88 @@ +import Foundation + +/// A class that serializes accesses to a database. +final class SerializedDatabase { + /// The database + private let database: Database + + /// The database configuration + var configuration: Configuration { + return database.configuration + } + + /// The dispatch queue + private let queue: dispatch_queue_t + + convenience init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCacheType) throws { + // According to https://www.sqlite.org/threadsafe.html + // + // > SQLite support three different threading modes: + // > + // > 1. Multi-thread. In this mode, SQLite can be safely used by + // > multiple threads provided that no single database connection is + // > used simultaneously in two or more threads. + // > + // > 2. Serialized. In serialized mode, SQLite can be safely used by + // > multiple threads with no restriction. + // > + // > [...] + // > + // > The default mode is serialized. + // + // Since our database connection is only used via our serial dispatch + // queue, there is no purpose using the default serialized mode. + var config = configuration + config.threadingMode = .MultiThread + + let database = try Database(path: path, configuration: config, schemaCache: schemaCache) + self.init(database: database) + } + + private init(database: Database) { + self.database = database + self.queue = dispatch_queue_create("com.github.groue.GRDB", nil) + + // Activate database.preconditionValidQueue() + let dispatchQueueID = unsafeBitCast(database, UnsafeMutablePointer.self) + dispatch_queue_set_specific(queue, Database.dispatchQueueIDKey, dispatchQueueID, nil) + database.dispatchQueueID = dispatchQueueID + } + + /// Synchronously executes a block a serialized dispatch queue, and returns + /// its result. + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + func inDatabase(block: (db: Database) throws -> T) rethrows -> T { + // This method is NOT reentrant. + // + // Avoiding dispatch_sync and calling block() right away if the specific + // is currently self.dispatchQueueID looks like a promising solution: + // + // serializedDatabase.inDatabase { db in + // serializedDatabase.inDatabase { db in + // // Look, ma! I'm reentrant! + // } + // } + // + // However it does not survive this code, which deadlocks: + // + // let queue = dispatch_queue_create("...", nil) + // serializedDatabase.inDatabase { db in + // dispatch_sync(queue) { + // serializedDatabase.inDatabase { db in + // // Never run + // } + // } + // } + // + // I try not to ship half-baked solutions, so until a complete solution + // is found to this problem, I prefer discouraging reentrancy. + precondition(database.dispatchQueueID != dispatch_get_specific(Database.dispatchQueueIDKey), "Database methods are not reentrant.") + return try dispatchSync(queue) { + try block(db: self.database) + } + } +} diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 5f374db26..d36eafe69 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -1,3 +1,5 @@ +import Foundation + /// A raw SQLite statement, suitable for the SQLite C API. public typealias SQLiteStatement = COpaquePointer @@ -22,10 +24,11 @@ public class Statement { self.sqliteStatement = sqliteStatement } - init(database: Database, sql: String) throws { + private init(database: Database, sql: String, observer: StatementCompilationObserver) throws { database.preconditionValidQueue() - // See https://www.sqlite.org/c3ref/prepare.html + observer.start() + defer { observer.stop() } let sqlCodeUnits = sql.nulTerminatedUTF8 var sqliteStatement: SQLiteStatement = nil @@ -53,9 +56,7 @@ public class Statement { } deinit { - if sqliteStatement != nil { - sqlite3_finalize(sqliteStatement) - } + sqlite3_finalize(sqliteStatement) } final func reset() throws { @@ -94,7 +95,7 @@ public class Statement { /// Throws a DatabaseError of code SQLITE_ERROR if arguments don't fill all /// statement arguments. public func validateArguments(arguments: StatementArguments) throws { - let _ = try validatedBindings(arguments) + _ = try validatedBindings(arguments) } /// Set arguments without any validation. Trades safety for performance. @@ -258,7 +259,7 @@ public class Statement { /// You create SelectStatement with the Database.selectStatement() method: /// /// dbQueue.inDatabase { db in -/// let statement = db.selectStatement("SELECT * FROM persons WHERE age > ?") +/// let statement = db.selectStatement("SELECT COUNT(*) FROM persons WHERE age > ?") /// let moreThanTwentyCount = Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])! /// } @@ -266,18 +267,11 @@ public final class SelectStatement : Statement { /// The tables this statement feeds on. var sourceTables: Set - override init(database: Database, sql: String) throws { + init(database: Database, sql: String) throws { self.sourceTables = [] - // During the execution of sqlite3_prepare_v2 by super.init, the - // observer listens to authorization callbacks in order to grab the - // list of source tables. - let observer = SourceTableObserver(database) - observer.start() - defer { observer.stop() } - - try super.init(database: database, sql: sql) - + let observer = StatementCompilationObserver(database) + try super.init(database: database, sql: sql, observer: observer) self.sourceTables = observer.sourceTables } @@ -288,7 +282,8 @@ public final class SelectStatement : Statement { /// The column names, ordered from left to right. public lazy var columnNames: [String] = { - (0..(arguments arguments: StatementArguments?, element: () -> T) -> DatabaseSequence { + func fetchSequence(arguments arguments: StatementArguments?, element: () -> Element) -> DatabaseSequence { // Force arguments validity. See UpdateStatement.execute(), and Database.execute() try! prepareWithArguments(arguments) return DatabaseSequence(statement: self, element: element) @@ -312,31 +307,29 @@ public final class SelectStatement : Statement { } /// A sequence of elements fetched from the database. -public struct DatabaseSequence: SequenceType { - private let generateImpl: () throws -> DatabaseGenerator +public struct DatabaseSequence: SequenceType { + private let generateImpl: () throws -> DatabaseGenerator // Statement sequence - private init(statement: SelectStatement, element: () -> T) { - let preconditionValidQueue = statement.database.preconditionValidQueue - let sqliteStatement = statement.sqliteStatement - generateImpl = { + private init(statement: SelectStatement, element: () -> Element) { + self.generateImpl = { // Check that generator is built on a valid queue. - preconditionValidQueue() + statement.database.preconditionValidQueue() - // DatabaseSequence can be restarted + // Support multiple sequence iterations try statement.reset() - return DatabaseGenerator { - // Check that generator is used on a valid queue. - preconditionValidQueue() - + let statementRef = Unmanaged.passRetained(statement) + return DatabaseGenerator(statementRef: statementRef) { (sqliteStatement, statementRef) in switch sqlite3_step(sqliteStatement) { case SQLITE_DONE: return nil case SQLITE_ROW: return element() case let errorCode: - throw DatabaseError(code: errorCode, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments) + let statement = statementRef.takeUnretainedValue() + try! { throw DatabaseError(code: errorCode, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments) }() + preconditionFailure() } } } @@ -346,34 +339,53 @@ public struct DatabaseSequence: SequenceType { static func emptySequence(database: Database) -> DatabaseSequence { // Empty sequence is just as strict as statement sequence, and requires // to be used on the database queue. - let preconditionValidQueue = database.preconditionValidQueue return DatabaseSequence() { // Check that generator is built on a valid queue. - preconditionValidQueue() - return DatabaseGenerator { - // Check that generator is used on a valid queue. - preconditionValidQueue() - return nil - } + database.preconditionValidQueue() + return DatabaseGenerator() } } - private init(generateImpl: () throws -> DatabaseGenerator) { + private init(generateImpl: () throws -> DatabaseGenerator) { self.generateImpl = generateImpl } /// Return a *generator* over the elements of this *sequence*. @warn_unused_result - public func generate() -> DatabaseGenerator { + public func generate() -> DatabaseGenerator { return try! generateImpl() } } /// A generator of elements fetched from the database. -public struct DatabaseGenerator: GeneratorType { - private let element: () throws -> T? - public func next() -> T? { - return try! element() +public class DatabaseGenerator: GeneratorType { + private let statementRef: Unmanaged? + private let sqliteStatement: SQLiteStatement + private let element: ((SQLiteStatement, Unmanaged) -> Element?)? + + // Generator takes ownership of statementRef + init(statementRef: Unmanaged, element: (SQLiteStatement, Unmanaged) -> Element?) { + self.statementRef = statementRef + self.sqliteStatement = statementRef.takeUnretainedValue().sqliteStatement + self.element = element + } + + init() { + self.statementRef = nil + self.sqliteStatement = nil + self.element = nil + } + + deinit { + statementRef?.release() + } + + @warn_unused_result + public func next() -> Element? { + guard let element = element else { + return nil + } + return element(sqliteStatement, unsafeUnwrap(statementRef)) } } @@ -400,18 +412,11 @@ public final class UpdateStatement : Statement { super.init(database: database, sql: sql, sqliteStatement: sqliteStatement) } - override init(database: Database, sql: String) throws { + init(database: Database, sql: String) throws { self.invalidatesDatabaseSchemaCache = false - // During the execution of sqlite3_prepare_v2 by super.init, the - // observer listens to authorization callbacks in order to observe - // schema changes. - let observer = SchemaChangeObserver(database) - observer.start() - defer { observer.stop() } - - try super.init(database: database, sql: sql) - + let observer = StatementCompilationObserver(database) + try super.init(database: database, sql: sql, observer: observer) self.invalidatesDatabaseSchemaCache = observer.invalidatesDatabaseSchemaCache } @@ -421,6 +426,8 @@ public final class UpdateStatement : Statement { /// - returns: A DatabaseChanges. /// - throws: A DatabaseError whenever an SQLite error occurs. public func execute(arguments arguments: StatementArguments? = nil) throws -> DatabaseChanges { + database.preconditionValidQueue() + // Force arguments validity. See SelectStatement.fetchSequence(), and Database.execute() try! prepareWithArguments(arguments) try! reset() diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index be018bf01..9fcd7c20d 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -137,13 +137,13 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible /// let names = String.fetchAll(db, "SELECT name FROM ...") // [String] /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - returns: An array of values. @warn_unused_result - public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] { - return fetchAll(try! db.selectStatement(sql), arguments: arguments) + public static func fetchAll(db: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> [Self] { + return db.nonIsolatedRead { db in fetchAll(try! db.selectStatement(sql), arguments: arguments) } } /// Returns a single value fetched from an SQL query. @@ -151,12 +151,12 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible /// let name = String.fetchOne(db, "SELECT name FROM ...") // String? /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - returns: An optional value. @warn_unused_result - public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? { - return fetchOne(try! db.selectStatement(sql), arguments: arguments) + public static func fetchOne(db: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> Self? { + return db.nonIsolatedRead { db in fetchOne(try! db.selectStatement(sql), arguments: arguments) } } } diff --git a/GRDB/Core/Support/StandardLibrary/RawRepresentable.swift b/GRDB/Core/Support/StandardLibrary/RawRepresentable.swift index 5c53c3e41..5aed73218 100644 --- a/GRDB/Core/Support/StandardLibrary/RawRepresentable.swift +++ b/GRDB/Core/Support/StandardLibrary/RawRepresentable.swift @@ -1,158 +1,30 @@ -// MARK: - DatabaseIntRepresentable - -/// Have your Int enum adopt DatabaseIntRepresentable and it automatically gains -/// DatabaseValueConvertible adoption. +/// DatabaseValueConvertible is free for RawRepresentable types whose raw value +/// is itself DatabaseValueConvertible: /// -/// // An Int enum: /// enum Color : Int { /// case Red /// case White /// case Rose /// } /// -/// // Declare DatabaseIntRepresentable adoption: -/// extension Color : DatabaseIntRepresentable { } +/// // Declare DatabaseValueConvertible adoption: +/// extension Color : DatabaseValueConvertible { } /// /// // Gain full GRDB.swift support: /// db.execute("INSERT INTO colors (color) VALUES (?)", [Color.Red]) /// let color: Color? = Color.fetchOne(db, "SELECT ...") -public protocol DatabaseIntRepresentable : DatabaseValueConvertible { - var rawValue: Int { get } - init?(rawValue: Int) -} - -extension DatabaseIntRepresentable { +public extension RawRepresentable where Self: DatabaseValueConvertible, Self.RawValue: DatabaseValueConvertible { /// Returns a value that can be stored in the database. - public var databaseValue: DatabaseValue { + var databaseValue: DatabaseValue { return rawValue.databaseValue } /// Returns a value initialized from *databaseValue*, if possible. - public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? { - guard let int = Int.fromDatabaseValue(databaseValue) else { + static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? { + guard let rawValue = RawValue.fromDatabaseValue(databaseValue) else { return nil } - return self.init(rawValue: int) - } -} - - -// MARK: - DatabaseInt32Representable - -/// Have your Int32 enum adopt DatabaseInt32Representable and it automatically -/// gains DatabaseValueConvertible adoption. -/// -/// // An Int enum: -/// enum Color : Int32 { -/// case Red -/// case White -/// case Rose -/// } -/// -/// // Declare DatabaseInt32Representable adoption: -/// extension Color : DatabaseInt32Representable { } -/// -/// // Gain full GRDB.swift support: -/// db.execute("INSERT INTO colors (color) VALUES (?)", [Color.Red]) -/// let color: Color? = Color.fetchOne(db, "SELECT ...") -public protocol DatabaseInt32Representable : DatabaseValueConvertible { - var rawValue: Int32 { get } - init?(rawValue: Int32) -} - -extension DatabaseInt32Representable { - - /// Returns a value that can be stored in the database. - public var databaseValue: DatabaseValue { - return rawValue.databaseValue - } - - /// Returns a value initialized from *databaseValue*, if possible. - public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? { - guard let int = Int32.fromDatabaseValue(databaseValue) else { - return nil - } - return self.init(rawValue: int) - } -} - - -// MARK: - DatabaseInt64Representable - -/// Have your Int64 enum adopt DatabaseInt64Representable and it automatically -/// gains DatabaseValueConvertible adoption. -/// -/// // An Int enum: -/// enum Color : Int64 { -/// case Red -/// case White -/// case Rose -/// } -/// -/// // Declare DatabaseInt64Representable adoption: -/// extension Color : DatabaseInt64Representable { } -/// -/// // Gain full GRDB.swift support: -/// db.execute("INSERT INTO colors (color) VALUES (?)", [Color.Red]) -/// let color: Color? = Color.fetchOne(db, "SELECT ...") -public protocol DatabaseInt64Representable : DatabaseValueConvertible { - var rawValue: Int64 { get } - init?(rawValue: Int64) -} - -extension DatabaseInt64Representable { - - /// Returns a value that can be stored in the database. - public var databaseValue: DatabaseValue { - return rawValue.databaseValue - } - - /// Returns a value initialized from *databaseValue*, if possible. - public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? { - guard let int = Int64.fromDatabaseValue(databaseValue) else { - return nil - } - return self.init(rawValue: int) - } -} - - -// MARK: - DatabaseStringRepresentable - -/// Have your String enum adopt DatabaseStringRepresentable and it automatically -/// gains DatabaseValueConvertible adoption. -/// -/// // A String enum: -/// enum Color : String { -/// case Red -/// case White -/// case Rose -/// } -/// -/// // Declare DatabaseIntRepresentable adoption: -/// extension Color : DatabaseStringRepresentable { } -/// -/// // Gain full GRDB.swift support: -/// db.execute("INSERT StringO colors (color) VALUES (?)", [Color.Red]) -/// let color: Color? = Color.fetchOne(db, "SELECT ...") -public protocol DatabaseStringRepresentable : DatabaseValueConvertible { - var rawValue: String { get } - init?(rawValue: String) -} - -extension DatabaseStringRepresentable { - - /// Returns a value that can be stored in the database. - public var databaseValue: DatabaseValue { - return rawValue.databaseValue - } - - /// Returns a value initialized from *databaseValue*, if possible. - public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? { - guard let string = String.fromDatabaseValue(databaseValue) else { - return nil - } - return self.init(rawValue: string) + return self.init(rawValue: rawValue) } } diff --git a/GRDB/Core/Utils.swift b/GRDB/Core/Utils.swift index c547c8cf6..9e8e9e926 100644 --- a/GRDB/Core/Utils.swift +++ b/GRDB/Core/Utils.swift @@ -28,8 +28,8 @@ let SQLITE_TRANSIENT = unsafeBitCast(COpaquePointer(bitPattern: -1), sqlite3_des /// A function declared as rethrows that synchronously executes a throwing /// block in a dispatch_queue. -func dispatchSync(queue: dispatch_queue_t, block: () throws -> T) rethrows -> T { - func dispatchSyncImpl(queue: dispatch_queue_t, block: () throws -> T, block2: (ErrorType) throws -> Void) rethrows -> T { +func dispatchSync(queue: dispatch_queue_t, _ block: () throws -> T) rethrows -> T { + func impl(queue: dispatch_queue_t, block: () throws -> T, onError: (ErrorType) throws -> ()) rethrows -> T { var result: T? = nil var blockError: ErrorType? = nil dispatch_sync(queue) { @@ -40,11 +40,11 @@ func dispatchSync(queue: dispatch_queue_t, block: () throws -> T) rethrows -> } } if let blockError = blockError { - try block2(blockError) + try onError(blockError) } return result! } - return try dispatchSyncImpl(queue, block: block, block2: { throw $0 }) + return try impl(queue, block: block, onError: { throw $0 }) } extension Array { @@ -82,3 +82,157 @@ extension SequenceType where Generator.Element: Equatable { return filter { element in !removedElements.contains(element) } } } + +/// A ReadWriteBox protects a value with a pthread_rwlock_t (single writer, several readers) +final class ReadWriteBox { + var value: T { + get { + pthread_rwlock_rdlock(&rwLock) + defer { pthread_rwlock_unlock(&rwLock) } + return _value + } + set { + pthread_rwlock_wrlock(&rwLock) + defer { pthread_rwlock_unlock(&rwLock) } + _value = newValue + } + } + + init(_ value: T) { + self._value = value + pthread_rwlock_init(&rwLock, nil) + } + + deinit { + pthread_rwlock_destroy(&rwLock) + } + + func read(block: (T) -> U) -> U { + pthread_rwlock_rdlock(&rwLock) + defer { pthread_rwlock_unlock(&rwLock) } + return block(_value) + } + + func write(block: (T) -> Void) { + pthread_rwlock_wrlock(&rwLock) + defer { pthread_rwlock_unlock(&rwLock) } + block(_value) + } + + private var _value: T + private var rwLock = pthread_rwlock_t() +} + +/// A Pool maintains a set of elements that are built them on demand. A pool has +/// a maximum number of elements. +/// +/// // A pool of 3 integers +/// var number = 0 +/// let pool = Pool(maximumCount: 3, makeElement: { +/// number = number + 1 +/// return number +/// }) +/// +/// The function get() dequeues an available element and gives this element to +/// the block argument. During the block execution, the element is not +/// available. When the block is ended, the element is available again. +/// +/// // got 1 +/// pool.get { n in +/// print("got \(n)") +/// } +/// +/// If there is no available element, the pool builds a new element, unless the +/// maximum number of elements is reached. In this case, the get() method +/// blocks the current thread, until an element eventually turns available again. +/// +/// let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) +/// dispatch_apply(6, queue) { _ in +/// pool.get { n in +/// print("got \(n)") +/// } +/// } +/// +/// got 1 +/// got 2 +/// got 3 +/// got 2 +/// got 1 +/// got 3 +final class Pool { + var makeElement: (() -> T)? + private var items: [PoolItem] = [] + private let queue: dispatch_queue_t // protects items + private let semaphore: dispatch_semaphore_t // limits the number of elements + + init(maximumCount: Int, makeElement: (() -> T)? = nil) { + precondition(maximumCount > 0, "Pool size must be at least 1") + self.makeElement = makeElement + self.queue = dispatch_queue_create("com.github.groue.GRDB.Pool", nil) + self.semaphore = dispatch_semaphore_create(maximumCount) + } + + /// Returns a tuple (element, releaseElement()) + /// Client MUST call releaseElement() after the element has been used. + func get() -> (T, () -> ()) { + let item = lockItem() + return (item.element, { self.unlockItem(item) }) + } + + /// Performs a synchronous block with an element. The element turns + /// available after the block has executed. + func get(@noescape block: (T) throws -> U) rethrows -> U { + let (element, release) = get() + defer { release() } + return try block(element) + } + + /// Performs a block on each pool element, available or not. + /// The block is run is some arbitrary queue. + func forEach(block: (T) -> ()) { + dispatch_sync(queue) { + for item in self.items { + block(item.element) + } + } + } + + /// Empty the pool. Currently used items won't be reused. + func clear() { + dispatch_sync(queue) { + self.items = [] + } + } + + private func lockItem() -> PoolItem { + var item: PoolItem! = nil + dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) + dispatch_sync(queue) { + if let index = self.items.indexOf({ $0.available }) { + item = self.items[index] + item.available = false + } else { + item = PoolItem(element: self.makeElement!(), available: false) + self.items.append(item) + } + } + return item + } + + private func unlockItem(item: PoolItem) { + dispatch_sync(queue) { + item.available = true + } + dispatch_semaphore_signal(semaphore) + } +} + +private class PoolItem { + let element: T + var available: Bool + + init(element: T, available: Bool) { + self.element = element + self.available = available + } +} diff --git a/GRDB/FetchRequest/FetchRequest.swift b/GRDB/FetchRequest/FetchRequest.swift index 3551f4135..df8198ba7 100644 --- a/GRDB/FetchRequest/FetchRequest.swift +++ b/GRDB/FetchRequest/FetchRequest.swift @@ -166,9 +166,11 @@ extension FetchRequest { // MARK: Counting /// Returns the number of rows matched by the request. + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public func fetchCount(db: Database) -> Int { - return Int.fetchOne(db, select([_SQLExpression.Count(_SQLResultColumn.Star(nil))]))! + public func fetchCount(db: DatabaseReader) -> Int { + return Int.fetchOne(db, FetchRequest(query.countQuery))! } } @@ -197,7 +199,8 @@ extension FetchRequest where T: RowConvertible { /// Returns a sequence of values. /// - /// let request = Person.order(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.order(nameColumn) /// let persons = request.fetch(db) // DatabaseSequence /// /// The returned sequence can be consumed several times, but it may yield @@ -218,20 +221,26 @@ extension FetchRequest where T: RowConvertible { /// Returns an array of values fetched from a fetch request. /// - /// let request = Person.order(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.order(nameColumn) /// let persons = request.fetchAll(db) // [Person] + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public func fetchAll(db: Database) -> [T] { - return Array(fetch(db)) + public func fetchAll(db: DatabaseReader) -> [T] { + return db.nonIsolatedRead { db in Array(self.fetch(db)) } } /// Returns a single value fetched from a fetch request. /// - /// let request = Person.order(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.order(nameColumn) /// let person = request.fetchOne(db) // Person? + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public func fetchOne(db: Database) -> T? { - return fetch(db).generate().next() + public func fetchOne(db: DatabaseReader) -> T? { + return db.nonIsolatedRead { db in self.fetch(db).generate().next() } } } @@ -296,12 +305,6 @@ extension TableMapping { return all().order(sql: sql) } - /// Returns a FetchRequest sorted in reversed order. - @warn_unused_result - public static func reverse() -> FetchRequest { - return all().reverse() - } - /// Returns a FetchRequest which fetches *limit* rows, starting at /// *offset*. @warn_unused_result @@ -316,8 +319,10 @@ extension TableMapping { // MARK: Counting /// Returns the number of records. + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchCount(db: Database) -> Int { + public static func fetchCount(db: DatabaseReader) -> Int { return all().fetchCount(db) } } @@ -329,7 +334,8 @@ extension DatabaseValueConvertible { /// Returns a sequence of values fetched from a fetch request. /// - /// let request = Person.select(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(nameColumn) /// let names = String.fetch(db, request) // DatabaseSequence /// /// The returned sequence can be consumed several times, but it may yield @@ -350,11 +356,14 @@ extension DatabaseValueConvertible { /// Returns an array of values fetched from a fetch request. /// - /// let request = Person.select(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(nameColumn) /// let names = String.fetchAll(db, request) // [String] + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchAll(db: Database, _ request: FetchRequest) -> [Self] { - return try! fetchAll(request.selectStatement(db)) + public static func fetchAll(db: DatabaseReader, _ request: FetchRequest) -> [Self] { + return db.nonIsolatedRead { db in try! fetchAll(request.selectStatement(db)) } } /// Returns a single value fetched from a fetch request. @@ -362,11 +371,14 @@ extension DatabaseValueConvertible { /// The result is nil if the query returns no row, or if no value can be /// extracted from the first row. /// - /// let request = Person.select(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(nameColumn) /// let name = String.fetchOne(db, request) // String? + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchOne(db: Database, _ request: FetchRequest) -> Self? { - return try! fetchOne(request.selectStatement(db)) + public static func fetchOne(db: DatabaseReader, _ request: FetchRequest) -> Self? { + return db.nonIsolatedRead { db in try! fetchOne(request.selectStatement(db)) } } } @@ -377,7 +389,8 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// Returns a sequence of optional values fetched from a fetch request. /// - /// let request = Person.select(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(nameColumn) /// let names = Optional.fetch(db, request) // DatabaseSequence /// /// The returned sequence can be consumed several times, but it may yield @@ -398,11 +411,14 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// Returns an array of optional values fetched from a fetch request. /// - /// let request = Person.select(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(nameColumn) /// let names = Optional.fetchAll(db, request) // [String?] + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchAll(db: Database, _ request: FetchRequest) -> [Wrapped?] { - return try! fetchAll(request.selectStatement(db)) + public static func fetchAll(db: DatabaseReader, _ request: FetchRequest) -> [Wrapped?] { + return db.nonIsolatedRead { db in try! fetchAll(request.selectStatement(db)) } } } @@ -413,7 +429,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a sequence of values fetched from a fetch request. /// - /// let request = Person.select(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(nameColumn) /// let names = String.fetch(db, request) // DatabaseSequence /// /// The returned sequence can be consumed several times, but it may yield @@ -434,11 +451,14 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns an array of values fetched from a fetch request. /// - /// let request = Person.select(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(nameColumn) /// let names = String.fetchAll(db, request) // [String] + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchAll(db: Database, _ request: FetchRequest) -> [Self] { - return try! fetchAll(request.selectStatement(db)) + public static func fetchAll(db: DatabaseReader, _ request: FetchRequest) -> [Self] { + return db.nonIsolatedRead { db in try! fetchAll(request.selectStatement(db)) } } /// Returns a single value fetched from a fetch request. @@ -446,11 +466,14 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// The result is nil if the query returns no row, or if no value can be /// extracted from the first row. /// - /// let request = Person.select(name) + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(nameColumn) /// let name = String.fetchOne(db, request) // String? + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchOne(db: Database, _ request: FetchRequest) -> Self? { - return try! fetchOne(request.selectStatement(db)) + public static func fetchOne(db: DatabaseReader, _ request: FetchRequest) -> Self? { + return db.nonIsolatedRead { db in try! fetchOne(request.selectStatement(db)) } } } @@ -461,17 +484,18 @@ extension RowConvertible { /// Returns a sequence of records fetched from a fetch request. /// - /// let request = Person.order(name) - /// let persons = Person.fetch(db, request) // DatabaseSequence + /// let nameColumn = SQLColumn("firstName") + /// let request = Person.order(nameColumn) + /// let identities = Identity.fetch(db, request) // DatabaseSequence /// /// The returned sequence can be consumed several times, but it may yield /// different results, should database changes have occurred between two /// generations: /// - /// let persons = Person.fetch(db, request) - /// Array(persons).count // 3 + /// let identities = Identity.fetch(db, request) + /// Array(identities).count // 3 /// db.execute("DELETE ...") - /// Array(persons).count // 2 + /// Array(identities).count // 2 /// /// If the database is modified while the sequence is iterating, the /// remaining elements are undefined. @@ -482,20 +506,26 @@ extension RowConvertible { /// Returns an array of records fetched from a fetch request. /// - /// let request = Person.order(name) - /// let persons = Person.fetchAll(db, request) // [Person] + /// let nameColumn = SQLColumn("name") + /// let request = Person.order(nameColumn) + /// let identities = Identity.fetchAll(db, request) // [Identity] + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchAll(db: Database, _ request: FetchRequest) -> [Self] { - return try! fetchAll(request.selectStatement(db)) + public static func fetchAll(db: DatabaseReader, _ request: FetchRequest) -> [Self] { + return db.nonIsolatedRead { db in try! fetchAll(request.selectStatement(db)) } } /// Returns a single record fetched from a fetch request. /// - /// let request = Person.order(name) - /// let person = Person.fetchOne(db, request) // Person? + /// let nameColumn = SQLColumn("name") + /// let request = Person.order(nameColumn) + /// let identity = Identity.fetchOne(db, request) // Identity? + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchOne(db: Database, _ request: FetchRequest) -> Self? { - return try! fetchOne(request.selectStatement(db)) + public static func fetchOne(db: DatabaseReader, _ request: FetchRequest) -> Self? { + return db.nonIsolatedRead { db in try! fetchOne(request.selectStatement(db)) } } } @@ -526,16 +556,20 @@ extension RowConvertible where Self: TableMapping { /// Returns an array of all records fetched from the database. /// /// let persons = Person.fetchAll(db) // [Person] + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchAll(db: Database) -> [Self] { + public static func fetchAll(db: DatabaseReader) -> [Self] { return all().fetchAll(db) } /// Returns the first record fetched from a fetch request. /// /// let person = Person.fetchOne(db) // Person? + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchOne(db: Database) -> Self? { + public static func fetchOne(db: DatabaseReader) -> Self? { return all().fetchOne(db) } } @@ -547,7 +581,9 @@ extension Row { /// Returns a sequence of rows fetched from a fetch request. /// - /// let request = Person.select(id, name) + /// let idColumn = SQLColumn("id") + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(idColumn, nameColumn) /// for row in Row.fetch(db, request) { /// let id: Int64 = row.value(atIndex: 0) /// let name: String = row.value(atIndex: 1) @@ -579,19 +615,27 @@ extension Row { /// Returns an array of rows fetched from a fetch request. /// - /// let statement = db.selectStatement("SELECT ...") + /// let idColumn = SQLColumn("id") + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(idColumn, nameColumn) /// let rows = Row.fetchAll(db, request) + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchAll(db: Database, _ request: FetchRequest) -> [Row] { - return try! fetchAll(request.selectStatement(db)) + public static func fetchAll(db: DatabaseReader, _ request: FetchRequest) -> [Row] { + return db.nonIsolatedRead { db in try! fetchAll(request.selectStatement(db)) } } /// Returns a single row fetched from a fetch request. /// - /// let statement = db.selectStatement("SELECT ...") + /// let idColumn = SQLColumn("id") + /// let nameColumn = SQLColumn("name") + /// let request = Person.select(idColumn, nameColumn) /// let row = Row.fetchOne(db, request) + /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). @warn_unused_result - public static func fetchOne(db: Database, _ request: FetchRequest) -> Row? { - return try! fetchOne(request.selectStatement(db)) + public static func fetchOne(db: DatabaseReader, _ request: FetchRequest) -> Row? { + return db.nonIsolatedRead { db in try! fetchOne(request.selectStatement(db)) } } } diff --git a/GRDB/FetchRequest/SQLSelectQuery.swift b/GRDB/FetchRequest/SQLSelectQuery.swift index 3390ee7bd..8c957da3e 100644 --- a/GRDB/FetchRequest/SQLSelectQuery.swift +++ b/GRDB/FetchRequest/SQLSelectQuery.swift @@ -46,6 +46,7 @@ public struct _SQLSelectQuery { sql += " DISTINCT" } + assert(!selection.isEmpty) sql += try " " + selection.map { try $0.resultColumnSQL(db, &bindings) }.joinWithSeparator(", ") if let source = source { @@ -88,6 +89,91 @@ public struct _SQLSelectQuery { return sql } + + /// Returns a query that counts the number of rows matched by self. + var countQuery: _SQLSelectQuery { + guard groupByExpressions.isEmpty && limit == nil else { + // SELECT ... GROUP BY ... + // SELECT ... LIMIT ... + return trivialCountQuery + } + + guard let source = source, case .Table(name: let tableName, alias: let alias) = source else { + // SELECT ... FROM (something which is not a table) + return trivialCountQuery + } + + assert(!selection.isEmpty) + if selection.count == 1 { + let selectable = self.selection[0] + switch selectable.sqlSelectableKind { + case .Star(sourceName: let sourceName): + guard !distinct else { + return trivialCountQuery + } + + if let sourceName = sourceName { + guard sourceName == tableName || sourceName == alias else { + return trivialCountQuery + } + } + + // SELECT * FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + var countQuery = unorderedQuery + countQuery.selection = [_SQLExpression.Count(selectable)] + return countQuery + + case .Expression(let expression): + // SELECT [DISTINCT] expr FROM tableName ... + if distinct { + // SELECT DISTINCT expr FROM tableName ... + // -> + // SELECT COUNT(DISTINCT expr) FROM tableName ... + var countQuery = unorderedQuery + countQuery.distinct = false + countQuery.selection = [_SQLExpression.CountDistinct(expression)] + return countQuery + } else { + // SELECT expr FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + var countQuery = unorderedQuery + countQuery.selection = [_SQLExpression.Count(_SQLResultColumn.Star(nil))] + return countQuery + } + } + } else { + // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... + + guard !distinct else { + return trivialCountQuery + } + + // SELECT expr1, expr2, ... FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + var countQuery = unorderedQuery + countQuery.selection = [_SQLExpression.Count(_SQLResultColumn.Star(nil))] + return countQuery + } + } + + // SELECT COUNT(*) FROM (self) + private var trivialCountQuery: _SQLSelectQuery { + return _SQLSelectQuery( + select: [_SQLExpression.Count(_SQLResultColumn.Star(nil))], + from: .Query(query: unorderedQuery, alias: nil)) + } + + /// Remove ordering + private var unorderedQuery: _SQLSelectQuery { + var query = self + query.reversed = false + query.sortDescriptors = [] + return query + } } @@ -95,11 +181,8 @@ public struct _SQLSelectQuery { indirect enum _SQLSource { case Table(name: String, alias: String?) - case Query(_SQLSelectQuery, alias: String) - case Join(_SQLSource, _SQLExpression, _SQLSource) + case Query(query: _SQLSelectQuery, alias: String?) - // a JOIN b ON ab JOIN c ON abc - // ((a,b,ab), c, abc) func sql(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String { switch self { case .Table(let table, let alias): @@ -109,15 +192,11 @@ indirect enum _SQLSource { return table.quotedDatabaseIdentifier } case .Query(let query, let alias): - return try "(" + query.sql(db, &bindings) + ") AS " + alias.quotedDatabaseIdentifier - case .Join(let first, let expression, let second): - switch second { - case .Join: - fatalError("WTF") - default: - break + if let alias = alias { + return try "(" + query.sql(db, &bindings) + ") AS " + alias.quotedDatabaseIdentifier + } else { + return try "(" + query.sql(db, &bindings) + ")" } - return try first.sql(db, &bindings) + " JOIN " + second.sql(db, &bindings) + " ON " + expression.sql(db, &bindings) } } } @@ -257,6 +336,14 @@ extension _SQLDerivedExpressionType { public func countedSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String { return try sqlExpression.sql(db, &bindings) } + + /// This property is an implementation detail of the query interface. + /// Do not use it directly. + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + public var sqlSelectableKind: _SQLSelectableKind { + return .Expression(sqlExpression) + } } extension _SQLDerivedExpressionType { @@ -279,7 +366,7 @@ extension _SQLDerivedExpressionType { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public func aliased(alias: String) -> _SQLSelectable { - return _SQLResultColumn.Expression(sqlExpression, alias) + return _SQLResultColumn.Expression(expression: sqlExpression, alias: alias) } } @@ -506,11 +593,21 @@ extension _SQLExpression : _SQLDerivedExpressionType { public protocol _SQLSelectable { func resultColumnSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String func countedSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String + var sqlSelectableKind: _SQLSelectableKind { get } +} + +/// This type is an implementation detail of the query interface. +/// Do not use it directly. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +public enum _SQLSelectableKind { + case Expression(_SQLExpression) + case Star(sourceName: String?) } enum _SQLResultColumn { case Star(String?) - case Expression(_SQLExpression, String) + case Expression(expression: _SQLExpression, alias: String) } extension _SQLResultColumn : _SQLSelectable { @@ -523,8 +620,8 @@ extension _SQLResultColumn : _SQLSelectable { } else { return "*" } - case .Expression(let expression, let identifier): - return try expression.sql(db, &bindings) + " AS " + identifier.quotedDatabaseIdentifier + case .Expression(expression: let expression, alias: let alias): + return try expression.sql(db, &bindings) + " AS " + alias.quotedDatabaseIdentifier } } @@ -532,10 +629,19 @@ extension _SQLResultColumn : _SQLSelectable { switch self { case .Star: return "*" - case .Expression(let expression, _): + case .Expression(expression: let expression, alias: _): return try expression.sql(db, &bindings) } } + + var sqlSelectableKind: _SQLSelectableKind { + switch self { + case .Star(let sourceName): + return .Star(sourceName: sourceName) + case .Expression(expression: let expression, alias: _): + return .Expression(expression) + } + } } diff --git a/GRDB/Migrations/DatabaseMigrator.swift b/GRDB/Migrations/DatabaseMigrator.swift index 8e3aac24f..75d810a37 100644 --- a/GRDB/Migrations/DatabaseMigrator.swift +++ b/GRDB/Migrations/DatabaseMigrator.swift @@ -79,10 +79,11 @@ public struct DatabaseMigrator { /// migration has not yet been applied, its block is executed in /// a transaction. /// - /// - parameter dbQueue: The Database Queue where migrations should apply. + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database) where migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. - public func migrate(dbQueue: DatabaseQueue) throws { - try dbQueue.inDatabase { db in + public func migrate(db: DatabaseWriter) throws { + try db.write { db in try self.setupMigrations(db) try self.runMigrations(db) } diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 9c4864f55..50d928868 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -62,7 +62,9 @@ public protocol MutablePersistable : TableMapping { /// } var persistentDictionary: [String: DatabaseValueConvertible?] { get } - /// Don't call this method directly: it is called upon successful insertion, + /// Do not call this method directly. + /// + /// It is called upon successful insertion, in a protected dispatch queue, /// with the inserted RowID and the eventual INTEGER PRIMARY KEY /// column name. /// @@ -99,8 +101,10 @@ public protocol MutablePersistable : TableMapping { /// implementation of insert(). In their implementation, it is recommended /// that they invoke the performInsert() method. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - throws: A DatabaseError whenever an SQLite error occurs. - mutating func insert(db: Database) throws + mutating func insert(db: DatabaseWriter) throws /// Executes an UPDATE statement. /// @@ -112,10 +116,12 @@ public protocol MutablePersistable : TableMapping { /// implementation of update(). In their implementation, it is recommended /// that they invoke the performUpdate() method. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - 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 + func update(db: DatabaseWriter) throws /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. @@ -133,9 +139,11 @@ public protocol MutablePersistable : TableMapping { /// implementation of save(). In their implementation, it is recommended /// that they invoke the performSave() method. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). - mutating func save(db: Database) throws + mutating func save(db: DatabaseWriter) throws /// Executes a DELETE statement. /// @@ -144,9 +152,11 @@ public protocol MutablePersistable : TableMapping { /// implementation of delete(). In their implementation, it is recommended /// that they invoke the performDelete() method. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - returns: Whether a database row was deleted. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - func delete(db: Database) throws -> Bool + func delete(db: DatabaseWriter) throws -> Bool /// Returns true if and only if the primary key matches a row in /// the database. @@ -156,8 +166,9 @@ public protocol MutablePersistable : TableMapping { /// implementation of exists(). In their implementation, it is recommended /// that they invoke the performExists() method. /// + /// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - returns: Whether the primary key matches a row in the database. - func exists(db: Database) -> Bool + func exists(db: DatabaseReader) -> Bool } public extension MutablePersistable { @@ -172,14 +183,14 @@ public extension MutablePersistable { /// Executes an INSERT statement. /// /// The default implementation for insert() invokes performInsert(). - mutating func insert(db: Database) throws { + mutating func insert(db: DatabaseWriter) throws { try performInsert(db) } /// Executes an UPDATE statement. /// /// The default implementation for update() invokes performUpdate(). - func update(db: Database) throws { + func update(db: DatabaseWriter) throws { try performUpdate(db) } @@ -187,14 +198,14 @@ public extension MutablePersistable { /// the database. /// /// The default implementation for save() invokes performSave(). - mutating func save(db: Database) throws { + mutating func save(db: DatabaseWriter) throws { try performSave(db) } /// Executes a DELETE statement. /// /// The default implementation for delete() invokes performDelete(). - func delete(db: Database) throws -> Bool { + func delete(db: DatabaseWriter) throws -> Bool { return try performDelete(db) } @@ -202,7 +213,7 @@ public extension MutablePersistable { /// the database. /// /// The default implementation for exists() invokes performExists(). - func exists(db: Database) -> Bool { + func exists(db: DatabaseReader) -> Bool { return performExists(db) } @@ -228,11 +239,13 @@ public extension MutablePersistable { /// that adopt MutablePersistable can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). - mutating func performInsert(db: Database) throws { - let dataMapper = DataMapper(db, self) - let changes = try dataMapper.insertStatement().execute() - if let rowID = changes.insertedRowID { - didInsertWithRowID(rowID, forColumn: dataMapper.primaryKey.rowIDColumn) + mutating func performInsert(db: DatabaseWriter) throws { + try db.write { db in + let dataMapper = DataMapper(db, self) + let changes = try dataMapper.insertStatement().execute() + if let rowID = changes.insertedRowID { + self.didInsertWithRowID(rowID, forColumn: dataMapper.primaryKey.rowIDColumn) + } } } @@ -243,10 +256,12 @@ 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 { - let changes = try DataMapper(db, self).updateStatement().execute() - if changes.changedRowCount == 0 { - throw PersistenceError.NotFound(self) + func performUpdate(db: DatabaseWriter) throws { + try db.write { db in + let changes = try DataMapper(db, self).updateStatement().execute() + if changes.changedRowCount == 0 { + throw PersistenceError.NotFound(self) + } } } @@ -259,23 +274,25 @@ public extension MutablePersistable { /// implementation of performSave(). /// /// This default implementation forwards the job to `update` or `insert`. - mutating func performSave(db: Database) throws { - // Make sure we call self.insert and self.update so that classes that - // override insert or save have opportunity to perform their custom job. - - if !canUpdateInDatabase(db) { - try insert(db) - return - } - - do { - try update(db) - } catch PersistenceError.NotFound { - // TODO: check that the not persisted objet is self - // - // Why? Adopting types could override update() and update another - // object which may be the one throwing this error. - try insert(db) + mutating func performSave(db: DatabaseWriter) throws { + try db.write { db in + // Make sure we call self.insert and self.update so that classes + // that override insert or save have opportunity to perform their + // custom job. + + if self.canUpdateInDatabase(db) { + do { + try self.update(db) + } catch PersistenceError.NotFound { + // TODO: check that the not persisted objet is self + // + // Why? Adopting types could override update() and update + // another object which may be the one throwing this error. + try self.insert(db) + } + } else { + try self.insert(db) + } } } @@ -286,8 +303,10 @@ public extension MutablePersistable { /// that adopt MutablePersistable can invoke performDelete() in /// their implementation of delete(). They should not provide their own /// implementation of performDelete(). - func performDelete(db: Database) throws -> Bool { - return try DataMapper(db, self).deleteStatement().execute().changedRowCount > 0 + func performDelete(db: DatabaseWriter) throws -> Bool { + return try db.write { db in + try DataMapper(db, self).deleteStatement().execute().changedRowCount > 0 + } } /// Don't invoke this method directly: it is an internal method for types @@ -297,12 +316,61 @@ public extension MutablePersistable { /// that adopt MutablePersistable can invoke performExists() in /// their implementation of exists(). They should not provide their own /// implementation of performExists(). - func performExists(db: Database) -> Bool { - return (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil) + func performExists(db: DatabaseReader) -> Bool { + return db.nonIsolatedRead { db in + (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil) + } } } +extension MutablePersistable { + /// Returns a function that returns the primary key of a record + /// + /// struct Person: MutablePersistable { ... } + /// dbQueue.inDatabase { db in + /// let primaryKey = Person.primaryKeyFunction(db) + /// } + /// let person = Person(id: 1, name: "Arthur") + /// primaryKey(person) // ["id": 1] + /// + /// - throws: A DatabaseError if table does not exist. + static func primaryKeyFunction(db: Database) throws -> (Self) -> [String: DatabaseValue] { + db.preconditionValidQueue() + let columns = try db.primaryKey(databaseTableName()).columns + return { record in + let dictionary = record.persistentDictionary + return Dictionary(keys: columns) { databaseValue(forColumn: $0, inDictionary: dictionary) } + } + } + + /// Returns a function that returns true if and only if two records have the + /// same primary key and both primary keys contain at least one non-null + /// value. + /// + /// struct Person: MutablePersistable { ... } + /// dbQueue.inDatabase { db in + /// let comparator = Person.primaryKeyComparator(db) + /// } + /// let unsaved = Person(id: nil, name: "Unsaved") + /// let arthur1 = Person(id: 1, name: "Arthur") + /// let arthur2 = Person(id: 1, name: "Arthur") + /// let barbara = Person(id: 2, name: "Barbara") + /// comparator(unsaved, unsaved) // false + /// comparator(arthur1, arthur2) // true + /// comparator(arthur1, barbara) // false + /// + /// - throws: A DatabaseError if table does not exist. + static func primaryKeyComparator(db: Database) throws -> (Self, Self) -> Bool { + let primaryKey = try Self.primaryKeyFunction(db) + return { (lhs, rhs) in + let (lhs, rhs) = (primaryKey(lhs), primaryKey(rhs)) + guard lhs.contains({ !$1.isNull }) else { return false } + guard rhs.contains({ !$1.isNull }) else { return false } + return lhs == rhs + } + } +} // MARK: - Persistable @@ -314,7 +382,9 @@ public extension MutablePersistable { /// mutating methods. public protocol Persistable : MutablePersistable { - /// Don't call this method directly: it is called upon successful insertion, + /// Do not call this method directly. + /// + /// It is called upon successful insertion, in a protected dispatch queue, /// with the inserted RowID and the eventual INTEGER PRIMARY KEY /// column name. /// @@ -342,8 +412,10 @@ public protocol Persistable : MutablePersistable { /// implementation of insert(). In their implementation, it is recommended /// that they invoke the performInsert() method. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - throws: A DatabaseError whenever an SQLite error occurs. - func insert(db: Database) throws + func insert(db: DatabaseWriter) throws /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. @@ -361,9 +433,11 @@ public protocol Persistable : MutablePersistable { /// implementation of save(). In their implementation, it is recommended /// that they invoke the performSave() method. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). - func save(db: Database) throws + func save(db: DatabaseWriter) throws } public extension Persistable { @@ -377,7 +451,7 @@ public extension Persistable { /// Executes an INSERT statement. /// /// The default implementation for insert() invokes performInsert(). - func insert(db: Database) throws { + func insert(db: DatabaseWriter) throws { try performInsert(db) } @@ -385,7 +459,7 @@ public extension Persistable { /// the database. /// /// The default implementation for save() invokes performSave(). - func save(db: Database) throws { + func save(db: DatabaseWriter) throws { try performSave(db) } @@ -399,11 +473,13 @@ public extension Persistable { /// that adopt Persistable can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). - func performInsert(db: Database) throws { - let dataMapper = DataMapper(db, self) - let changes = try dataMapper.insertStatement().execute() - if let rowID = changes.insertedRowID { - didInsertWithRowID(rowID, forColumn: dataMapper.primaryKey.rowIDColumn) + func performInsert(db: DatabaseWriter) throws { + try db.write { db in + let dataMapper = DataMapper(db, self) + let changes = try dataMapper.insertStatement().execute() + if let rowID = changes.insertedRowID { + self.didInsertWithRowID(rowID, forColumn: dataMapper.primaryKey.rowIDColumn) + } } } @@ -416,23 +492,24 @@ public extension Persistable { /// implementation of performSave(). /// /// This default implementation forwards the job to `update` or `insert`. - func performSave(db: Database) throws { - // Make sure we call self.insert and self.update so that classes that - // override insert or save have opportunity to perform their custom job. - - if !canUpdateInDatabase(db) { - try insert(db) - return - } - - do { - try update(db) - } catch PersistenceError.NotFound { - // TODO: check that the not persisted objet is self - // - // Why? Adopting types could override update() and update another - // object which may be the one throwing this error. - try insert(db) + func performSave(db: DatabaseWriter) throws { + try db.write { db in + // Make sure we call self.insert and self.update so that classes that + // override insert or save have opportunity to perform their custom job. + + if self.canUpdateInDatabase(db) { + do { + try self.update(db) + } catch PersistenceError.NotFound { + // TODO: check that the not persisted objet is self + // + // Why? Adopting types could override update() and update another + // object which may be the one throwing this error. + try self.insert(db) + } + } else { + try self.insert(db) + } } } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 5c75e496f..2cbe7af35 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -22,8 +22,12 @@ public class Record : RowConvertible, TableMapping, Persistable { required public init(_ row: Row) { } - /// Don't call this method directly. It is called after a Record has been - /// fetched. + /// Do not call this method directly. + /// + /// This method is called in a protected dispatch queue, after a record has + /// been fetched from the database. + /// + /// Record subclasses have an opportunity to complete their initialization. /// /// *Important*: subclasses must invoke super's implementation. public func awakeFromFetch(row row: Row, database: Database) { @@ -77,11 +81,22 @@ public class Record : RowConvertible, TableMapping, Persistable { return [:] } - /// Don't call this method directly: it is called upon successful insertion, + /// Do not call this method directly. + /// + /// It is called upon successful insertion, in a protected dispatch queue, /// with the inserted RowID and the eventual INTEGER PRIMARY KEY /// column name. /// - /// The default implementation does nothing. + /// The implementation of the base Record class does nothing. + /// + /// class Person : Record { + /// var id: Int64? + /// var name: String? + /// + /// func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + /// id = rowID + /// } + /// } /// /// - parameters: /// - rowID: The inserted rowID. @@ -186,8 +201,10 @@ public class Record : RowConvertible, TableMapping, Persistable { /// their id automatically set after successful insertion, if it was nil /// before the insertion. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - throws: A DatabaseError whenever an SQLite error occurs. - public func insert(db: Database) throws { + public func insert(db: DatabaseWriter) throws { // The simplest code would be: // // try performInsert(db) @@ -200,30 +217,32 @@ public class Record : RowConvertible, TableMapping, Persistable { // So let's provide our custom implementation of insert, which uses the // same persistentDictionary for both insertion, and change tracking. - let dataMapper = DataMapper(db, self) - var persistentDictionary = dataMapper.persistentDictionary - let changes = try dataMapper.insertStatement().execute() - if let rowID = changes.insertedRowID { - let rowIDColumn = dataMapper.primaryKey.rowIDColumn - didInsertWithRowID(rowID, forColumn: rowIDColumn) - - // Update persistentDictionary with inserted id, so that we can - // set hasPersistentChangedValues to false: - if let rowIDColumn = rowIDColumn { - if persistentDictionary[rowIDColumn] != nil { - persistentDictionary[rowIDColumn] = rowID - } else { - let rowIDColumn = rowIDColumn.lowercaseString - for column in persistentDictionary.keys where column.lowercaseString == rowIDColumn { - persistentDictionary[column] = rowID - break + try db.write { db in + let dataMapper = DataMapper(db, self) + var persistentDictionary = dataMapper.persistentDictionary + let changes = try dataMapper.insertStatement().execute() + if let rowID = changes.insertedRowID { + let rowIDColumn = dataMapper.primaryKey.rowIDColumn + self.didInsertWithRowID(rowID, forColumn: rowIDColumn) + + // Update persistentDictionary with inserted id, so that we can + // set hasPersistentChangedValues to false: + if let rowIDColumn = rowIDColumn { + if persistentDictionary[rowIDColumn] != nil { + persistentDictionary[rowIDColumn] = rowID + } else { + let rowIDColumn = rowIDColumn.lowercaseString + for column in persistentDictionary.keys where column.lowercaseString == rowIDColumn { + persistentDictionary[column] = rowID + break + } } } } + + // Set hasPersistentChangedValues to false + self.referenceRow = Row(persistentDictionary) } - - // Set hasPersistentChangedValues to false - referenceRow = Row(persistentDictionary) } /// Executes an UPDATE statement. @@ -234,10 +253,12 @@ public class Record : RowConvertible, TableMapping, Persistable { /// This method is guaranteed to have updated a row in the database if it /// returns without error. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - 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 and record could not be updated. - public func update(db: Database) throws { + public func update(db: DatabaseWriter) throws { // The simplest code would be: // // try performUpdate(db) @@ -249,15 +270,16 @@ 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) - let changes = try dataMapper.updateStatement().execute() - if changes.changedRowCount == 0 { - throw PersistenceError.NotFound(self) + try db.write { db in + let dataMapper = DataMapper(db, self) + let changes = try dataMapper.updateStatement().execute() + if changes.changedRowCount == 0 { + throw PersistenceError.NotFound(self) + } + + // Set hasPersistentChangedValues to false + self.referenceRow = Row(dataMapper.persistentDictionary) } - - // Set hasPersistentChangedValues to false - referenceRow = Row(dataMapper.persistentDictionary) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in @@ -274,9 +296,11 @@ public class Record : RowConvertible, TableMapping, Persistable { /// This method is guaranteed to have inserted or updated a row in the /// database if it returns without error. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). - final public func save(db: Database) throws { + final public func save(db: DatabaseWriter) throws { try performSave(db) } @@ -285,15 +309,18 @@ public class Record : RowConvertible, TableMapping, Persistable { /// On success, this method sets the *hasPersistentChangedValues* flag /// to true. /// + /// - parameter db: A DatabaseWriter (DatabaseQueue, DatabasePool, or + /// Database). /// - returns: Whether a database row was deleted. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func delete(db: Database) throws -> Bool { - let deleted = try performDelete(db) - // Future calls to update() will throw NotFound. Make the user - // a favor and make sure this error is thrown even if she checks the - // hasPersistentChangedValues flag: - hasPersistentChangedValues = true - return deleted + public func delete(db: DatabaseWriter) throws -> Bool { + defer { + // Future calls to update() will throw NotFound. Make the user + // a favor and make sure this error is thrown even if she checks the + // hasPersistentChangedValues flag: + hasPersistentChangedValues = true + } + return try performDelete(db) } } diff --git a/GRDB/Record/RowConvertible.swift b/GRDB/Record/RowConvertible.swift index 41f76d18b..9c6637583 100644 --- a/GRDB/Record/RowConvertible.swift +++ b/GRDB/Record/RowConvertible.swift @@ -27,6 +27,9 @@ public protocol RowConvertible { /// Do not call this method directly. /// + /// This method is called in a protected dispatch queue, after a record has + /// been fetched from the database. + /// /// Types that adopt RowConvertible have an opportunity to complete their /// initialization. mutating func awakeFromFetch(row row: Row, database: Database) @@ -134,13 +137,13 @@ extension RowConvertible { /// let persons = Person.fetchAll(db, "SELECT * FROM persons") // [Person] /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - returns: An array of records. @warn_unused_result - public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] { - return fetchAll(try! db.selectStatement(sql), arguments: arguments) + public static func fetchAll(db: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> [Self] { + return db.nonIsolatedRead { db in fetchAll(try! db.selectStatement(sql), arguments: arguments) } } /// Returns a single record fetched from an SQL query. @@ -148,12 +151,12 @@ extension RowConvertible { /// let person = Person.fetchOne(db, "SELECT * FROM persons") // Person? /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - returns: An optional record. @warn_unused_result - public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? { - return fetchOne(try! db.selectStatement(sql), arguments: arguments) + public static func fetchOne(db: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> Self? { + return db.nonIsolatedRead { db in fetchOne(try! db.selectStatement(sql), arguments: arguments) } } } diff --git a/GRDB/Record/TableMapping.swift b/GRDB/Record/TableMapping.swift index e45bffd79..0035ae955 100644 --- a/GRDB/Record/TableMapping.swift +++ b/GRDB/Record/TableMapping.swift @@ -42,15 +42,17 @@ extension RowConvertible where Self: TableMapping { /// The order of records in the returned array is undefined. /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - keys: A sequence of primary keys. /// - returns: An array of records. @warn_unused_result - public static func fetchAll(db: Database, keys: Sequence) -> [Self] { - guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else { - return [] + public static func fetchAll(db: DatabaseReader, keys: Sequence) -> [Self] { + return db.nonIsolatedRead { db in + guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else { + return [] + } + return fetchAll(statement) } - return fetchAll(statement) } /// Returns a single record given its primary key. @@ -58,15 +60,17 @@ extension RowConvertible where Self: TableMapping { /// let person = Person.fetchOne(db, key: 123) // Person? /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - key: A primary key value. /// - returns: An optional record. @warn_unused_result - public static func fetchOne(db: Database, key: PrimaryKeyType?) -> Self? { + public static func fetchOne(db: DatabaseReader, key: PrimaryKeyType?) -> Self? { guard let key = key else { return nil } - return fetchOne(fetchByPrimaryKeyStatement(db, values: [key])!) + return db.nonIsolatedRead { db in + return fetchOne(fetchByPrimaryKeyStatement(db, values: [key])!) + } } // Returns "SELECT * FROM table WHERE id IN (?,?,?)" @@ -132,15 +136,17 @@ extension RowConvertible where Self: TableMapping { /// The order of records in the returned array is undefined. /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - keys: An array of key dictionaries. /// - returns: An array of records. @warn_unused_result - public static func fetchAll(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> [Self] { - guard let statement = fetchByKeyStatement(db, keys: keys) else { - return [] + public static func fetchAll(db: DatabaseReader, keys: [[String: DatabaseValueConvertible?]]) -> [Self] { + return db.nonIsolatedRead { db in + guard let statement = fetchByKeyStatement(db, keys: keys) else { + return [] + } + return fetchAll(statement) } - return fetchAll(statement) } /// Returns a single record given a key dictionary. @@ -148,12 +154,12 @@ extension RowConvertible where Self: TableMapping { /// let person = Person.fetchOne(db, key: ["name": Arthur"]) // Person? /// /// - parameters: - /// - db: A Database. + /// - db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database). /// - key: A dictionary of values. /// - returns: An optional record. @warn_unused_result - public static func fetchOne(db: Database, key: [String: DatabaseValueConvertible?]) -> Self? { - return fetchOne(fetchByKeyStatement(db, keys: [key])!) + public static func fetchOne(db: DatabaseReader, key: [String: DatabaseValueConvertible?]) -> Self? { + return db.nonIsolatedRead { db in fetchOne(fetchByKeyStatement(db, keys: [key])!) } } // Returns "SELECT * FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ... diff --git a/Playgrounds/Record.playground/Contents.swift b/Playgrounds/Record.playground/Contents.swift index 22949f0c8..27e4dd506 100644 --- a/Playgrounds/Record.playground/Contents.swift +++ b/Playgrounds/Record.playground/Contents.swift @@ -99,18 +99,16 @@ try dbQueue.inDatabase { db in //: ## Fetching Records -dbQueue.inDatabase { db in //: Fetch records from the database: - let allPersons = Person.fetchAll(db) - +let allPersons = Person.fetchAll(dbQueue) + //: Fetch record by primary key: - let person = Person.fetchOne(db, key: arthur.id)! - person.fullName +let person = Person.fetchOne(dbQueue, key: arthur.id)! +person.fullName //: Fetch persons with an SQL query: - let millers = Person.fetchAll(db, "SELECT * FROM persons WHERE lastName = ?", arguments: ["Miller"]) - millers.first!.fullName -} +let millers = Person.fetchAll(dbQueue, "SELECT * FROM persons WHERE lastName = ?", arguments: ["Miller"]) +millers.first!.fullName //: To fetch persons using the query interface, you need some colums that can filter or sort: @@ -120,11 +118,8 @@ struct Col { static let lastName = SQLColumn("lastName") } -dbQueue.inDatabase { db in - //: Sort - let personsSortedByName = Person.order(Col.firstName, Col.lastName).fetchAll(db) - +let personsSortedByName = Person.order(Col.firstName, Col.lastName).fetchAll(dbQueue) + //: Filter - let millers = Person.filter(Col.lastName == "Miller").fetchAll(db) -} +let streisands = Person.filter(Col.lastName == "Streisand").fetchAll(dbQueue) diff --git a/Playgrounds/Tour.playground/Contents.swift b/Playgrounds/Tour.playground/Contents.swift new file mode 100644 index 000000000..597a755db --- /dev/null +++ b/Playgrounds/Tour.playground/Contents.swift @@ -0,0 +1,123 @@ +//: To run this playground, select and build the GRDBOSX scheme. +//: +//: Tour +//: ====== +//: +//: This playground is a tour of GRDB. + +import GRDB +import CoreLocation + + +//: Open a connection to the database + +// Open an in-memory database that logs all SQL statements +var configuration = Configuration() +configuration.trace = { print($0) } +let dbQueue = DatabaseQueue(configuration: configuration) + + +//: Execute SQL queries + +try dbQueue.execute( + "CREATE TABLE pointOfInterests (" + + "id INTEGER PRIMARY KEY, " + + "title TEXT, " + + "favorite BOOLEAN NOT NULL, " + + "latitude DOUBLE NOT NULL, " + + "longitude DOUBLE NOT NULL" + + ")") + +let parisId = try dbQueue.execute( + "INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " + + "VALUES (?, ?, ?, ?)", + arguments: ["Paris", true, 48.85341, 2.3488]).insertedRowID! + + +//: Fetch database rows and values + +for row in Row.fetchAll(dbQueue, "SELECT * FROM pointOfInterests") { + let title: String = row.value(named: "title") + let favorite: Bool = row.value(named: "favorite") + let coordinate = CLLocationCoordinate2DMake( + row.value(named: "latitude"), + row.value(named: "longitude")) + print("Fetched", title, favorite, coordinate) +} + +let poiCount = Int.fetchOne(dbQueue, "SELECT COUNT(*) FROM pointOfInterests")! // Int +let poiTitles = String.fetchAll(dbQueue, "SELECT title FROM pointOfInterests") // [String] + + +//: Insert and fetch records + +struct PointOfInterest { + var id: Int64? + var title: String? + var favorite: Bool + var coordinate: CLLocationCoordinate2D +} + +// Adopt RowConvertible +extension PointOfInterest : RowConvertible { + init(_ row: Row) { + id = row.value(named: "id") + title = row.value(named: "title") + favorite = row.value(named: "favorite") + coordinate = CLLocationCoordinate2DMake( + row.value(named: "latitude"), + row.value(named: "longitude")) + } +} + +// Adopt TableMapping +extension PointOfInterest : TableMapping { + static func databaseTableName() -> String { + return "pointOfInterests" + } +} + +// Adopt MutablePersistable +extension PointOfInterest : MutablePersistable { + var persistentDictionary: [String: DatabaseValueConvertible?] { + return [ + "id": id, + "title": title, + "favorite": favorite, + "latitude": coordinate.latitude, + "longitude": coordinate.longitude + ] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + id = rowID + } +} + +var berlin = PointOfInterest( + id: nil, + title: "Berlin", + favorite: false, + coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) + +try berlin.insert(dbQueue) +berlin.id // some value + +berlin.favorite = true +try berlin.update(dbQueue) + +// Fetch from SQL +let pois = PointOfInterest.fetchAll(dbQueue, "SELECT * FROM pointOfInterests") // [PointOfInterest] + + +//: Avoid SQL with the query interface: + +let title = SQLColumn("title") +let favorite = SQLColumn("favorite") + +berlin = PointOfInterest.filter(title == "Berlin").fetchOne(dbQueue)! // PointOfInterest +let paris = PointOfInterest.fetchOne(dbQueue, key: 1) // PointOfInterest? +let favoritePois = PointOfInterest // [PointOfInterest] + .filter(favorite) + .order(title) + .fetchAll(dbQueue) diff --git a/Playgrounds/Tour.playground/contents.xcplayground b/Playgrounds/Tour.playground/contents.xcplayground new file mode 100644 index 000000000..fd676d5b4 --- /dev/null +++ b/Playgrounds/Tour.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Playgrounds/Tour.playground/timeline.xctimeline b/Playgrounds/Tour.playground/timeline.xctimeline new file mode 100644 index 000000000..bf468afec --- /dev/null +++ b/Playgrounds/Tour.playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/Playgrounds/TransactionObserver.playground/Contents.swift b/Playgrounds/TransactionObserver.playground/Contents.swift index cd2ce3dd5..c0f49a88d 100644 --- a/Playgrounds/TransactionObserver.playground/Contents.swift +++ b/Playgrounds/TransactionObserver.playground/Contents.swift @@ -53,9 +53,8 @@ class TableChangeObserver : NSObject, TransactionObserverType { // Register observer -dbQueue.inDatabase { db in - db.addTransactionObserver(TableChangeObserver()) -} +let observer = TableChangeObserver() +dbQueue.addTransactionObserver(observer) // diff --git a/Playgrounds/UserDefaults.playground/Contents.swift b/Playgrounds/UserDefaults.playground/Contents.swift index aad798176..c3d3e7d3b 100644 --- a/Playgrounds/UserDefaults.playground/Contents.swift +++ b/Playgrounds/UserDefaults.playground/Contents.swift @@ -2,25 +2,34 @@ import GRDB +// UserDefaults can work with both DatabaseQueue and DatabasePool +public protocol UserDefaultsBackEnd: class, DatabaseReader, DatabaseWriter { } +extension DatabaseQueue : UserDefaultsBackEnd { } +extension DatabasePool : UserDefaultsBackEnd { } +extension Database : UserDefaultsBackEnd { } + /// UserDefaults is a class that behaves like NSUserDefaults. /// /// Usage: /// /// let dbQueue = DatabaseQueue(...) +/// let defaults = UserDefaults.inDatabase(db) +/// +/// defaults.integerForKey("bar") // 0 +/// defaults.setInteger(12, forKey: "bar") +/// defaults.integerForKey("bar") // 12 +/// /// dbQueue.inDatabase { db in /// let defaults = UserDefaults.inDatabase(db) -/// defaults.registerDefaults(["foo": "bar"]) -/// defaults.setInteger(12, forKey: "bar") /// defaults.integerForKey("bar") // 12 /// } public class UserDefaults { - private weak var db: Database! - private var registrationDictionary: [String: AnyObject] = [:] + private weak var db: UserDefaultsBackEnd! private var needsTable: Bool = true private static var registeredDefaults: [UserDefaults] = [] /// Returns the defaults for the database - public static func inDatabase(db: Database) -> UserDefaults { + public static func inDatabase(db: UserDefaultsBackEnd) -> UserDefaults { registeredDefaults = registeredDefaults.filter { $0.db != nil } for defaults in registeredDefaults where defaults.db === db { return defaults } let defaults = UserDefaults(db: db) @@ -28,7 +37,7 @@ public class UserDefaults { return defaults } - private init(db: Database) { + private init(db: UserDefaultsBackEnd) { self.db = db } @@ -39,15 +48,6 @@ public class UserDefaults { } - // MARK: - Registering Defaults - - public func registerDefaults(registrationDictionary: [String: AnyObject]) { - for (key, value) in registrationDictionary { - self.registrationDictionary[key] = value - } - } - - // MARK: - Setting Default Values public func removeObjectForKey(key: String) { @@ -95,7 +95,7 @@ public class UserDefaults { public var dictionaryRepresentation: [String: AnyObject] { createTableIfNeeded() - var dic = registrationDictionary + var dic: [String: AnyObject] = [:] for item in UserDefaultsItem.fetchAll(db) { dic[item.key] = item.value } @@ -132,10 +132,7 @@ public class UserDefaults { public func objectForKey(key: String) -> AnyObject? { createTableIfNeeded() - if let item = UserDefaultsItem.fetchOne(db, key: key) { - return item.value - } - return registrationDictionary[key] + return UserDefaultsItem.fetchOne(db, key: key)?.value } public func stringArrayForKey(key: String) -> [String]? { @@ -181,13 +178,13 @@ private let UserDefaultsItemTableName = "grdb_UserDefaults" // ============================================================ let dbQueue = DatabaseQueue() +let defaults = UserDefaults.inDatabase(dbQueue) + +defaults.integerForKey("bar") // 0 +defaults.setInteger(12, forKey: "bar") +defaults.integerForKey("bar") // 12 + dbQueue.inDatabase { db in let defaults = UserDefaults.inDatabase(db) - - defaults.registerDefaults(["foo": "qux"]) - defaults.stringForKey("foo") // "qux" - - defaults.integerForKey("bar") // 0 - defaults.setInteger(12, forKey: "bar") defaults.integerForKey("bar") // 12 } diff --git a/README.md b/README.md index fd79ebf13..6b3e0b17c 100644 --- a/README.md +++ b/README.md @@ -3,49 +3,63 @@ GRDB.swift GRDB.swift is an SQLite toolkit for Swift 2. -It provides an SQL API and application tools. +It ships with an SQL API, protocols that turn your custom types in ORM-like objects, safe concurrent accesses to the database (that's pretty unique), and a Swift query interface which lets SQL-allergic developers avoid their most dreaded language. -**February 9, 2016: GRDB.swift 0.45.0 is out** ([changelog](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +And it's well-documented, tested, and [fast](https://github.com/groue/GRDB.swift/wiki/Performance). + +You should give it a try. + +--- + +**March 14, 2016: GRDB.swift 0.51.2 is out** ([changelog](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. **Requirements**: iOS 7.0+ / OSX 10.9+, Xcode 7+ ### Usage -Open a connection to the [database](#database-queues): +Open a [connection](#database-connections) to the database: ```swift import GRDB let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") ``` -Execute [SQL queries](#executing-updates): +[Execute SQL statements](#executing-updates): ```swift -try dbQueue.inDatabase { db in - try db.execute( - "CREATE TABLE pointOfInterests (" + - "id INTEGER PRIMARY KEY, " + - "title TEXT, " + - "favorite BOOLEAN NOT NULL, " + - "latitude DOUBLE NOT NULL, " + - "longitude DOUBLE NOT NULL" + - ")") - - let parisId = try db.execute( - "INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " + - "VALUES (?, ?, ?, ?)", - arguments: ["Paris", true, 48.85341, 2.3488]).insertedRowID - - for row in Row.fetch(db, "SELECT * FROM pointOfInterests") { - let title: String = row.value(named: "title") - let favorite: Bool = row.value(named: "favorite") - print(title, favorite) - } -} +try dbQueue.execute( + "CREATE TABLE pointOfInterests (" + + "id INTEGER PRIMARY KEY, " + + "title TEXT, " + + "favorite BOOLEAN NOT NULL, " + + "latitude DOUBLE NOT NULL, " + + "longitude DOUBLE NOT NULL" + + ")") + +let parisId = try dbQueue.execute( + "INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " + + "VALUES (?, ?, ?, ?)", + arguments: ["Paris", true, 48.85341, 2.3488]).insertedRowID ``` -Insert and fetch [Records](#records): +[Fetch database rows and values](#fetch-queries): + +```swift +for row in Row.fetchAll(dbQueue, "SELECT * FROM pointOfInterests") { + let title: String = row.value(named: "title") + let favorite: Bool = row.value(named: "favorite") + let coordinate = CLLocationCoordinate2DMake( + row.value(named: "latitude"), + row.value(named: "longitude")) + print(title, favorite, coordinate) +} + +let poiCount = Int.fetchOne(dbQueue, "SELECT COUNT(*) FROM pointOfInterests")! // Int +let poiTitles = String.fetchAll(dbQueue, "SELECT title FROM pointOfInterests") // [String] +``` + +Insert and fetch [records](#records): ```swift struct PointOfInterest { @@ -58,47 +72,72 @@ struct PointOfInterest { // snip: turn PointOfInterest into a "record" by adopting the protocols that // provide fetching and persistence methods. -try dbQueue.inDatabase { db in - // INSERT INTO "pointOfInterests" ... - var berlin = PointOfInterest(id: nil, title: "Berlin", favorite: false, coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) - try berlin.insert(db) - print(berlin.id) +var berlin = PointOfInterest( + id: nil, + title: "Berlin", + favorite: false, + coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) + +try berlin.insert(dbQueue) +print(berlin.id) // some value + +berlin.favorite = true +try berlin.update(dbQueue) - // UPDATE "pointOfInterests" ... - berlin.favorite = true - try berlin.update(db) - - // Fetch from SQL - let pois = PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests") -} +// Fetch from SQL +let pois = PointOfInterest.fetchAll(dbQueue, "SELECT * FROM pointOfInterests") // [PointOfInterest] ``` -Turn Swift into SQL with the [query interface](#the-query-interface): +Avoid SQL with the [query interface](#the-query-interface): ```swift let title = SQLColumn("title") let favorite = SQLColumn("favorite") -dbQueue.inDatabase { db in - // SELECT * FROM "pointOfInterests" WHERE "title" = 'Paris' - let paris = PointOfInterest.filter(title == "Paris").fetchOne(db) - - // SELECT * FROM "pointOfInterests" WHERE "favorite" ORDER BY "title" - let favoritePois = PointOfInterest.filter(favorite).order(title).fetchAll(db) -} +let paris = PointOfInterest.fetchOne(dbQueue, key: 1) // PointOfInterest? +let berlin = PointOfInterest.filter(title == "Berlin").fetchOne(dbQueue) // PointOfInterest? +let favoritePois = PointOfInterest // [PointOfInterest] + .filter(favorite) + .order(title) + .fetchAll(dbQueue) ``` -### Documentation +Documentation +============= + +**GRDB runs on top of SQLite**: you should get familiar with the [SQLite FAQ](http://www.sqlite.org/faq.html). For general and detailed information, jump to the [SQLite Documentation](http://www.sqlite.org/docs.html). + +**Reference** + +- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/index.html) (on cocoadocs.org) + +**Getting started** -- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.45.0/index.html) (on cocoadocs.org) - [Installation](#installation) -- [SQLite API](#sqlite-api): SQL & SQLite +- [Database Connections](#database-connections): Connect to SQLite databases + +**SQLite and SQL** + +- [SQLite API](#sqlite-api) + +**Application tools** + - [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies. - [Query Interface](#the-query-interface): A swift way to generate SQL. - [Migrations](#migrations): Transform your database as your application evolves. - [Database Changes Observation](#database-changes-observation): Perform post-commit and post-rollback actions. -- [Sample Code](#sample-code) + +**Good to know** + +- [Error Handling](#error-handling) +- [Unicode](#unicode) +- [Memory Management](#memory-management) +- [Concurrency](#concurrency) + +[FAQ](#faq) + +[Sample Code](#sample-code) ### Installation @@ -112,13 +151,13 @@ You can use GRDB in a project targetting iOS7. See [GRDBDemoiOS7](DemoApps/GRDBD [CocoaPods](http://cocoapods.org/) is a dependency manager for Xcode projects. -To use GRDB with Cocoapods, specify in your Podfile: +To use GRDB with CocoaPods, specify in your Podfile: ```ruby source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '~> 0.45.0' +pod 'GRDB.swift', '~> 0.51.2' ``` @@ -129,7 +168,7 @@ pod 'GRDB.swift', '~> 0.45.0' To use GRDB with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" ~> 0.45.0 +github "groue/GRDB.swift" ~> 0.51.2 ``` @@ -143,63 +182,36 @@ github "groue/GRDB.swift" ~> 0.45.0 See [GRDBDemoiOS](DemoApps/GRDBDemoiOS) for an example of such integration. -SQLite API -========== +Database Connections +==================== -**Overview** +GRDB provides two classes for accessing SQLite databases: `DatabaseQueue` and `DatabasePool`. + +Both grant safe database access from any thread of your application. ```swift import GRDB -// Open connection to database +// Pick one: let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") - -try dbQueue.inDatabase { db in - // Create tables - try db.execute("CREATE TABLE wines (...)") - - // Insert - let wineId = try db.execute("INSERT INTO wines (color, name) VALUES (?, ?)", - arguments: [Color.Red, "Pomerol"]).insertedRowID - print("Inserted wine id: \(wineId)") - - // Fetch rows - for row in Row.fetch(db, "SELECT * FROM wines") { - let name: String = row.value(named: "name") - let color: Color = row.value(named: "color") - print(name, color) - } - - // Fetch values - let redWineCount = Int.fetchOne(db, - "SELECT COUNT(*) FROM wines WHERE color = ?", - arguments: [Color.Red])! -} +let dbPool = try DatabasePool(path: "/path/to/database.sqlite") ``` +The differences are: + +- Only database pools allow concurrent database accesses (this can improve the performance of multithreaded applications). +- Unless read-only, database pools open your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html). +- Only database queues can open an in-memory database (without database file). + +**If you are not sure, choose DatabaseQueue.** You will always be able to switch to DatabasePool later. + - [Database Queues](#database-queues) -- [Executing Updates](#executing-updates) -- [Fetch Queries](#fetch-queries) - - [Row Queries](#row-queries) - - [Value Queries](#value-queries) -- [Values](#values) - - [NSData](#nsdata-and-memory-savings) - - [NSDate and NSDateComponents](#nsdate-and-nsdatecomponents) - - [Swift enums](#swift-enums) -- [String Comparison](#string-comparison) -- [Transactions](#transactions) -- [Error Handling](#error-handling) -- Advanced topics: - - [Custom Value Types](#custom-value-types) - - [Prepared Statements](#prepared-statements) - - [Concurrency](#concurrency) - - [Custom SQL Functions](#custom-sql-functions) - - [Raw SQLite Pointers](#raw-sqlite-pointers) +- [Database Pools](#database-pools) ## Database Queues -You access SQLite databases through **database queues** (inspired by [ccgus/fmdb](https://github.com/ccgus/fmdb)): +**Open a database queue** with the path to a database file: ```swift import GRDB @@ -210,86 +222,176 @@ let inMemoryDBQueue = DatabaseQueue() SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated. -**A database queue can be used from any thread.** The `inDatabase` and `inTransaction` methods block the current thread until your database statements are executed: + +**A database queue can be used from any thread.** + +Execute [database updates](#executing-updates), and [fetch](#fetch-queries) arrays or single values: ```swift -// Execute database statements: -dbQueue.inDatabase { db in - for row in Row.fetch(db, "SELECT * FROM wines") { - let name: String = row.value(named: "name") - let color: Color = row.value(named: "color") - print(name, color) - } -} - -// Wrap database statements in a transaction: -try dbQueue.inTransaction { db in - try db.execute("INSERT ...") - try db.execute("DELETE FROM ...") - return .Commit -} - -// Extract values from the database: -let wineCount = dbQueue.inDatabase { db in - Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! -} -print(wineCount) +try dbQueue.execute("CREATE TABLE pointOfInterests (...)") +try PointOfInterest(...).insert(dbQueue) +let pois = PointOfInterest.fetchAll(dbQueue) +let poi = PointOfInterest.fetchOne(dbQueue, key: 1) ``` +You can group statements in [transactions](#transactions). In a multithreaded application, you can isolate a bunch or related statements from concurrent updates: read [Concurrency](#concurrency). -**You can configure databases:** +**Configure database queues:** ```swift var config = Configuration() config.readonly = true config.foreignKeysEnabled = true // The default is already true config.trace = { print($0) } // Prints all SQL statements +config.fileAttributes = [NSFileProtectionKey: ...] // Configure database protection let dbQueue = try DatabaseQueue( path: "/path/to/database.sqlite", configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.45.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Structs/Configuration.html) for more details. -> :bowtie: **Tip**: see [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift) for a sample code that sets up a GRDB database. +> :bowtie: **Tip**: see [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift) for a sample code that sets up a database queue. + + +## Database Pools + +[Database Queues](#database-queues) are simple, but they prevent concurrent accesses: at every moment, there is no more than a single thread that is using the database. + +**A Database Pool can improve your application performance because it allows concurrent database accesses.** + +```swift +import GRDB +let dbPool = try DatabasePool(path: "/path/to/database.sqlite") +``` + +SQLite creates the database file if it does not already exist. The connection is closed when the database pool gets deallocated. + +> :point_up: **Note**: unless read-only, a database pool opens your database in the SQLite "WAL mode". The WAL mode does not fit all situations. Please have a look at https://www.sqlite.org/wal.html. + + +**A database pool can be used from any thread.** + +Execute [database updates](#executing-updates), and [fetch](#fetch-queries) arrays or single values: + +```swift +try dbPool.execute("CREATE TABLE pointOfInterests (...)") +try PointOfInterest(...).insert(dbPool) +let pois = PointOfInterest.fetchAll(dbPool) +let poi = PointOfInterest.fetchOne(dbPool, key: 1) +``` + +You can group statements in [transactions](#transactions). In a multithreaded application, you can isolate a bunch or related statements from concurrent updates: read [Concurrency](#concurrency). + +The total number of concurrent reads is limited. When the maximum number has been reached, a read waits for another read to complete. + +**Configure database pools:** + +```swift +var config = Configuration() +config.readonly = true +config.foreignKeysEnabled = true // The default is already true +config.trace = { print($0) } // Prints all SQL statements +config.fileAttributes = [NSFileProtectionKey: ...] // Configure database protection + +let dbPool = try DatabasePool( + path: "/path/to/database.sqlite", + configuration: config, + maximumReaderCount: 10) // The default is 5 +``` + +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Structs/Configuration.html) for more details. + + +Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. + +> :warning: **Warning**: database pools, although well tested, are still experimental. In particular, the best number of concurrent reads is unknown. Please share the results of your experiments! + + + +SQLite API +========== + +**In this section of the documentation, we will talk SQL only.** Jump to the [query interface](#the-query-interface) if SQL if not your cup of tea. + +Once granted with a [database connection](#database-connections), you can perform SQL requests: + +```swift +// Create tables: +try dbQueue.execute("CREATE TABLE wines (...)") + +// Insert: +let wineId = try dbQueue.execute("INSERT INTO wines (color, name) VALUES (?, ?)", + arguments: [Color.Red, "Pomerol"]).insertedRowID +print("Inserted wine id: \(wineId)") + +// Fetch arrays and single values: +let rows = Row.fetchAll(dbQueue, "SELECT * FROM wines") // [Row] +let redWineCount = Int.fetchOne(dbQueue, "SELECT COUNT(*) FROM wines")! // Int + +// Iterate sequences: +try dbQueue.inDatabase { db in + for row in Row.fetch(db, "SELECT * FROM wines") { + let name: String = row.value(named: "name") + let color: Color = row.value(named: "color") + print(name, color) + } +} +``` + +- [Executing Updates](#executing-updates) +- [Fetch Queries](#fetch-queries) + - [Row Queries](#row-queries) + - [Value Queries](#value-queries) +- [Values](#values) + - [NSData](#nsdata-and-memory-savings) + - [NSDate and NSDateComponents](#nsdate-and-nsdatecomponents) + - [NSNumber and NSDecimalNumber](#nsnumber-and-nsdecimalnumber) + - [Swift enums](#swift-enums) +- [Transactions](#transactions) + +Advanced topics: + +- [Custom Value Types](#custom-value-types) +- [Prepared Statements](#prepared-statements) +- [Custom SQL Functions](#custom-sql-functions) +- [Raw SQLite Pointers](#raw-sqlite-pointers) ## Executing Updates -The `Database.execute` method executes the SQL statements that do not return any database row, such as `CREATE TABLE`, `INSERT`, `DELETE`, `ALTER`, etc. +The `execute` method executes the SQL statements that do not return any database row, such as `CREATE TABLE`, `INSERT`, `DELETE`, `ALTER`, etc. For example: ```swift -try dbQueue.inDatabase { db in - try db.execute( - "CREATE TABLE persons (" + - "id INTEGER PRIMARY KEY," + - "name TEXT NOT NULL," + - "age INT" + - ")") - - try db.execute( - "INSERT INTO persons (name, age) VALUES (:name, :age)", - arguments: ["name": "Barbara", "age": 39]) - - // Join multiple statements with a semicolon: - try db.execute( - "INSERT INTO persons (name, age) VALUES (?, ?); " + - "INSERT INTO persons (name, age) VALUES (?, ?)", - arguments: ["Arthur", 36, "Barbara", 39]) -} +try db.execute( + "CREATE TABLE persons (" + + "id INTEGER PRIMARY KEY," + + "name TEXT NOT NULL," + + "age INT" + + ")") + +try db.execute( + "INSERT INTO persons (name, age) VALUES (:name, :age)", + arguments: ["name": "Barbara", "age": 39]) + +// Join multiple statements with a semicolon: +try db.execute( + "INSERT INTO persons (name, age) VALUES (?, ?); " + + "INSERT INTO persons (name, age) VALUES (?, ?)", + arguments: ["Arthur", 36, "Barbara", 39]) ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the **statements arguments**. You pass arguments in with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, NSDate, Swift enums, etc.). +The `?` and colon-prefixed keys like `:name` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, NSDate, Swift enums, etc.). **After an INSERT statement**, you extract the inserted Row ID from the result of the `execute` method: ```swift let personID = try db.execute( "INSERT INTO persons (name, age) VALUES (?, ?)", - arguments: ["Arthur", 36]).insertedRowID + arguments: ["Arthur", 36]).insertedRowID! ``` Don't miss [Records](#records), that provide classic **persistence methods**: @@ -308,11 +410,10 @@ You can fetch database rows, plain values, and custom models aka "records". **Rows** are the raw results of SQL queries: ```swift -dbQueue.inDatabase { db in - for row in Row.fetch(db, "SELECT * FROM wines") { - let name: String = row.value(named: "name") - let color: Color = row.value(named: "color") - } +for row in Row.fetchAll(db, "SELECT * FROM wines") { + let name: String = row.value(named: "name") + let color: Color = row.value(named: "color") + print(name, color) } ``` @@ -320,22 +421,16 @@ dbQueue.inDatabase { db in **Values** are the Bool, Int, String, NSDate, Swift enums, etc. stored in row columns: ```swift -dbQueue.inDatabase { db in - let wineCount = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! // Int - let urls = NSURL.fetchAll(db, "SELECT url FROM wines") // [NSURL] -} +let wineCount = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! // Int +let urls = NSURL.fetchAll(db, "SELECT url FROM wines") // [NSURL] ``` **Records** are your application objects that can initialize themselves from rows: ```swift -dbQueue.inDatabase { db in - let wines = Wine.fetchAll(db, // [Wine] - "SELECT * FROM wines WHERE origin = ? ORDER BY price", - arguments: ["Burgundy"]) - let favoriteWine = Wine.fetchOne(db, key: favoriteWineID) // Wine? -} +let wines = Wine.fetchAll(db, "SELECT * FROM wines") // [Wine] +let anyWine = Wine.fetchOne(db, "SELECT * FROM wines LIMIT 1") // Wine? ``` - [Fetching Methods](#fetching-methods) @@ -346,17 +441,61 @@ dbQueue.inDatabase { db in ### Fetching Methods -**Throughout GRDB**, values can always be fetched as a *sequence*, as an *array*, or as a *single value*: +**Throughout GRDB**, you can always fetch *sequences*, *arrays*, or *single values* of any fetchable type (database [row](#row-queries), simple [value](#value-queries), or custom [record](#records)): ```swift -Value.fetch(...) // DatabaseSequence -Value.fetchAll(...) // [Value] -Value.fetchOne(...) // Value? +Type.fetch(...) // DatabaseSequence +Type.fetchAll(...) // [Type] +Type.fetchOne(...) // Type? ``` -- `fetch` returns a sequence that is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). The sequence fetches a new set of results each time it is iterated. -- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory. -- `fetchOne` consumes a single database row, if any is available. +- `fetch` returns a **sequence** that is memory efficient, but must be consumed in a protected dispatch queue (you'll get a fatal error if you do otherwise). + + ```swift + dbQueue.inDatabase { db in + for row in Row.fetch(db, "SELECT ...") { ... } + } + dbPool.read { db in + for row in Row.fetch(db, "SELECT ...") { ... } + } + ``` + + Don't modify the database during a sequence iteration: + + ```swift + try dbQueue.inDatabase { db in + // Undefined behavior + for row in Row.fetch(db, "SELECT * FROM persons") { + try db.execute("DELETE FROM persons ...") + } + } + ``` + + A sequence fetches a new set of results each time it is iterated. + +- `fetchAll` returns an **array** that can be fetched and iterated on any thread. It contains copies of database values, and can take a lot of memory. + + Load arrays from database [queues](#database-queues), [pools](#database-pools), or raw databases connections: + + ```swift + let persons = Person.fetchAll(dbQueue, "SELECT ...") // DatabaseQueue + let persons = Person.fetchAll(dbPool, "SELECT ...") // DatabasePool + dbQueue.inDatabase { db in + let persons = Person.fetchAll(db, "SELECT ...") // Database + } + ``` + +- `fetchOne` returns a **single optional value**, and consumes a single database row (if any). + + Like arrays, you can load single values from database [queues](#database-queues), [pools](#database-pools), or raw databases connections: + + ```swift + let count = Int.fetchOne(dbQueue, "SELECT COUNT(*) ...") // DatabaseQueue + let count = Int.fetchOne(dbPool, "SELECT COUNT(*) ...") // DatabasePool + dbQueue.inDatabase { db in + let count = Int.fetchOne(db, "SELECT COUNT(*) ...") // Database + } + ``` ### Row Queries @@ -371,27 +510,25 @@ Value.fetchOne(...) // Value? Fetch **sequences** of rows, **arrays**, or **single** rows (see [fetching methods](#fetching-methods)): ```swift -dbQueue.inDatabase { db in - Row.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence - Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row] - Row.fetchOne(db, "SELECT ...", arguments: ...) // Row? - - for row in Row.fetch(db, "SELECT * FROM wines") { - let name: String = row.value(named: "name") - let color: Color = row.value(named: "color") - print(name, color) - } +Row.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence +Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row] +Row.fetchOne(db, "SELECT ...", arguments: ...) // Row? + +for row in Row.fetch(db, "SELECT * FROM wines") { + let name: String = row.value(named: "name") + let color: Color = row.value(named: "color") + print(name, color) } ``` Arguments are optional arrays or dictionaries that fill the positional `?` and colon-prefixed keys like `:name` in the query: ```swift -let rows = Row.fetch(db, +let rows = Row.fetchAll(db, "SELECT * FROM persons WHERE name = ?", arguments: ["Arthur"]) -let rows = Row.fetch(db, +let rows = Row.fetchAll(db, "SELECT * FROM persons WHERE name = :name", arguments: ["name": "Arthur"]) ``` @@ -424,6 +561,7 @@ The `value` function returns the type you ask for. See [Values](#values) for mor let bookCount: Int = row.value(named: "bookCount") let bookCount64: Int64 = row.value(named: "bookCount") let hasBooks: Bool = row.value(named: "bookCount") // false when 0 + let dateString: String = row.value(named: "date") // "2015-09-11 18:14:15.123" let date: NSDate = row.value(named: "date") // NSDate self.date = row.value(named: "date") // Depends on the type of the property. @@ -448,11 +586,11 @@ Generally speaking, you can extract the type you need, *provided it can be conve - **Successful conversions include:** - - Numeric (integer and real) SQLite values to Swift Int, Int32, Int64, Double and Bool (zero is the only false boolean). + - All numeric (integer and real) SQLite values to Swift Int, Int32, Int64, Double and Bool (zero is the only false boolean). - Text SQLite values to Swift String. - Blob SQLite values to NSData. - See [Values](#values) for more information on supported types (NSDate, Swift enums, etc.). + See [Values](#values) for more information on supported types (Bool, Int, String, NSDate, Swift enums, etc.) - **Invalid conversions return nil.** @@ -555,15 +693,13 @@ for (columnName, databaseValue) in row { ... } // ("foo", 1), ("foo", 2) Instead of rows, you can directly fetch **[values](#values)**. Like rows, fetch them as **sequences**, **arrays**, or **single** values (see [fetching methods](#fetching-methods)). Values are extracted from the leftmost column of the SQL queries: ```swift -dbQueue.inDatabase { db in - Int.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence - Int.fetchAll(db, "SELECT ...", arguments: ...) // [Int] - Int.fetchOne(db, "SELECT ...", arguments: ...) // Int? +Int.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence +Int.fetchAll(db, "SELECT ...", arguments: ...) // [Int] +Int.fetchOne(db, "SELECT ...", arguments: ...) // Int? - // When database may contain NULL: - Optional.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence - Optional.fetchAll(db, "SELECT ...", arguments: ...) // [Int?] -} +// When database may contain NULL: +Optional.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence +Optional.fetchAll(db, "SELECT ...", arguments: ...) // [Int?] ``` `fetchOne` returns an optional value which is nil in two cases: either the SELECT statement yielded no row, or one row with a NULL value. @@ -571,23 +707,8 @@ dbQueue.inDatabase { db in There are many supported value types (Bool, Int, String, NSDate, Swift enums, etc.). See [Values](#values) for more information: ```swift -dbQueue.inDatabase { db in - // The number of persons with an email ending in @example.com: - let count: Int = Int.fetchOne(db, - "SELECT COUNT(*) FROM persons WHERE email LIKE ?", - arguments: ["%@example.com"])! - - // All URLs: - let urls: [NSURL] = NSURL.fetchAll(db, "SELECT url FROM links") - - // The emails of people who own at least two pets: - let emails: [String?] = Optional.fetchAll(db, - "SELECT persons.email " + - "FROM persons " + - "JOIN pets ON pets.masterId = persons.id " + - "GROUP BY persons.id " + - "HAVING COUNT(pets.id) >= 2") -} +let count = Int.fetchOne(db, "SELECT COUNT(*) FROM persons")! // Int +let urls = NSURL.fetchAll(db, "SELECT url FROM links") // [NSURL] ``` @@ -595,13 +716,13 @@ dbQueue.inDatabase { db in GRDB ships with built-in support for the following value types: -- **Swift Standard Library**: Bool, Float, Double, Int, Int32, Int64, String, [Swift enums](#swift-enums). +- **Swift Standard Library**: Bool, Double, Float, Int, Int32, Int64, String, [Swift enums](#swift-enums). -- **Foundation**: [NSData](#nsdata-and-memory-savings), [NSDate](#nsdate-and-nsdatecomponents), [NSDateComponents](#nsdate-and-nsdatecomponents), NSNull, NSNumber, NSString, NSURL. +- **Foundation**: [NSData](#nsdata-and-memory-savings), [NSDate](#nsdate-and-nsdatecomponents), [NSDateComponents](#nsdate-and-nsdatecomponents), NSNull, [NSNumber](#nsnumber-and-nsdecimalnumber), NSString, NSURL. - **CoreGraphics**: CGFloat. -All types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol are supported. +- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. Values can be used as [statement arguments](#executing-updates): @@ -622,7 +743,7 @@ for row in Row.fetch(db, "SELECT * FROM links") { } ``` -Values can be [directly fetched](#value-queries) from the database: +Values can be [directly fetched](#value-queries): ```swift let urls = NSURL.fetchAll(db, "SELECT url FROM links") // [NSURL] @@ -652,7 +773,6 @@ Use values in the [query interface](#the-query-interface): ```swift let url = NSURL(string: "http://example.com")! let link = Link.filter(Col.url == url).fetchOne(db) -let urlCount = Int.fetchOne(db, Link.select(count(distinct: Col.url)))! ``` @@ -668,7 +788,7 @@ for row in Row.fetch(db, "SELECT data, ...") { } ``` -> :point_up: **Note**: The non-copied data does not live longer than the iteration step: make sure that you do not use it past this point. +> :point_up: **Note**: the non-copied data does not live longer than the iteration step: make sure that you do not use it past this point. Compare with the **anti-patterns** below: @@ -765,9 +885,52 @@ dbComponents.dateComponents // NSDateComponents ``` +### NSNumber and NSDecimalNumber + +While NSNumber deserves no special discussion, NSDecimalNumber does. + +**SQLite has no support for decimal numbers.** Given the table below, SQLite will actually store integers or doubles: + +```sql +CREATE TABLE transfers ( + amount DECIMAL(10,5) -- will store integer or double, actually +) +``` + +This means that computations will not be exact: + +```swift +try db.execute("INSERT INTO transfers (amount) VALUES (0.1)") +try db.execute("INSERT INTO transfers (amount) VALUES (0.2)") +let sum = NSDecimalNumber.fetchOne(db, "SELECT SUM(amount) FROM transfers")! + +// Yikes! 0.3000000000000000512 +print(sum) +``` + +Don't blame SQLite or GRDB, and instead store your decimal numbers differently. + +A classic technique is to store *integers* instead, since SQLite performs exact computations of integers. For example, don't store Euros, but store cents instead: + +```swift +// Store +let amount = NSDecimalNumber(string: "0.1") +let integerAmount = amount + .decimalNumberByMultiplyingByPowerOf10(2) + .longLongValue +// INSERT INTO transfers (amount) VALUES (100) +try db.execute("INSERT INTO transfers (amount) VALUES (?)", arguments: [integerAmount]) + +// Read +let integerAmount = Int64.fetchOne(db, "SELECT SUM(amount) FROM transfers")! +let amount = NSDecimalNumber(longLong: integerAmount) + .decimalNumberByMultiplyingByPowerOf10(-2) +``` + + ### Swift Enums -**Swift enums** get full support from GRDB as long as their raw values are Int, Int32, Int64 or String: +**Swift enums** get full support from GRDB as long as their raw values are supported (Int, Int32, Int64 or String): ```swift enum Color : Int { @@ -779,11 +942,11 @@ enum Grape : String { } ``` -Add conformance to a protocol, and the enum type can be stored and fetched from the database just like other [value types](#values): +Declare adoption of the `DatabaseValueConvertible` protocol, and the enum type can be stored and fetched from the database just like other [value types](#values): ```swift -extension Color : DatabaseIntRepresentable { } // DatabaseInt32Representable for Int32, DatabaseInt64Representable for Int64 -extension Grape : DatabaseStringRepresentable { } +extension Color : DatabaseValueConvertible { } +extension Grape : DatabaseValueConvertible { } // Store try db.execute("INSERT INTO wines (grape, color) VALUES (?, ?)", @@ -806,62 +969,9 @@ row.value(atIndex: 0) as Grape // fatal error: could not convert "Syrah" to Gr ``` -## String Comparison - -SQLite compares strings in many occasions: when you sort rows according to a string column, or when you use a comparison operator such as `=` and `<=`. - -The comparison result comes from a *collating function*, or *collation*. SQLite comes with [three built-in collations](https://www.sqlite.org/datatype3.html#collation): - -- `binary`, the default, which considers "Foo" and "foo" to be inequal, and "Jérôme" and "Jerome" to be inequal because it has no Unicode support. -- `nocase`, which considers "Foo" and "foo" to be equal, but "Jérôme" and "Jerome" to be inequal because it has no Unicode support. -- `rtrim`: the same as `binary`, except that trailing space characters are ignored. - -**You can define your own collations**, based on the rich set of Swift string comparisons: - -```swift -let collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in - return (lhs as NSString).localizedCaseInsensitiveCompare(rhs) -} - -dbQueue.inDatabase { db in - db.addCollation(collation) -} -``` - -Once defined, the custom collation can be applied to a table column. All comparisons involving this column will automatically trigger your comparison function: - -```swift -dbQueue.inDatabase { db in - // Apply the custom collation to the `name` column - try db.execute( - "CREATE TABLE persons (" + - "name TEXT COLLATE localized_case_insensitive" + // The name of the collation - ")") - - // Persons are sorted as expected: - let persons = Person.order(name).fetchAll(db) - - // Matches "Jérôme", "jerome", etc. - let persons = Person.filter(name == "Jérôme").fetchAll(db) -} -``` - -If you can't or don't want to define the comparison behavior of a column, you can still use an explicit collation on particular requests: - -```swift -// SELECT * FROM "persons" WHERE ("name" = 'foo' COLLATE NOCASE) -let persons = Person.filter(name.collating("NOCASE") == "foo").fetchAll(db) - -// SELECT * FROM "persons" WHERE ("name" = 'Jérôme' COLLATE localized_case_insensitive) -let persons = Person.filter(name.collating(collation) == "Jérôme").fetchAll(db) -``` - -See the [query interface](#the-query-interface) for more information. - - ## Transactions -The `DatabaseQueue.inTransaction()` method opens an SQLite transaction: +The `DatabaseQueue.inTransaction()` and `DatabasePool.writeInTransaction()` methods open an SQLite transaction and run their closure argument in a protected dispatch queue. They block the current thread until your database statements are executed: ```swift try dbQueue.inTransaction { db in @@ -873,12 +983,10 @@ try dbQueue.inTransaction { db in A ROLLBACK statement is issued if an error is thrown within the transaction block. -Otherwise, transactions are guaranteed to succeed, *provided there is a single DatabaseQueue connected to the database file*. See [Concurrency](#concurrency) for more information about concurrent database access. - -If you want to insert a transaction between other database statements, and group those in a single block of code protected by the database queue, you can use the Database.inTransaction() function: +If you want to insert a transaction between other database statements, you can use the Database.inTransaction() function: ```swift -try dbQueue.inDatabase { db in +try dbQueue.inDatabase { db in // or dbPool.write { db in ... try db.inTransaction { ... @@ -905,74 +1013,6 @@ dbQueue.inTransaction(.Exclusive) { db in ... } ``` -## Error Handling - -**No SQLite error goes unnoticed.** - -When an [SQLite error](https://www.sqlite.org/rescode.html) happens, some GRDB functions throw a DatabaseError, and some crash with a fatal error: - -```swift -// fatal error: -// SQLite error 1 with statement `SELECT foo FROM bar`: no such table: bar -Row.fetchAll(db, "SELECT foo FROM bar") - -do { - try db.execute( - "INSERT INTO pets (masterId, name) VALUES (?, ?)", - arguments: [1, "Bobby"]) -} catch let error as DatabaseError { - // SQLite error 19 with statement `INSERT INTO pets (masterId, name) - // VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed - error.description - - // The SQLite result code: 19 (SQLITE_CONSTRAINT) - error.code - - // The eventual SQLite message - // "FOREIGN KEY constraint failed" - error.message - - // The eventual erroneous SQL query - // "INSERT INTO pets (masterId, name) VALUES (?, ?)" - error.sql -} -``` - - -**Fatal errors can be avoided.** For example, let's consider the code below: - -```swift -let sql = "..." -let arguments: NSDictionary = ... -let rows = Row.fetchAll(db, sql, arguments: StatementArguments(arguments)) -``` - -It has many opportunities to fail: - -- The sql string may contain invalid sql, or refer to non-existing tables or columns. -- The arguments dictionary may contain unsuitable values. -- The arguments dictionary may miss values required by the statement. - -Compare with the safe version: - -```swift -// Dictionary arguments may contain invalid values: -if let arguments = StatementArguments(arguments) { - - // SQL may be invalid - let statement = try db.selectStatement(sql) - - // Arguments may not fit the statement - try statement.validateArguments(arguments) - - // OK now - let rows = Row.fetchAll(statement, arguments: arguments) -} -``` - -See [prepared statements](#prepared-statements) for more information. - - ## Custom Value Types Conversion to and from the database is based on the `DatabaseValueConvertible` protocol: @@ -1015,10 +1055,7 @@ try dbQueue.inDatabase { db in The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type StatementArguments, which happens to adopt the ArrayLiteralConvertible and DictionaryLiteralConvertible protocols). ```swift -// INSERT INTO persons (name, age) VALUES (:name, :age) updateStatement.arguments = ["name": "Arthur", "age": 41] - -// SELECT * FROM persons WHERE name = ? selectStatement.arguments = ["Arthur"] ``` @@ -1028,61 +1065,26 @@ After arguments are set, you can execute the prepared statement: let changes = try updateStatement.execute() changes.changedRowCount // The number of rows changed by the statement. changes.insertedRowID // For INSERT statements, the inserted Row ID. - -for row in Row.fetch(selectStatement) { ... } -for person in Person.fetch(selectStatement) { ... } ``` -It is possible to set the arguments at the moment of the statement execution: +Select statements can be used wherever a raw SQL query string would fit (see [fetch queries](#fetch-queries)): ```swift -// INSERT INTO persons (name, age) VALUES (:name, :age) -try statement.execute(arguments: ["name": "Arthur", "age": 41]) +for row in Row.fetch(selectStatement) { ... } +let persons = Person.fetchAll(selectStatement) +let person = Person.fetchOne(selectStatement) +``` -// SELECT * FROM persons WHERE name = ? +You can set the arguments at the moment of the statement execution: + +```swift +try updateStatement.execute(arguments: ["name": "Arthur", "age": 41]) let person = Person.fetchOne(selectStatement, arguments: ["Arthur"]) ``` -Select statements can be used wherever a raw SQL query would fit (see [fetch queries](#fetch-queries)): - -```swift -Row.fetch(statement, arguments: ...) // DatabaseSequence -Row.fetchAll(statement, arguments: ...) // [Row] -Row.fetchOne(statement, arguments: ...) // Row? - -String.fetch(statement, arguments: ...) // DatabaseSequence -String.fetchAll(statement, arguments: ...) // [String] -String.fetchOne(statement, arguments: ...) // String? - -Optional.fetch(statement, arguments: ...) // DatabaseSequence -Optional.fetchAll(statement, arguments: ...) // [String?] - -Person.fetch(statement, arguments: ...) // DatabaseSequence -Person.fetchAll(statement, arguments: ...) // [Person] -Person.fetchOne(statement, arguments: ...) // Person? -``` - See [row queries](#row-queries), [value queries](#value-queries), and [Records](#records) for more information. -## Concurrency - -**When your application has a single DatabaseQueue connected to the database file, it has no concurrency issue.** That is because all your database statements are executed in a single serial dispatch queue that is connected alone to the database. - -**Things turn more complex as soon as there are several connections to a database file.** - -SQLite concurrency management is fragmented. Documents of interest include: - -- General discussion about isolation in SQLite: https://www.sqlite.org/isolation.html -- Types of locks and transactions: https://www.sqlite.org/lang_transaction.html -- WAL journal mode: https://www.sqlite.org/wal.html -- Busy handlers: https://www.sqlite.org/c3ref/busy_handler.html - -By default, GRDB opens database in the **default journal mode**, uses **IMMEDIATE transactions**, and registers **no busy handler** of any kind. - -See [Configuration](GRDB/Core/Configuration.swift) type and [DatabaseQueue.inTransaction()](GRDB/Core/DatabaseQueue.swift) method for more precise handling of transactions and eventual SQLITE_BUSY errors. - - ## Custom SQL Functions **SQLite lets you define SQL functions.** @@ -1090,25 +1092,23 @@ See [Configuration](GRDB/Core/Configuration.swift) type and [DatabaseQueue.inTra You can for example use the Unicode support of Swift strings, and go beyond the ASCII limitations of the built-in SQLite `upper()` function: ```swift -dbQueue.inDatabase { db in - let unicodeUpper = DatabaseFunction( - "unicodeUpper", // The name of the function - argumentCount: 1, // Number of arguments - pure: true, // True means that the result only depends on input - function: { (databaseValues: [DatabaseValue]) in - guard let string: String = databaseValues[0].value() else { - return nil - } - return string.uppercaseString }) - - db.addFunction(unicodeUpper) - - // "JÉRÔME" - String.fetchOne(db, "SELECT unicodeUpper(?)", arguments: ["Jérôme"])! - - // "JéRôME" - String.fetchOne(db, "SELECT upper(?)", arguments: ["Jérôme"])! -} +let unicodeUpper = DatabaseFunction( + "unicodeUpper", // The name of the function + argumentCount: 1, // Number of arguments + pure: true, // True means that the result only depends on input + function: { (databaseValues: [DatabaseValue]) in + guard let string: String = databaseValues[0].value() else { + return nil + } + return string.uppercaseString + }) +dbQueue.addFunction(unicodeUpper) // Or dbPool.addFunction(...) + +// "JÉRÔME" +String.fetchOne(dbQueue, "SELECT unicodeUpper(?)", arguments: ["Jérôme"])! + +// "JéRôME" +String.fetchOne(dbQueue, "SELECT upper(?)", arguments: ["Jérôme"])! ``` The *function* argument takes an array of [DatabaseValue](#rows-as-dictionaries), and returns any valid [value](#values) (Bool, Int, String, NSDate, Swift enums, etc.) The number of database values is guaranteed to be *argumentCount*. @@ -1121,39 +1121,35 @@ SQLite has the opportunity to perform additional optimizations when functions ar When you don't provide any explicit *argumentCount*, the function can take any number of arguments: ```swift -dbQueue.inDatabase { db in - let averageOf = DatabaseFunction("averageOf", pure: true) { (databaseValues: [DatabaseValue]) in - let doubles: [Double] = databaseValues.flatMap { $0.value() } - return doubles.reduce(0, combine: +) / Double(doubles.count) - } - db.addFunction(averageOf) - - // 2.0 - Double.fetchOne(db, "SELECT averageOf(1, 2, 3)")! +let averageOf = DatabaseFunction("averageOf", pure: true) { (databaseValues: [DatabaseValue]) in + let doubles: [Double] = databaseValues.flatMap { $0.value() } + return doubles.reduce(0, combine: +) / Double(doubles.count) } +dbQueue.addFunction(averageOf) + +// 2.0 +Double.fetchOne(dbQueue, "SELECT averageOf(1, 2, 3)")! ``` **Functions can throw:** ```swift -dbQueue.inDatabase { db in - let sqrt = DatabaseFunction("sqrt", argumentCount: 1, pure: true) { (databaseValues: [DatabaseValue]) in - let dbv = databaseValues[0] - guard let double: Double = dbv.value() else { - return nil - } - guard double >= 0.0 else { - throw DatabaseError(message: "Invalid negative value in function sqrt()") - } - return sqrt(double) +let sqrt = DatabaseFunction("sqrt", argumentCount: 1, pure: true) { (databaseValues: [DatabaseValue]) in + let dbv = databaseValues[0] + guard let double: Double = dbv.value() else { + return nil } - db.addFunction(sqrt) - - // fatal error: SQLite error 1 with statement `SELECT sqrt(-1)`: - // Invalid negative value in function sqrt() - Double.fetchOne(db, "SELECT sqrt(-1)") + guard double >= 0.0 else { + throw DatabaseError(message: "Invalid negative value in function sqrt()") + } + return sqrt(double) } +dbQueue.addFunction(sqrt) + +// fatal error: SQLite error 1 with statement `SELECT sqrt(-1)`: +// Invalid negative value in function sqrt() +Double.fetchOne(dbQueue, "SELECT sqrt(-1)") ``` See [error handling](#error-handling) for more information on database errors. @@ -1209,6 +1205,8 @@ Before jumping in the low-level wagon, here is a reminder of SQLite APIs support - [sqlite3_update_hook](https://www.sqlite.org/c3ref/update_hook.html) - [sqlite3_commit_hook](https://www.sqlite.org/c3ref/commit_hook.html) - [sqlite3_rollback_hook](https://www.sqlite.org/c3ref/commit_hook.html) +- Authorizations callbacks are *reserved* by GRDB: + - [sqlite3_set_authorizer](https://www.sqlite.org/c3ref/set_authorizer.html) Application Tools @@ -1237,12 +1235,10 @@ To insert a record in the database, subclass the [Record](#record-class) class o class Person : Record { ... } let person = Person(name: "Arthur", email: "arthur@example.com") -try dbQueue.inDatabase { db in - try person.insert(db) -} +try person.insert(db) ``` -Of course, you need to open a [database connection](#database-queues), and [create a database table](#executing-updates) first. +Of course, you need to open a [database connection](#database-connections), and [create a database table](#executing-updates) first. #### Fetching Records @@ -1251,17 +1247,14 @@ Of course, you need to open a [database connection](#database-queues), and [crea ```swift class Person : Record { ... } +let persons = Person.fetchAll(db, "SELECT ...", arguments: ...) +``` -dbQueue.inDatabase { db in - // Using the query interface - let persons = Person.filter(email != nil).order(name).fetchAll(db) - - // By key - let person = Person.fetchOne(db, key: 1) - - // Using SQL - let persons = Person.fetchAll(db, "SELECT ...", arguments: ...) -} +Add the [TableMapping](#tablemapping-protocol) protocol and you can stop writing SQL: + +```swift +let persons = Person.filter(email != nil).order(name).fetchAll(db) +let person = Person.fetchOne(db, key: 1) ``` To learn more about querying records, check the [query interface](#the-query-interface). @@ -1272,31 +1265,25 @@ To learn more about querying records, check the [query interface](#the-query-int [Record](#record-class) subclasses and types that adopt the [Persistable](#persistable-protocol) protocol can be updated in the database: ```swift -try dbQueue.inDatabase { db in - let person = Person.fetchOne(db, key: 1)! - person.name = "Arthur" - try person.update(db) -} +let person = Person.fetchOne(db, key: 1)! +person.name = "Arthur" +try person.update(db) ``` [Record](#record-class) subclasses track changes: ```swift -try dbQueue.inDatabase { db in - let person = Person.fetchOne(db, key: 1)! - person.name = "Arthur" - if person.hasPersistentChangedValues { - try person.update(db) - } +let person = Person.fetchOne(db, key: 1)! +person.name = "Arthur" +if person.hasPersistentChangedValues { + try person.update(db) } ``` For batch updates, you have to execute an [SQL query](#executing-updates): ```swift -try dbQueue.inDatabase { db in - try db.execute("UPDATE persons SET synchronized = 1") -} +try db.execute("UPDATE persons SET synchronized = 1") ``` @@ -1305,18 +1292,14 @@ try dbQueue.inDatabase { db in [Record](#record-class) subclasses and types that adopt the [Persistable](#persistable-protocol) protocol can be deleted from the database: ```swift -try dbQueue.inDatabase { db in - let person = Person.fetchOne(db, key: 1)! - try person.delete(db) -} +let person = Person.fetchOne(db, key: 1)! +try person.delete(db) ``` For batch deletions, you have to execute an [SQL query](#executing-updates): ```swift -try dbQueue.inDatabase { db in - try db.execute("DELETE FROM persons") -} +try db.execute("DELETE FROM persons") ``` @@ -1325,9 +1308,7 @@ try dbQueue.inDatabase { db in [Record](#record-class) subclasses and types that adopt the [TableMapping](#tablemapping-protocol) protocol can be counted: ```swift -let personWithEmailCount = dbQueue.inDatabase { db in - Person.filter(email != nil).fetchCount(db) // Int -} +let personWithEmailCount = Person.filter(email != nil).fetchCount(db) // Int ``` @@ -1365,7 +1346,7 @@ struct PointOfInterest { } extension PointOfInterest : RowConvertible { - init(_ row: Row){ + init(_ row: Row) { id = row.value(named: "id") title = row.value(named: "title") coordinate = CLLocationCoordinate2DMake( @@ -1377,7 +1358,7 @@ extension PointOfInterest : RowConvertible { See [column values](#column-values) for more information about the `row.value()` method. -> :point_up: **Note**: For performance reasons, the same row argument to `init(_:Row)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. +> :point_up: **Note**: for performance reasons, the same row argument to `init(_:Row)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. RowConvertible allows adopting types to be fetched from SQL queries: @@ -1413,9 +1394,7 @@ extension PointOfInterest : TableMapping { Adopting types can be fetched using the [query interface](#the-query-interface): ```swift -let paris = dbQueue.inDatabase { db in - PointOfInterest.filter(name == "Paris").fetchOne(db)? -} +let paris = PointOfInterest.filter(name == "Paris").fetchOne(db) ``` You can also fetch records according to their primary key (see [fetching methods](#fetching-methods)): @@ -1429,14 +1408,17 @@ PointOfInterest.fetchOne(db, key: ...) // PointOfInterest? Any single-column primary key is OK: ```swift -// SELECT * FROM pointOfInterests WHERE id IN (1, 2, 3) -PointOfInterest.fetchAll(db, keys: [1, 2, 3]) +// SELECT * FROM persons WHERE id = 1 +Person.fetchOne(db, key: 1) // Person? -// SELECT * FROM pointOfInterests WHERE id = 1 -PointOfInterest.fetchOne(db, key: 1) +// SELECT * FROM persons WHERE id IN (1, 2, 3) +Person.fetchAll(db, keys: [1, 2, 3]) // [Person] -// SELECT * FROM countries WHERE isoCode = 'FR' -Country.fetchOne(db, key: "FR") +// 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] ``` @@ -1472,6 +1454,8 @@ Yes, two protocols instead of one. Both grant exactly the same advantages. Here The `persistentDictionary` property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information. +The `didInsertWithRowID` method is called in a protected dispatch queue. + **To use those protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitely. For example: ```swift @@ -1497,10 +1481,8 @@ var paris = PointOfInterest( title: "Paris", coordinate: CLLocationCoordinate2DMake(48.8534100, 2.3488000)) -try dbQueue.inDatabase { db in - try paris.insert(db) - paris.id // some value -} +try paris.insert(db) +paris.id // some value ``` @@ -1509,13 +1491,23 @@ try dbQueue.inDatabase { db in [Record](#record-class) subclasses and types that adopt [Persistable](#persistable-protocol) are given default implementations for methods that insert, update, and delete: ```swift -try object.insert(db) // INSERT -try object.update(db) // UPDATE -try object.save(db) // Inserts or updates -try object.delete(db) // DELETE -object.exists(db) // Bool +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 ``` +- The argument of persistence methods is any object able to write in a database: + + ```swift + pointOfInterest.insert(dbQueue) // DatabaseQueue + pointOfInterest.insert(dbPool) // DatabasePool + dbQueue.inDatabase { db in + pointOfInterest.insert(db) // Database + } + ``` + - `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. - `update` can also throw a PersistenceError of type NotFound, should the update fail because there is no matching row in the database. @@ -1537,7 +1529,7 @@ When you subclass [Record](#record-class), you simply have to override the custo class Person : Record { var uuid: String? - override func insert(db: Database) throws { + override func insert(db: DatabaseWriter) throws { if uuid == nil { uuid = NSUUID().UUIDString } @@ -1552,12 +1544,12 @@ If you use the raw [Persistable](#persistable-protocol) protocol, use one of the struct Link : Persistable { var url: NSURL - func insert(db: Database) throws { + func insert(db: DatabaseWriter) throws { try validate() try performInsert(db) } - func update(db: Database) throws { + func update(db: DatabaseWriter) throws { try validate() try performUpdate(db) } @@ -1570,9 +1562,9 @@ struct Link : Persistable { } ``` -> :point_up: **Note**: The special methods `performInsert`, `performUpdate`, etc. are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. +> :point_up: **Note**: the special methods `performInsert`, `performUpdate`, etc. are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. > -> :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`. +> :point_up: **Note**: it is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`. ### Record Class @@ -1632,7 +1624,7 @@ class PointOfInterest : Record { } /// Update record ID after a successful insertion - func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + override func didInsertWithRowID(rowID: Int64, forColumn column: String?) { id = rowID } } @@ -1643,46 +1635,38 @@ class PointOfInterest : Record { ```swift let poi = PointOfInterest(...) -try dbQueue.inDatabase { db in - try poi.insert(db) -} +try poi.insert(db) ``` **Fetch records** (see [RowConvertible](#rowconvertible-protocol) and the [query interface](#the-query-interface)): ```swift -dbQueue.inDatabase { db in - // Using the query interface - let pois = PointOfInterest.order(title).fetchAll(db) - - // By key - let poi = PointOfInterest.fetchOne(db, key: 1) - - // Using SQL - let pois = PointOfInterest.fetchAll(db, "SELECT ...", arguments: ...) -} +// Using the query interface +let pois = PointOfInterest.order(title).fetchAll(db) + +// By key +let poi = PointOfInterest.fetchOne(db, key: 1) + +// Using SQL +let pois = PointOfInterest.fetchAll(db, "SELECT ...", arguments: ...) ``` **Update records** (see [persistence methods](#persistence-methods)): ```swift -try dbQueue.inDatabase { db in - let poi = PointOfInterest.fetchOne(db, key: 1)! - poi.coordinate = ... - try poi.update(db) -} +let poi = PointOfInterest.fetchOne(db, key: 1)! +poi.coordinate = ... +try poi.update(db) ``` **Delete records** (see [persistence methods](#persistence-methods)): ```swift -try dbQueue.inDatabase { db in - let poi = PointOfInterest.fetchOne(db, key: 1)! - try poi.delete(db) -} +let poi = PointOfInterest.fetchOne(db, key: 1)! +try poi.delete(db) ``` @@ -1726,24 +1710,29 @@ For an efficient algorithm which synchronizes the content of a database table wi **The query interface lets you write pure Swift instead of SQL:** ```swift +let redWineCount = Wine.filter(color == Color.Red).fetchCount(db) let wines = Wine.filter(origin == "Burgundy").order(price).fetchAll(db) ``` -Please bear in mind that the query interface can not generate all possible SQL queries. You may also *prefer* writing SQL: +Please bear in mind that the query interface can not generate all possible SQL queries. You may also *prefer* writing SQL, and this is just OK: ```swift +let redWineCount = Int.fetchOne(db, + "SELECT COUNT(*) FROM wines WHERE color = ?", + arguments [Color.Red])! let wines = Wine.fetchAll(db, "SELECT * FROM wines WHERE origin = ? ORDER BY price", arguments: ["Burgundy"]) ``` -So don't miss the [SQL API](#fetch-queries). +So don't miss the [SQL API](#sqlite-api). - [Requests](#requests) - [Expressions](#expressions) - [SQL Operators](#sql-operators) - [SQL Functions](#sql-functions) - [Fetching from Requests](#fetching-from-requests) +- [Fetching by Primary Key](#fetching-by-primary-key) - [Fetching Aggregated Values](#fetching-aggregated-values) @@ -1752,11 +1741,7 @@ So don't miss the [SQL API](#fetch-queries). Everything starts from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): ```swift -class Person: Record { - static func databaseTableName() -> String { - return "persons" - } -} +class Person: Record { ... } ``` Declare the table **columns** that you want to use for filtering, or sorting: @@ -1994,7 +1979,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: // SELECT * FROM "events" // WHERE ("userId" IN (SELECT "id" FROM "persons" WHERE "verified")) let verifiedUsers = User.filter(Col.verified) - Event.filter(verifiedPersonIds.select(Col.id).contains(Col.userId)) + Event.filter(verifiedUsers.select(Col.id).contains(Col.userId)) ``` - `EXISTS (subquery)`, `NOT EXISTS (subquery)` @@ -2066,15 +2051,13 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Once you have a request, you can fetch the records at the origin of the request: ```swift -dbQueue.inDatabase { db in - // Some request based on `Person` - let request = Person.filter(...)... - - // Fetch persons: - request.fetch(db) // DatabaseSequence - request.fetchAll(db) // [Person] - request.fetchOne(db) // Person? -} +// Some request based on `Person` +let request = Person.filter(...)... + +// Fetch persons: +request.fetch(db) // DatabaseSequence +request.fetchAll(db) // [Person] +request.fetchOne(db) // Person? ``` See [fetching methods](#fetching-methods) for information about the `fetch`, `fetchAll` and `fetchOne` methods. @@ -2082,98 +2065,74 @@ See [fetching methods](#fetching-methods) for information about the `fetch`, `fe For example: ```swift -for person in Person.filter(Col.name != nil).fetch(db) { - print(person) -} -let allPersons = Person.fetchAll(db) // [Person] -let arthur = Person.filter(Col.name == "Arthur").fetchOne(db) // Person? +let allPersons = Person.fetchAll(db) // [Person] +let arthur = Person.filter(Col.name == "Arthur").fetchOne(db) // Person? ``` -**When the selected columns don't fit the source type**, you just have to change your target: any other type that adopts the [RowConvertible](#rowconvertible-protocol) protocol, plain [database rows](#column-values), and even [values](#values): +**When the selected columns don't fit the source type**, change your target: any other type that adopts the [RowConvertible](#rowconvertible-protocol) protocol, plain [database rows](#fetching-rows), and even [values](#values): ```swift -dbQueue.inDatabase { db in - let request = Person.... - - // Alternative records: - Other.fetch(db, request) // DatabaseSequence - Other.fetchAll(db, request) // [Other] - Other.fetchOne(db, request) // Other? - - // Rows: - Row.fetch(db, request) // DatabaseSequence - Row.fetchAll(db, request) // [Row] - Row.fetchOne(db, request) // Row? - - // Values: - Int.fetch(db, request) // DatabaseSequence - Int.fetchAll(db, request) // [Int] - Int.fetchOne(db, request) // Int? -} -``` - -For example: - -```swift -// Int +// Double let request = Person.select(min(Col.height)) -let minHeight = Int.fetchOne(db, request)! +let minHeight = Double.fetchOne(db, request)! // Row let request = Person.select(min(Col.height), max(Col.height)) let row = Row.fetchOne(db, request)! -let minHeight = row.value(atIndex: 0) as Int -let maxHeight = row.value(atIndex: 1) as Int +let minHeight = row.value(atIndex: 0) as Double +let maxHeight = row.value(atIndex: 1) as Double ``` -See [column values](#column-values) for more information about the `row.value()` method. + +### Fetching By Primary Key **Fetching records according to their primary key** is a very common task. It has a shortcut which accepts any single-column primary key: ```swift // SELECT * FROM persons WHERE id = 1 -Person.fetchOne(db, key: 1)! +Person.fetchOne(db, key: 1) // Person? // SELECT * FROM persons WHERE id IN (1, 2, 3) -Person.fetchAll(db, keys: [1, 2, 3])! +Person.fetchAll(db, keys: [1, 2, 3]) // [Person] // SELECT * FROM persons WHERE isoCode = 'FR' -Country.fetchOne(db, key: "FR")! +Country.fetchOne(db, key: "FR") // Country? // SELECT * FROM countries WHERE isoCode IN ('FR', 'US') -Country.fetchAll(db, keys: ["FR", "US"])! +Country.fetchAll(db, keys: ["FR", "US"]) // [Country] ``` ### Fetching Aggregated Values -**Requests can count:** +**Requests can count.** The `fetchCount()` method returns the number of rows that would be returned by a fetch request: ```swift -dbQueue.inDatabase { db in - // SELECT COUNT(*) FROM "persons" - let count = Person.fetchCount(db) // Int - - // SELECT COUNT(*) FROM "persons" WHERE "email" IS NOT NULL - let count = Person.filter(Col.email != nil).fetchCount(db) // Int -} +// SELECT COUNT(*) FROM "persons" +let count = Person.fetchCount(db) // Int + +// SELECT COUNT(*) FROM "persons" WHERE "email" IS NOT NULL +let count = Person.filter(Col.email != nil).fetchCount(db) + +// SELECT COUNT(DISTINCT "name") FROM "persons" +let count = Person.select(Col.name).distinct.fetchCount(db) + +// SELECT COUNT(*) FROM (SELECT DISTINCT "name", "age" FROM "persons") +let count = Person.select(Col.name, Col.age).distinct.fetchCount(db) ``` -Other aggregated values can also be selected and fetched (see [SQL Functions](#sql-functions)): + +**Other aggregated values** can also be selected and fetched (see [SQL Functions](#sql-functions)): ```swift -dbQueue.inDatabase { db in - // SELECT MIN("age") FROM "persons" - let request = Person.select(min(Col.age)) - let minAge = Int.fetchOne(db, request) // Int? - - // SELECT MIN("height"), MAX("height") FROM "persons" - let request = Person.select(min(Col.height), max(Col.height)) - let row = Row.fetchOne(db, request)! - let minHeight = row.value(atIndex: 0) as Int? - let maxHeight = row.value(atIndex: 1) as Int? -} +let request = Person.select(min(Col.height)) +let minHeight = Double.fetchOne(db, request) // Int? + +let request = Person.select(min(Col.height), max(Col.height)) +let row = Row.fetchOne(db, request)! +let minHeight = row.value(atIndex: 0) as Double? +let maxHeight = row.value(atIndex: 1) as Double? ``` @@ -2207,7 +2166,7 @@ migrator.registerMigration("AddBirthDateToPersons") { db in // "ALTER TABLE books ADD COLUMN year INT") // } -try migrator.migrate(dbQueue) +try migrator.migrate(dbQueue) // or dbPool ``` **Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`. @@ -2258,13 +2217,11 @@ public protocol TransactionObserverType : class { } ``` -To activate a transaction observer, add it to the database: +To activate a transaction observer, add it to the database queue or pool: ```swift let observer = MyObserver() -dbQueue.inDatabase { db in - db.addTransactionObserver(observer) -} +dbQueue.addTransactionObserver(observer) ``` Database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. @@ -2290,10 +2247,8 @@ try dbQueue.inTransaction { db in Database statements that are executed outside of an explicit transaction do not drop off the radar: ```swift -try dbQueue.inDatabase { db in - try db.execute("INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit - try db.execute("UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit -} +try db.execute("INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit +try db.execute("UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit ``` **Eventual errors** thrown from `databaseWillCommit` are exposed to the application code: @@ -2309,13 +2264,359 @@ do { } ``` -> :point_up: **Note**: All callbacks are called on the database queue. +> :point_up: **Note**: all callbacks are called on a protected dispatch queue. > -> :point_up: **Note**: The databaseDidChangeWithEvent and databaseWillCommit callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. +> :point_up: **Note**: the databaseDidChangeWithEvent and databaseWillCommit callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. Check [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd) for a transaction observer that notifies, on the main thread, of modified database tables. Your view controllers can listen to those notifications and update their views accordingly. +Good To Know +============ + +This chapter covers general topics that you should be aware of. + +- [Error Handling](#error-handling) +- [Unicode](#unicode) +- [Memory Management](#memory-management) + + +## Error Handling + +**No SQLite error goes unnoticed.** + +When an [SQLite error](https://www.sqlite.org/rescode.html) happens, some GRDB functions throw a DatabaseError, and some crash with a fatal error: + +```swift +// fatal error: +// SQLite error 1 with statement `SELECT * FROM bar`: no such table: bar +Row.fetchAll(db, "SELECT * FROM bar") + +do { + try db.execute( + "INSERT INTO pets (masterId, name) VALUES (?, ?)", + arguments: [1, "Bobby"]) +} catch let error as DatabaseError { + // SQLite error 19 with statement `INSERT INTO pets (masterId, name) + // VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed + error.description + + // The SQLite result code: 19 (SQLITE_CONSTRAINT) + error.code + + // The eventual SQLite message + // "FOREIGN KEY constraint failed" + error.message + + // The eventual erroneous SQL query + // "INSERT INTO pets (masterId, name) VALUES (?, ?)" + error.sql +} +``` + + +**Fatal errors can be avoided.** For example, let's consider the code below: + +```swift +let sql = "SELECT ..." +let arguments: NSDictionary = ... +let rows = Row.fetchAll(dbQueue, sql, arguments: StatementArguments(arguments)) +``` + +It has many opportunities to fail: + +- The sql string may contain invalid sql, or refer to non-existing tables or columns. +- The arguments NSDictionary may contain unsuitable values. +- The arguments NSDictionary may miss values required by the statement. + +The safe version of the code above goes down a level in GRDB API, in order to expose each failure point: + +```swift +// Grab a database connection: +try dbQueue.inDatabase { db in + + // Dictionary arguments may contain invalid values: + if let arguments = StatementArguments(arguments) { + + // SQL may be invalid + let statement = try db.selectStatement(sql) + + // Arguments may not fit the statement + try statement.validateArguments(arguments) + + // OK now + let rows = Row.fetchAll(statement, arguments: arguments) + } +} +``` + +See [prepared statements](#prepared-statements) for more information. + + +## Unicode + +SQLite lets you store unicode strings in the database. + +However, SQLite does not provide any unicode-aware string transformations or comparisons. + +### Unicode functions + +The `upper` and `lower` SQLite functions are not unicode-aware. See [SQL Functions](#sql-functions) to learn how you can introduce custom string functions. + +### String Comparison + +SQLite compares strings in many occasions: when you sort rows according to a string column, or when you use a comparison operator such as `=` and `<=`. + +The comparison result comes from a *collating function*, or *collation*. SQLite comes with [three built-in collations](https://www.sqlite.org/datatype3.html#collation) that do not support Unicode. For SQLite, "Jérôme" and "jerome" will never match. + +Fortunately, **you can define your own collations**, based on the rich set of Swift string comparisons: + +```swift +let collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in + return (lhs as NSString).localizedCaseInsensitiveCompare(rhs) +} +dbQueue.addCollation(collation) // Or dbPool.addCollation(...) +``` + +Once defined, the custom collation can be applied to a table column. All comparisons involving this column will automatically trigger your comparison function: + +```swift +// Apply the custom collation to the `name` column +try dbQueue.execute( + "CREATE TABLE persons (" + + "name TEXT COLLATE localized_case_insensitive" + // The name of the collation + ")") + +// Persons are sorted as expected: +let persons = Person.order(name).fetchAll(dbQueue) + +// Matches "Jérôme", "jerome", etc. +let persons = Person.filter(name == "Jérôme").fetchAll(dbQueue) +``` + +If you can't or don't want to define the comparison behavior of a column, you can still use an explicit collation on particular requests: + +```swift +// SELECT * FROM "persons" WHERE ("name" = 'foo' COLLATE NOCASE) +let persons = Person.filter(name.collating("NOCASE") == "foo").fetchAll(db) + +// SELECT * FROM "persons" WHERE ("name" = 'Jérôme' COLLATE localized_case_insensitive) +let persons = Person.filter(name.collating(collation) == "Jérôme").fetchAll(db) +``` + +See the [query interface](#the-query-interface) for more information. + + +## Memory Management + +**You can reclaim memory used by GRDB.** + +The most obvious way is to release your [database queues](#database-queues) and [pools](#database-pools): + +```swift +// Eventually release all memory, after all database accesses are completed: +dbQueue = nil +dbPool = nil +``` + +Yet both SQLite and GRDB use non-essential memory that help them perform better. You can claim this memory with the `releaseMemory` method: + +```swift +// Release as much memory as possible. +dbQueue.releaseMemory() +dbPool.releaseMemory() +``` + +This method blocks the current thread until all current database accesses are completed, and the memory collected. + + +### Memory Management on iOS + +**The iOS operating system likes applications that do not consume much memory.** + +You should call the `releaseMemory` method when your application receives a memory warning, and when it enters background. Since `releaseMemory` is blocking, dispatch it to some background queue so that you avoid freezing your user interface. + +For example: + +```swift +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + var dbQueue: DatabaseQueue! + + func applicationDidReceiveMemoryWarning(application: UIApplication) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { + self.dbQueue.releaseMemory() + } + } + + func applicationDidEnterBackground(application: UIApplication) { + let task = application.beginBackgroundTaskWithExpirationHandler(nil) + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { + self.dbQueue.releaseMemory() + application.endBackgroundTask(task) + } + } +} +``` + + +## Concurrency + +GRDB ships with support for two concurrency modes: + +- [DatabaseQueue](#database-queues) opens a single database connection, and serializes all database accesses. +- [DatabasePool](#database-pools) manages a pool of several database connections, serializes writes, and allows concurrent reads and writes. + +A database queue or pool prevents all concurrency troubles, granted there is no other connection to your database. + +**As a consequence, your application should have a unique instance of DatabaseQueue or DatabasePool connected to a database file.** You may experience concurrency trouble if you do otherwise. + +Now, as thread-safe as DatabaseQueue and DatabasePool are, your multithreaded application should be well aware that two consecutive statements do not operate on a stable database state: + +```swift +// Those two values may be different because some other thread may have inserted +// or deleted a point of interest between the two statements: +let count1 = PointOfInterest.fetchCount(dbQueueOrPool) +let count2 = PointOfInterest.fetchCount(dbQueueOrPool) +``` + +Now it is easy to avoid surprises, and isolate a bunch or related statements together: + +- [Isolation with DatabaseQueue](#isolation-with-databasequeue) +- [Isolation with DatabasePool](#isolation-with-databasepool) + + +### Isolation with DatabaseQueue + +In a multithreaded application, use `inDatabase` or `inTransaction` to isolate consecutive statements, and make sure they are not disturbed by parallel database updates: + +```swift +dbQueue.inDatabase { db in + // Those two values are guaranteed to be equal: + let count1 = PointOfInterest.fetchCount(db) + let count2 = PointOfInterest.fetchCount(db) +} + +dbQueue.inDatabase { db in + // Now this value may be different: + let count = PointOfInterest.fetchCount(db) +} + +// Wrap statements in a transaction: +try dbQueue.inTransaction { db in + if let paris = PointOfInterest.fetchOne(db, key: parisId) { + try paris.delete(db) + } + return .Commit +} +``` + +The `inDatabase` and `inTransaction` methods execute their closure argument in a protected dispatch queue, and block the current thread until your database statements are executed. The database accesses are serialized, which means that no two threads can execute such a closure in parallel. + +See [Transactions](#transactions) for more information. + + +### Isolation with DatabasePool + +In a multithreaded application, use `read` to isolate consecutive fetch statements, and make sure they are not disturbed by parallel database updates: + +```swift +dbPool.read { db in + // Those two values are guaranteed to be equal, even if the `wines` + // tables is concurrently modified between the two requests: + let count1 = PointOfInterest.fetchCount(db) + let count2 = PointOfInterest.fetchCount(db) +} + +dbPool.read { db in + // Now this value may be different: + let count = PointOfInterest.fetchCount(db) +} +``` + +`read` executes its closure argument in a protected dispatch queue, and blocks the current thread until your database statements are executed. Eventual concurrent updates may happen, but they are not visible inside a `read` closure. + +For isolated updates, use `write` or `writeInTransaction`. They also execute their closure argument in a protected dispatch queue, and block the current thread until your database statements are executed. The database writes are serialized, which means that no two threads can execute such a closure in parallel: + +```swift +try dbPool.write { db in + try country.save(db) + try poi.save(db) +} + +// Wrap statements in a transaction: +try dbPool.writeInTransaction { db in + if let paris = PointOfInterest.fetchOne(db, key: parisId) { + try paris.delete(db) + } + return .Commit +} +``` + +See [Transactions](#transactions) for more information. + + +### Advanced Concurrency + +SQLite concurrency is a wiiide topic. + +First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Protocols/DatabaseWriter.html) protocols. + +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: + +- General discussion about isolation in SQLite: https://www.sqlite.org/isolation.html +- Types of locks and transactions: https://www.sqlite.org/lang_transaction.html +- WAL journal mode: https://www.sqlite.org/wal.html +- Busy handlers: https://www.sqlite.org/c3ref/busy_handler.html + +See also [Transactions](#transactions) for more precise handling of transactions, and [Configuration](GRDB/Core/Configuration.swift) for more precise handling of eventual SQLITE_BUSY errors. + + +FAQ +=== + +- **How do I close a database connection?** + + The short answer is: + + ```swift + // Eventually close all database connections + dbQueue = nil + dbPool = nil + ``` + + You do not explicitely close a database connection: it is managed by a [database queue](#database-queues) or [pool](#database-pools). The connection is closed when all usages of this connection are completed, and when its database queue or pool gets deallocated. + + Database accesses that run in background threads postpone the closing of connections. + + The `releaseMemory` method of DatabasePool ([documentation](#memory-management)) will actually close some connections, but the pool will open another connection as soon as you access the database again. + + +- **How do I open a database stored as a resource of my application?** + + If your application does not need to modify the database, open a read-only [connection](#database-connections) to your resource: + + ```swift + var configuration = Configuration() + configuration.readonly = true + let dbPath = NSBundle.mainBundle().pathForResource("db", ofType: "sqlite")! + let dbQueue = try! DatabaseQueue(path: dbPath, configuration: configuration) + ``` + + If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the Documents folder. Only then, open a [connection](#database-connections): + + ```swift + let fm = NSFileManager.defaultManager() + let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] + let dbPath = (documentsPath as NSString).stringByAppendingPathComponent("db.sqlite") + if !fm.fileExistsAtPath(dbPath) { + let dbResourcePath = NSBundle.mainBundle().pathForResource("db", ofType: "sqlite")! + try! fm.copyItemAtPath(dbResourcePath, toPath: dbPath) + } + let dbQueue = DatabaseQueue(path: dbPath) + ``` + + Sample Code =========== diff --git a/Support/Info.plist b/Support/Info.plist index 5f1d94e97..6ee1b75a5 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.45.0 + 0.51.2 CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index 3114689e3..004e8e3cf 100644 --- a/TODO.md +++ b/TODO.md @@ -1,5 +1,4 @@ -- [ ] How to have robust single writer/several readers? -- [ ] protocol DatabaseEquatable, with default implementation for MutablePersistable +- [ ] Read https://sqlite.org/sharedcache.html - [ ] Query builder - [ ] SELECT readers.*, books.* FROM ... JOIN ... - [ ] date functions @@ -10,11 +9,10 @@ - [ ] MATCH https://www.sqlite.org/lang_expr.html - [ ] REGEXP https://www.sqlite.org/lang_expr.html - [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html - - [ ] EXISTS https://www.sqlite.org/lang_expr.html - Not sure: +- [ ] Build Swift string functions in, and have Person.select(name.uppercaseString) call a custom function named uppercaseString - [ ] Refactor errors in a single type? - [ ] Since Records' primary key are infered, no operation is possible on the primary key unless we have a Database instance. It's impossible to define the record.primaryKey property, or to provide a copy() function that does not clone the primary key: they miss the database that is the only object aware of the primary key. Should we change our mind, and have Record explicitly expose their primary key again? - [ ] Have Record adopt Hashable and Equatable, based on primary key. Problem: we can't do it know because we don't know the primary key until we have a database connection. @@ -23,7 +21,6 @@ Not sure: Require changes in the Swift language: -- [ ] Turn DatabaseIntRepresentable and DatabaseStringRepresentable into StatementColumnConvertible when Swift allows for it. - [ ] Specific and optimized Optional.fetch... methods when http://openradar.appspot.com/22852669 is fixed. diff --git a/Tests/Crash/DatabasePoolCrashTests.swift b/Tests/Crash/DatabasePoolCrashTests.swift new file mode 100644 index 000000000..59dbb15c3 --- /dev/null +++ b/Tests/Crash/DatabasePoolCrashTests.swift @@ -0,0 +1,21 @@ +import GRDB +import XCTest + +class DatabasePoolCrashTests: GRDBCrashTestCase { + + func testReaderCanNotStartTransaction() { + assertCrash("DatabasePool readers can not start transactions or savepoints.") { + try dbPool.read { db in + let statement = try db.updateStatement("BEGIN TRANSACTION") + } + } + } + + func testReaderCanNotStartSavepoint() { + assertCrash("DatabasePool readers can not start transactions or savepoints.") { + try dbPool.read { db in + let statement = try db.updateStatement("SAVEPOINT foo") + } + } + } +} diff --git a/Tests/Crash/DatabaseQueueCrashTests.swift b/Tests/Crash/DatabaseQueueCrashTests.swift new file mode 100644 index 000000000..cec7b0f43 --- /dev/null +++ b/Tests/Crash/DatabaseQueueCrashTests.swift @@ -0,0 +1,107 @@ +import GRDB +import XCTest + +class DatabaseQueueCrashTests: GRDBCrashTestCase { + + + // ========================================================================= + // MARK: - Reentrancy + + func testInDatabaseIsNotReentrant() { + assertCrash("Database methods are not reentrant.") { + dbQueue.inDatabase { db in + self.dbQueue.inDatabase { db in + } + } + } + } + + func testInTransactionInsideInDatabaseIsNotReentrant() { + assertCrash("Database methods are not reentrant.") { + try dbQueue.inDatabase { db in + try self.dbQueue.inTransaction { db in + return .Commit + } + } + } + } + + func testInTransactionIsNotReentrant() { + assertCrash("Database methods are not reentrant.") { + try dbQueue.inTransaction { db in + try self.dbQueue.inTransaction { db in + return .Commit + } + return .Commit + } + } + } + + + // ========================================================================= + // MARK: - Sequence iteration in wrong queue + + func testRowSequenceCanNotBeGeneratedOutsideOfDatabaseQueue() { + assertCrash("Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") { + var rows: DatabaseSequence? + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE persons (name TEXT)") + rows = Row.fetch(db, "SELECT * FROM persons") + } + _ = rows!.generate() + } + } + + func testRowSequenceCanNotBeIteratedOutsideOfDatabaseQueue() { + assertCrash("Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") { + var generator: DatabaseGenerator? + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE persons (name TEXT)") + generator = Row.fetch(db, "SELECT * FROM persons").generate() + } + _ = generator!.next() + } + } + + + // ========================================================================= + // MARK: - Concurrency + + func testReaderCrashDuringExclusiveTransaction() { + assertCrash("SQLite error 5 with statement `SELECT * FROM stuffs`: database is locked") { + databasePath = "/tmp/GRDBTestReaderDuringExclusiveTransaction.sqlite" + do { try NSFileManager.defaultManager().removeItemAtPath(databasePath) } catch { } + let dbQueue1 = try! DatabaseQueue(path: databasePath) + let dbQueue2 = try! DatabaseQueue(path: databasePath) + + try! dbQueue1.inDatabase { db in + try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)") + } + + let queue = NSOperationQueue() + queue.maxConcurrentOperationCount = 2 + queue.addOperation(NSBlockOperation { + do { + try dbQueue1.inTransaction(.Exclusive) { db in + sleep(2) // let other queue try to read. + return .Commit + } + } + catch is DatabaseError { + } + catch { + XCTFail("\(error)") + } + }) + + queue.addOperation(NSBlockOperation { + dbQueue2.inDatabase { db in + sleep(1) // let other queue open transaction + _ = Row.fetch(db, "SELECT * FROM stuffs") // Crash expected + } + }) + + queue.waitUntilAllOperationsAreFinished() + } + } +} diff --git a/Tests/Crash/DatabaseValueConvertibleCrashTests.swift b/Tests/Crash/DatabaseValueConvertibleCrashTests.swift new file mode 100644 index 000000000..a263909b2 --- /dev/null +++ b/Tests/Crash/DatabaseValueConvertibleCrashTests.swift @@ -0,0 +1,89 @@ +import XCTest +import GRDB + +// A type that adopts DatabaseValueConvertible but does not adopt StatementColumnConvertible +private struct IntConvertible: DatabaseValueConvertible { + let int: Int + init(int: Int) { + self.int = int + } + var databaseValue: DatabaseValue { + return int.databaseValue + } + static func fromDatabaseValue(databaseValue: DatabaseValue) -> IntConvertible? { + guard let int = Int.fromDatabaseValue(databaseValue) else { + return nil + } + return IntConvertible(int: int) + } +} + +class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase { + + func testCrashFetchDatabaseValueConvertibleFromStatement() { + assertCrash("could not convert NULL to IntConvertible.") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE ints (int Int)") + try db.execute("INSERT INTO ints (int) VALUES (1)") + try db.execute("INSERT INTO ints (int) VALUES (NULL)") + + let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int") + let sequence = IntConvertible.fetch(statement) + for _ in sequence { } + } + } + } + + func testCrashFetchAllDatabaseValueConvertibleFromStatement() { + assertCrash("could not convert NULL to IntConvertible.") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE ints (int Int)") + try db.execute("INSERT INTO ints (int) VALUES (1)") + try db.execute("INSERT INTO ints (int) VALUES (NULL)") + + let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int") + _ = IntConvertible.fetchAll(statement) + } + } + } + + func testCrashFetchDatabaseValueConvertibleFromDatabase() { + assertCrash("could not convert NULL to IntConvertible.") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE ints (int Int)") + try db.execute("INSERT INTO ints (int) VALUES (1)") + try db.execute("INSERT INTO ints (int) VALUES (NULL)") + + let sequence = IntConvertible.fetch(db, "SELECT int FROM ints ORDER BY int") + for _ in sequence { } + } + } + } + + func testCrashFetchAllDatabaseValueConvertibleFromDatabase() { + assertCrash("could not convert NULL to IntConvertible.") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE ints (int Int)") + try db.execute("INSERT INTO ints (int) VALUES (1)") + try db.execute("INSERT INTO ints (int) VALUES (NULL)") + + _ = IntConvertible.fetchAll(db, "SELECT int FROM ints ORDER BY int") + } + } + } + + func testCrashDatabaseValueConvertibleInvalidConversionFromNULL() { + assertCrash("could not convert NULL to IntConvertible.") { + let row = Row(["int": nil]) + _ = row.value(named: "int") as IntConvertible + } + } + + func testCrashDatabaseValueConvertibleInvalidConversionFromInvalidType() { + assertCrash("could not convert \"foo\" to IntConvertible") { + let row = Row(["int": "foo"]) + _ = row.value(named: "int") as IntConvertible + } + } + +} diff --git a/Tests/Crash/GRDBCrashTestCase.swift b/Tests/Crash/GRDBCrashTestCase.swift new file mode 100644 index 000000000..1efc33b09 --- /dev/null +++ b/Tests/Crash/GRDBCrashTestCase.swift @@ -0,0 +1,15 @@ +import XCTest + +class GRDBCrashTestCase: GRDBTestCase { + + // This method does not actually catch any crash. + // But it expresses an intent :-) + func assertCrash(message: String, @noescape block: () throws -> ()) { + do { + try block() + XCTFail("Crash expected: \(message)") + } catch { + XCTFail("Unexpected error: \(error)") + } + } +} diff --git a/Tests/Crash/MigrationCrashTests.swift b/Tests/Crash/MigrationCrashTests.swift new file mode 100644 index 000000000..af21276e2 --- /dev/null +++ b/Tests/Crash/MigrationCrashTests.swift @@ -0,0 +1,13 @@ +import GRDB + +class MigrationCrashTests: GRDBCrashTestCase { + + func testMigrationNamesMustBeUnique() { + assertCrash("already registered migration: \"foo\"") { + var migrator = DatabaseMigrator() + migrator.registerMigration("foo") { db in } + migrator.registerMigration("foo") { db in } + } + } + +} diff --git a/Tests/Crash/RecordCrashTests.swift b/Tests/Crash/RecordCrashTests.swift new file mode 100644 index 000000000..816f341ff --- /dev/null +++ b/Tests/Crash/RecordCrashTests.swift @@ -0,0 +1,324 @@ +import XCTest +import GRDB + +private class RecordWithoutDatabaseTableName: Record { } + +private class RecordWithInexistingDatabaseTable: Record { + override static func databaseTableName() -> String { + return "foo" + } +} + +private class RecordWithEmptyPersistentDictionary : Record { + override static func databaseTableName() -> String { + return "records" + } +} + +private class RecordWithNilPrimaryKey : Record { + override static func databaseTableName() -> String { + return "records" + } + + override var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": nil] + } +} + +private class RecordForTableWithoutPrimaryKey : Record { + override static func databaseTableName() -> String { + return "records" + } + + override var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["name": "foo"] + } +} + +private class RecordForTableWithMultipleColumnsPrimaryKey : Record { + override static func databaseTableName() -> String { + return "records" + } + + override var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["name": "foo"] + } +} + +private class RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary : Record { + override static func databaseTableName() -> String { + return "records" + } + + override var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["name": "foo"] + } +} + +class RecordCrashTests: GRDBCrashTestCase { + + // ========================================================================= + // MARK: - RecordWithoutDatabaseTableName + + func testRecordWithoutDatabaseTableNameCanNotBeFetchedByID() { + assertCrash("subclass must override") { + dbQueue.inDatabase { db in + _ = RecordWithoutDatabaseTableName.fetchOne(db, key: 1) + } + } + } + + func testRecordWithoutDatabaseTableNameCanNotBeFetchedByKey() { + assertCrash("subclass must override") { + dbQueue.inDatabase { db in + _ = RecordWithoutDatabaseTableName.fetchOne(db, key: ["foo": "bar"]) + } + } + } + + func testRecordWithoutDatabaseTableNameCanNotBeInserted() { + assertCrash("subclass must override") { + try dbQueue.inDatabase { db in + try RecordWithoutDatabaseTableName().insert(db) + } + } + } + + func testRecordWithoutDatabaseTableNameCanNotBeUpdated() { + assertCrash("subclass must override") { + try dbQueue.inDatabase { db in + try RecordWithoutDatabaseTableName().update(db) + } + } + } + + func testRecordWithoutDatabaseTableNameCanNotBeSaved() { + assertCrash("subclass must override") { + try dbQueue.inDatabase { db in + try RecordWithoutDatabaseTableName().save(db) + } + } + } + + func testRecordWithoutDatabaseTableNameCanNotBeDeleted() { + assertCrash("subclass must override") { + try dbQueue.inDatabase { db in + try RecordWithoutDatabaseTableName().delete(db) + } + } + } + + func testRecordWithoutDatabaseTableNameCanNotBeTestedForExistence() { + assertCrash("subclass must override") { + dbQueue.inDatabase { db in + RecordWithoutDatabaseTableName().exists(db) + } + } + } + + + // ========================================================================= + // MARK: - RecordWithInexistingDatabaseTable + + func testRecordWithInexistingDatabaseTableCanNotBeFetchedByID() { + assertCrash("no such table: foo") { + dbQueue.inDatabase { db in + _ = RecordWithInexistingDatabaseTable.fetchOne(db, key: 1) + } + } + } + + func testRecordWithInexistingDatabaseTableCanNotBeFetchedByKey() { + assertCrash("SQLite error 1 with statement `SELECT * FROM \"foo\" WHERE (\"id\" = ?)`: no such table: foo") { + dbQueue.inDatabase { db in + _ = RecordWithInexistingDatabaseTable.fetchOne(db, key: ["id": 1]) + } + } + } + + func testRecordWithInexistingDatabaseTableCanNotBeInserted() { + assertCrash("no such table: foo") { + try dbQueue.inDatabase { db in + try RecordWithInexistingDatabaseTable().insert(db) + } + } + } + + func testRecordWithInexistingDatabaseTableCanNotBeUpdated() { + assertCrash("no such table: foo") { + try dbQueue.inDatabase { db in + try RecordWithInexistingDatabaseTable().update(db) + } + } + } + + func testRecordWithInexistingDatabaseTableCanNotBeSaved() { + assertCrash("no such table: foo") { + try dbQueue.inDatabase { db in + try RecordWithInexistingDatabaseTable().save(db) + } + } + } + + func testRecordWithInexistingDatabaseTableCanNotBeDeleted() { + assertCrash("no such table: foo") { + try dbQueue.inDatabase { db in + try RecordWithInexistingDatabaseTable().delete(db) + } + } + } + + func testRecordWithInexistingDatabaseTableCanNotBeTestedForExistence() { + assertCrash("no such table: foo") { + dbQueue.inDatabase { db in + RecordWithInexistingDatabaseTable().exists(db) + } + } + } + + + // ========================================================================= + // MARK: - RecordWithEmptyPersistentDictionary + + func testRecordWithEmptyPersistentDictionaryCanNotBeInserted() { + assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") + try RecordWithEmptyPersistentDictionary().insert(db) + } + } + } + + func testRecordWithEmptyPersistentDictionaryCanNotBeUpdated() { + assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") + try RecordWithEmptyPersistentDictionary().update(db) + } + } + } + + func testRecordWithEmptyPersistentDictionaryCanNotBeSaved() { + assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") + try RecordWithEmptyPersistentDictionary().save(db) + } + } + } + + func testRecordWithEmptyPersistentDictionaryCanNotBeDeleted() { + assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") + try RecordWithEmptyPersistentDictionary().delete(db) + } + } + } + + func testRecordWithEmptyPersistentDictionaryCanNotBeTestedForExistence() { + assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") + RecordWithEmptyPersistentDictionary().exists(db) + } + } + } + + + // ========================================================================= + // MARK: - RecordWithNilPrimaryKey + + func testRecordWithNilPrimaryKeyCanNotBeUpdated() { + assertCrash("invalid primary key in ") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") + try RecordWithNilPrimaryKey().update(db) + } + } + } + + func testRecordWithNilPrimaryKeyCanNotBeDeleted() { + assertCrash("invalid primary key in ") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") + try RecordWithNilPrimaryKey().delete(db) + } + } + } + + func testRecordWithNilPrimaryKeyCanNotBeTestedForExistence() { + assertCrash("invalid primary key in ") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") + RecordWithNilPrimaryKey().exists(db) + } + } + } + + + // ========================================================================= + // MARK: - RecordForTableWithoutPrimaryKey + + func testRecordForTableWithoutPrimaryKeyCanNotBeFetchedByID() { + assertCrash("expected single column primary key in table: records") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (name TEXT)") + _ = RecordForTableWithoutPrimaryKey.fetchOne(db, key: 1) + } + } + } + + func testRecordForTableWithoutPrimaryKeyCanNotBeUpdated() { + assertCrash("invalid primary key in ") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (name TEXT)") + try RecordForTableWithoutPrimaryKey().update(db) + } + } + } + + func testRecordForTableWithoutPrimaryKeyCanNotBeDeleted() { + assertCrash("invalid primary key in ") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (name TEXT)") + try RecordForTableWithoutPrimaryKey().delete(db) + } + } + } + + func testRecordForTableWithoutPrimaryKeyCanNotBeTestedForExistence() { + assertCrash("invalid primary key in ") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (name TEXT)") + RecordForTableWithoutPrimaryKey().exists(db) + } + } + } + + + // ========================================================================= + // MARK: - RecordForTableWithMultipleColumnsPrimaryKey + + func testRecordForTableWithMultipleColumnsPrimaryKeyCanNotBeFetchedByID() { + assertCrash("expected single column primary key in table: records") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (a TEXT, b TEXT, PRIMARY KEY(a,b))") + _ = RecordForTableWithMultipleColumnsPrimaryKey.fetchOne(db, key: 1) + } + } + } + + + // ========================================================================= + // MARK: - RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary + + func testRecordWithRowIDPrimaryKeyNotExposedInPersistentDictionaryCanNotBeInserted() { + assertCrash("invalid primary key in ") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY, name TEXT)") + try RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary().update(db) + } + } + } +} diff --git a/Tests/Crash/StatementColumnConvertibleCrashTests.swift b/Tests/Crash/StatementColumnConvertibleCrashTests.swift new file mode 100644 index 000000000..413591163 --- /dev/null +++ b/Tests/Crash/StatementColumnConvertibleCrashTests.swift @@ -0,0 +1,58 @@ +import XCTest +import GRDB + +class StatementColumnConvertibleCrashTests: GRDBCrashTestCase { + + func testCrashFetchStatementColumnConvertibleFromStatement() { + assertCrash("could not convert NULL to Int.") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE ints (int Int)") + try db.execute("INSERT INTO ints (int) VALUES (1)") + try db.execute("INSERT INTO ints (int) VALUES (NULL)") + + let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int") + let sequence = Int.fetch(statement) + for _ in sequence { } + } + } + } + + func testCrashFetchAllStatementColumnConvertibleFromStatement() { + assertCrash("could not convert NULL to Int.") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE ints (int Int)") + try db.execute("INSERT INTO ints (int) VALUES (1)") + try db.execute("INSERT INTO ints (int) VALUES (NULL)") + + let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int") + _ = Int.fetchAll(statement) + } + } + } + + func testCrashFetchStatementColumnConvertibleFromDatabase() { + assertCrash("could not convert NULL to Int.") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE ints (int Int)") + try db.execute("INSERT INTO ints (int) VALUES (1)") + try db.execute("INSERT INTO ints (int) VALUES (NULL)") + + let sequence = Int.fetch(db, "SELECT int FROM ints ORDER BY int") + for _ in sequence { } + } + } + } + + func testCrashFetchAllStatementColumnConvertibleFromDatabase() { + assertCrash("could not convert NULL to Int.") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE ints (int Int)") + try db.execute("INSERT INTO ints (int) VALUES (1)") + try db.execute("INSERT INTO ints (int) VALUES (NULL)") + + _ = Int.fetchAll(db, "SELECT int FROM ints ORDER BY int") + } + } + } + +} diff --git a/Tests/Crash/StatementCrashTests.swift b/Tests/Crash/StatementCrashTests.swift new file mode 100644 index 000000000..9f95a06ac --- /dev/null +++ b/Tests/Crash/StatementCrashTests.swift @@ -0,0 +1,73 @@ +import XCTest +import GRDB + +class StatementCrashTests: GRDBCrashTestCase { + + func testInvalidStatementArguments() { + assertCrash("SQLite error 1 with statement `INSERT INTO persons (name, age) VALUES (:name, :age)`: missing statement argument(s): age") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE persons (name TEXT, age INT)") + try! db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur"]) + } + } + + assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', ?);`: wrong number of statement arguments: 0") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE persons (name TEXT, age INT)") + try db.execute( + "INSERT INTO persons (name, age) VALUES ('Arthur', ?);" + + "INSERT INTO persons (name, age) VALUES ('Barbara', ?);") + } + } + + assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Barbara', ?);`: wrong number of statement arguments: 0") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE persons (name TEXT, age INT)") + try db.execute( + "INSERT INTO persons (name, age) VALUES ('Arthur', ?);" + + "INSERT INTO persons (name, age) VALUES ('Barbara', ?);", + arguments: [41]) + } + } + + assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', :age1);`: missing statement argument(s): age1") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE persons (name TEXT, age INT)") + try db.execute( + "INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" + + "INSERT INTO persons (name, age) VALUES ('Barbara', :age2);") + } + } + + assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Barbara', :age2);`: missing statement argument(s): age2") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE persons (name TEXT, age INT)") + try db.execute( + "INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" + + "INSERT INTO persons (name, age) VALUES ('Barbara', :age2);", + arguments: ["age1": 41]) + } + } + + assertCrash("SQLite error 21: wrong number of statement arguments: 3") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE persons (name TEXT, age INT)") + try db.execute( + "INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" + + "INSERT INTO persons (name, age) VALUES ('Arthur', :age2);", + arguments: [41, 32, 17]) + } + } + + assertCrash("SQLite error 21: wrong number of statement arguments: 3") { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE persons (name TEXT, age INT)") + try db.execute( + "INSERT INTO persons (name, age) VALUES ('Arthur', ?);" + + "INSERT INTO persons (name, age) VALUES ('Arthur', ?);", + arguments: [41, 32, 17]) + } + } + } + +} diff --git a/Tests/GRDBProfiling/GRDBProfiling/AppDelegate.swift b/Tests/GRDBProfiling/GRDBProfiling/AppDelegate.swift index f15db9fd4..852b1352e 100644 --- a/Tests/GRDBProfiling/GRDBProfiling/AppDelegate.swift +++ b/Tests/GRDBProfiling/GRDBProfiling/AppDelegate.swift @@ -78,10 +78,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { func fetchRecords() { let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("ProfilingDatabase", ofType: "sqlite")! let dbQueue = try! DatabaseQueue(path: databasePath) - - let items = dbQueue.inDatabase { db in - Item.fetchAll(db, "SELECT * FROM items") - } + let items = Item.fetchAll(dbQueue) assert(items.count == expectedRowCount) assert(items[0].i0 == 0) assert(items[1].i1 == 1) @@ -101,7 +98,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in @@ -130,7 +127,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in @@ -149,7 +146,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { func insertRecords() { let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite" let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName) - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) defer { let dbQueue = try! DatabaseQueue(path: databasePath) dbQueue.inDatabase { db in @@ -160,7 +157,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in diff --git a/Tests/GRDBTestCase.swift b/Tests/GRDBTestCase.swift index 9270a6670..391406e4e 100644 --- a/Tests/GRDBTestCase.swift +++ b/Tests/GRDBTestCase.swift @@ -2,36 +2,77 @@ import XCTest import GRDB class GRDBTestCase: XCTestCase { - var databasePath: String! - var dbQueue: DatabaseQueue! + var dbConfiguration = Configuration() + + var dbQueuePath: String! + var _dbQueue: DatabaseQueue? + var dbQueue: DatabaseQueue! { + get { + if let _dbQueue = _dbQueue { + return _dbQueue + } else { + _dbQueue = try! DatabaseQueue(path: dbQueuePath, configuration: dbConfiguration) + return _dbQueue! + } + } + set { + _dbQueue = newValue + } + } + + var dbPoolDirectoryPath: String! + var dbPoolPath: String { + return (dbPoolDirectoryPath as NSString).stringByAppendingPathComponent("db.sqlite") + } + var _dbPool: DatabasePool? + var dbPool: DatabasePool! { + get { + if let _dbPool = _dbPool { + return _dbPool + } else { + try! NSFileManager.defaultManager().createDirectoryAtPath(dbPoolDirectoryPath, withIntermediateDirectories: true, attributes: nil) + _dbPool = try! DatabasePool(path: dbPoolPath, configuration: dbConfiguration) + return _dbPool! + } + } + set { + _dbPool = newValue + } + } + + var sqlQueries: [String]! var lastSQLQuery: String! - var dbConfiguration: Configuration { - var dbConfiguration = Configuration() + + override func setUp() { + super.setUp() + + let dbQueueFileName = "GRDBTestCase-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite" + dbQueuePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(dbQueueFileName) + + let dbPoolDirectoryName = "GRDBTestCase-\(NSProcessInfo.processInfo().globallyUniqueString)" + dbPoolDirectoryPath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(dbPoolDirectoryName) + dbConfiguration.trace = { (sql) in self.sqlQueries.append(sql) self.lastSQLQuery = sql // LogSQL(sql) // Uncomment for verbose tests } - return dbConfiguration - } - - override func setUp() { - super.setUp() - sqlQueries = [] + lastSQLQuery = nil - let databaseFileName = "GRDBTestCase-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite" - databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName) - do { try NSFileManager.defaultManager().removeItemAtPath(databasePath) } catch { } - dbQueue = try! DatabaseQueue(path: databasePath, configuration: dbConfiguration) + do { try NSFileManager.defaultManager().removeItemAtPath(dbQueuePath) } catch { } + do { try NSFileManager.defaultManager().removeItemAtPath(dbPoolDirectoryPath) } catch { } } override func tearDown() { super.tearDown() - dbQueue = nil - try! NSFileManager.defaultManager().removeItemAtPath(databasePath) + _dbQueue = nil + _dbPool = nil + + do { try NSFileManager.defaultManager().removeItemAtPath(dbQueuePath) } catch { } + do { try NSFileManager.defaultManager().removeItemAtPath(dbPoolDirectoryPath) } catch { } } func assertNoError(@noescape test: (Void) throws -> Void) { @@ -44,7 +85,7 @@ class GRDBTestCase: XCTestCase { func sql(request: FetchRequest) -> String { return dbQueue.inDatabase { db in - let _ = Row.fetchOne(db, request) + _ = Row.fetchOne(db, request) return self.lastSQLQuery } } diff --git a/Tests/Performance/FetchNamedValuesTests.swift b/Tests/Performance/FetchNamedValuesTests.swift index aa8cadee0..658d8327e 100644 --- a/Tests/Performance/FetchNamedValuesTests.swift +++ b/Tests/Performance/FetchNamedValuesTests.swift @@ -17,16 +17,16 @@ class FetchNamedValuesTests: XCTestCase { dbQueue.inDatabase { db in if let rs = db.executeQuery("SELECT * FROM items", withArgumentsInArray: nil) { while rs.next() { - let _ = rs.longForColumn("i0") - let _ = rs.longForColumn("i1") - let _ = rs.longForColumn("i2") - let _ = rs.longForColumn("i3") - let _ = rs.longForColumn("i4") - let _ = rs.longForColumn("i5") - let _ = rs.longForColumn("i6") - let _ = rs.longForColumn("i7") - let _ = rs.longForColumn("i8") - let _ = rs.longForColumn("i9") + _ = rs.longForColumn("i0") + _ = rs.longForColumn("i1") + _ = rs.longForColumn("i2") + _ = rs.longForColumn("i3") + _ = rs.longForColumn("i4") + _ = rs.longForColumn("i5") + _ = rs.longForColumn("i6") + _ = rs.longForColumn("i7") + _ = rs.longForColumn("i8") + _ = rs.longForColumn("i9") count += 1 } @@ -46,16 +46,16 @@ class FetchNamedValuesTests: XCTestCase { dbQueue.inDatabase { db in for row in Row.fetch(db, "SELECT * FROM items") { - let _: Int = row.value(named: "i0") - let _: Int = row.value(named: "i1") - let _: Int = row.value(named: "i2") - let _: Int = row.value(named: "i3") - let _: Int = row.value(named: "i4") - let _: Int = row.value(named: "i5") - let _: Int = row.value(named: "i6") - let _: Int = row.value(named: "i7") - let _: Int = row.value(named: "i8") - let _: Int = row.value(named: "i9") + _ = row.value(named: "i0") as Int + _ = row.value(named: "i1") as Int + _ = row.value(named: "i2") as Int + _ = row.value(named: "i3") as Int + _ = row.value(named: "i4") as Int + _ = row.value(named: "i5") as Int + _ = row.value(named: "i6") as Int + _ = row.value(named: "i7") as Int + _ = row.value(named: "i8") as Int + _ = row.value(named: "i9") as Int count += 1 } @@ -73,16 +73,16 @@ class FetchNamedValuesTests: XCTestCase { var count = 0 for item in try! db.prepare(itemsTable) { - let _ = item[i0Column] - let _ = item[i1Column] - let _ = item[i2Column] - let _ = item[i3Column] - let _ = item[i4Column] - let _ = item[i5Column] - let _ = item[i6Column] - let _ = item[i7Column] - let _ = item[i8Column] - let _ = item[i9Column] + _ = item[i0Column] + _ = item[i1Column] + _ = item[i2Column] + _ = item[i3Column] + _ = item[i4Column] + _ = item[i5Column] + _ = item[i6Column] + _ = item[i7Column] + _ = item[i8Column] + _ = item[i9Column] count += 1 } diff --git a/Tests/Performance/FetchPositionalValuesTests.swift b/Tests/Performance/FetchPositionalValuesTests.swift index 6fe3b8aec..dfc708bf2 100644 --- a/Tests/Performance/FetchPositionalValuesTests.swift +++ b/Tests/Performance/FetchPositionalValuesTests.swift @@ -22,16 +22,16 @@ class FetchPositionalValuesTests: XCTestCase { case 101 /*SQLITE_DONE*/: break loop case 100 /*SQLITE_ROW*/: - let _ = sqlite3_column_int64(statement, 0) - let _ = sqlite3_column_int64(statement, 1) - let _ = sqlite3_column_int64(statement, 2) - let _ = sqlite3_column_int64(statement, 3) - let _ = sqlite3_column_int64(statement, 4) - let _ = sqlite3_column_int64(statement, 5) - let _ = sqlite3_column_int64(statement, 6) - let _ = sqlite3_column_int64(statement, 7) - let _ = sqlite3_column_int64(statement, 8) - let _ = sqlite3_column_int64(statement, 9) + _ = sqlite3_column_int64(statement, 0) + _ = sqlite3_column_int64(statement, 1) + _ = sqlite3_column_int64(statement, 2) + _ = sqlite3_column_int64(statement, 3) + _ = sqlite3_column_int64(statement, 4) + _ = sqlite3_column_int64(statement, 5) + _ = sqlite3_column_int64(statement, 6) + _ = sqlite3_column_int64(statement, 7) + _ = sqlite3_column_int64(statement, 8) + _ = sqlite3_column_int64(statement, 9) break default: XCTFail() @@ -58,16 +58,16 @@ class FetchPositionalValuesTests: XCTestCase { dbQueue.inDatabase { db in if let rs = db.executeQuery("SELECT * FROM items", withArgumentsInArray: nil) { while rs.next() { - let _ = rs.longForColumnIndex(0) - let _ = rs.longForColumnIndex(1) - let _ = rs.longForColumnIndex(2) - let _ = rs.longForColumnIndex(3) - let _ = rs.longForColumnIndex(4) - let _ = rs.longForColumnIndex(5) - let _ = rs.longForColumnIndex(6) - let _ = rs.longForColumnIndex(7) - let _ = rs.longForColumnIndex(8) - let _ = rs.longForColumnIndex(9) + _ = rs.longForColumnIndex(0) + _ = rs.longForColumnIndex(1) + _ = rs.longForColumnIndex(2) + _ = rs.longForColumnIndex(3) + _ = rs.longForColumnIndex(4) + _ = rs.longForColumnIndex(5) + _ = rs.longForColumnIndex(6) + _ = rs.longForColumnIndex(7) + _ = rs.longForColumnIndex(8) + _ = rs.longForColumnIndex(9) count += 1 } @@ -87,16 +87,16 @@ class FetchPositionalValuesTests: XCTestCase { dbQueue.inDatabase { db in for row in Row.fetch(db, "SELECT * FROM items") { - let _: Int = row.value(atIndex: 0) - let _: Int = row.value(atIndex: 1) - let _: Int = row.value(atIndex: 2) - let _: Int = row.value(atIndex: 3) - let _: Int = row.value(atIndex: 4) - let _: Int = row.value(atIndex: 5) - let _: Int = row.value(atIndex: 6) - let _: Int = row.value(atIndex: 7) - let _: Int = row.value(atIndex: 8) - let _: Int = row.value(atIndex: 9) + _ = row.value(atIndex: 0) as Int + _ = row.value(atIndex: 1) as Int + _ = row.value(atIndex: 2) as Int + _ = row.value(atIndex: 3) as Int + _ = row.value(atIndex: 4) as Int + _ = row.value(atIndex: 5) as Int + _ = row.value(atIndex: 6) as Int + _ = row.value(atIndex: 7) as Int + _ = row.value(atIndex: 8) as Int + _ = row.value(atIndex: 9) as Int count += 1 } @@ -115,16 +115,16 @@ class FetchPositionalValuesTests: XCTestCase { for row in try! db.prepare("SELECT * FROM items") { // Direct Int extraction is not supported. - let _ = Int(row[0] as! Int64) - let _ = Int(row[1] as! Int64) - let _ = Int(row[2] as! Int64) - let _ = Int(row[3] as! Int64) - let _ = Int(row[4] as! Int64) - let _ = Int(row[5] as! Int64) - let _ = Int(row[6] as! Int64) - let _ = Int(row[7] as! Int64) - let _ = Int(row[8] as! Int64) - let _ = Int(row[9] as! Int64) + _ = Int(row[0] as! Int64) + _ = Int(row[1] as! Int64) + _ = Int(row[2] as! Int64) + _ = Int(row[3] as! Int64) + _ = Int(row[4] as! Int64) + _ = Int(row[5] as! Int64) + _ = Int(row[6] as! Int64) + _ = Int(row[7] as! Int64) + _ = Int(row[8] as! Int64) + _ = Int(row[9] as! Int64) count += 1 } diff --git a/Tests/Performance/FetchRecordTests.swift b/Tests/Performance/FetchRecordTests.swift index c3486802e..bb0e18608 100644 --- a/Tests/Performance/FetchRecordTests.swift +++ b/Tests/Performance/FetchRecordTests.swift @@ -2,6 +2,7 @@ import XCTest import GRDB import SQLite import CoreData +import RealmSwift private let expectedRowCount = 100_000 @@ -92,9 +93,7 @@ class FetchRecordTests: XCTestCase { let dbQueue = try! DatabaseQueue(path: databasePath) measureBlock { - let items = dbQueue.inDatabase { db in - Item.fetchAll(db, "SELECT * FROM items") - } + let items = Item.fetchAll(dbQueue, "SELECT * FROM items") XCTAssertEqual(items.count, expectedRowCount) XCTAssertEqual(items[0].i0, 0) XCTAssertEqual(items[1].i1, 1) @@ -156,4 +155,28 @@ class FetchRecordTests: XCTestCase { XCTAssertEqual(items.count, expectedRowCount) } } + + func testRealm() { + let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceRealmTests", ofType: "realm")! + let realm = try! Realm(path: databasePath) + + measureBlock { + let items = realm.objects(RealmItem) + var count = 0 + for item in items { + count += 1 + _ = item.i0 + _ = item.i1 + _ = item.i2 + _ = item.i3 + _ = item.i4 + _ = item.i5 + _ = item.i6 + _ = item.i7 + _ = item.i8 + _ = item.i9 + } + XCTAssertEqual(count, expectedRowCount) + } + } } diff --git a/Tests/Performance/InsertNamedValuesTests.swift b/Tests/Performance/InsertNamedValuesTests.swift index 3defdf1a7..cc561f831 100644 --- a/Tests/Performance/InsertNamedValuesTests.swift +++ b/Tests/Performance/InsertNamedValuesTests.swift @@ -21,7 +21,7 @@ class InsertNamedValuesTests: XCTestCase { } measureBlock { - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let dbQueue = FMDatabaseQueue(path: databasePath) dbQueue.inDatabase { db in @@ -51,7 +51,7 @@ class InsertNamedValuesTests: XCTestCase { } measureBlock { - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in @@ -82,7 +82,7 @@ class InsertNamedValuesTests: XCTestCase { } measureBlock { - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let db = try! Connection(databasePath) try! db.run(itemsTable.create { t in diff --git a/Tests/Performance/InsertPositionalValuesTests.swift b/Tests/Performance/InsertPositionalValuesTests.swift index 772fc0b1f..605b33081 100644 --- a/Tests/Performance/InsertPositionalValuesTests.swift +++ b/Tests/Performance/InsertPositionalValuesTests.swift @@ -21,7 +21,7 @@ class InsertPositionalValuesTests: XCTestCase { } measureBlock { - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) var connection: COpaquePointer = nil sqlite3_open_v2(databasePath, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil) @@ -66,7 +66,7 @@ class InsertPositionalValuesTests: XCTestCase { try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } measureBlock { - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let dbQueue = FMDatabaseQueue(path: databasePath) dbQueue.inDatabase { db in @@ -95,7 +95,7 @@ class InsertPositionalValuesTests: XCTestCase { try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } measureBlock { - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in @@ -125,7 +125,7 @@ class InsertPositionalValuesTests: XCTestCase { try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } measureBlock { - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let db = try! Connection(databasePath) try! db.run(itemsTable.create { t in diff --git a/Tests/Performance/InsertRecordTests.swift b/Tests/Performance/InsertRecordTests.swift index 35a7f306e..2ba5ced8e 100644 --- a/Tests/Performance/InsertRecordTests.swift +++ b/Tests/Performance/InsertRecordTests.swift @@ -1,6 +1,7 @@ import XCTest import GRDB import CoreData +import RealmSwift private let insertedRowCount = 20_000 @@ -10,7 +11,7 @@ class InsertRecordTests: XCTestCase { func testGRDB() { let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite" let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName) - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) defer { let dbQueue = try! DatabaseQueue(path: databasePath) dbQueue.inDatabase { db in @@ -22,7 +23,7 @@ class InsertRecordTests: XCTestCase { } measureBlock { - let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) let dbQueue = try! DatabaseQueue(path: databasePath) try! dbQueue.inDatabase { db in @@ -68,4 +69,20 @@ class InsertRecordTests: XCTestCase { try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } } + + func testRealm() { + let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).realm" + let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName) + + measureBlock { + _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath) + let realm = try! Realm(path: databasePath) + + try! realm.write { + for i in 0.. + +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMObject, RLMRealm, RLMResults RLM_GENERIC_COLLECTION, RLMNotificationToken; + +/** + + RLMArray is the container type in Realm used to define to-many relationships. + + Unlike an NSArray, RLMArrays hold a single type, specified by the `objectClassName` property. + This is referred to in these docs as the “type” of the array. + + When declaring an RLMArray property, the type must be marked as conforming to a + protocol by the same name as the objects it should contain (see the + `RLM_ARRAY_TYPE` macro). RLMArray properties can also use Objective-C generics + if available. For example: + + RLM_ARRAY_TYPE(ObjectType) + ... + @property RLMArray *arrayOfObjectTypes; + + RLMArrays can be queried with the same predicates as RLMObject and RLMResults. + + RLMArrays cannot be created directly. RLMArray properties on RLMObjects are + lazily created when accessed, or can be obtained by querying a Realm. + + ### Key-Value Observing + + RLMArray supports array key-value observing on RLMArray properties on RLMObject + subclasses, and the `invalidated` property on RLMArray instances themselves is + key-value observing compliant when the RLMArray is attached to a persisted + RLMObject (RLMArrays on standalone RLMObjects will never become invalidated). + + Because RLMArrays are attached to the object which they are a property of, they + do not require using the mutable collection proxy objects from + `-mutableArrayValueForKey:` or KVC-compatible mutation methods on the containing + object. Instead, you can call the mutation methods on the RLMArray directly. + */ + +@interface RLMArray RLM_GENERIC_COLLECTION : NSObject + +#pragma mark - Properties + +/** + Number of objects in the array. + */ +@property (nonatomic, readonly, assign) NSUInteger count; + +/** + The class name (i.e. type) of the RLMObjects contained in this RLMArray. + */ +@property (nonatomic, readonly, copy) NSString *objectClassName; + +/** + The Realm in which this array is persisted. Returns nil for standalone arrays. + */ +@property (nonatomic, readonly, nullable) RLMRealm *realm; + +/** + Indicates if an array can no longer be accessed. + */ +@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; + +#pragma mark - Accessing Objects from an Array + +/** + Returns the object at the index specified. + + @param index The index to look up. + + @return An RLMObject of the type contained in this RLMArray. + */ +- (RLMObjectType)objectAtIndex:(NSUInteger)index; + +/** + Returns the first object in the array. + + Returns `nil` if called on an empty RLMArray. + + @return An RLMObject of the type contained in this RLMArray. + */ +- (nullable RLMObjectType)firstObject; + +/** + Returns the last object in the array. + + Returns `nil` if called on an empty RLMArray. + + @return An RLMObject of the type contained in this RLMArray. + */ +- (nullable RLMObjectType)lastObject; + + + +#pragma mark - Adding, Removing, and Replacing Objects in an Array + +/** + Adds an object to the end of the array. + + @warning This method can only be called during a write transaction. + + @param object An RLMObject of the type contained in this RLMArray. + */ +- (void)addObject:(RLMObjectArgument)object; + +/** + Adds an array of objects at the end of the array. + + @warning This method can only be called during a write transaction. + + @param objects An enumerable object such as NSArray or RLMResults which contains objects of the + same class as this RLMArray. + */ +- (void)addObjects:(id)objects; + +/** + Inserts an object at the given index. + + Throws an exception when the index exceeds the bounds of this RLMArray. + + @warning This method can only be called during a write transaction. + + @param anObject An RLMObject of the type contained in this RLMArray. + @param index The array index at which the object is inserted. + */ +- (void)insertObject:(RLMObjectArgument)anObject atIndex:(NSUInteger)index; + +/** + Removes an object at a given index. + + Throws an exception when the index exceeds the bounds of this RLMArray. + + @warning This method can only be called during a write transaction. + + @param index The array index identifying the object to be removed. + */ +- (void)removeObjectAtIndex:(NSUInteger)index; + +/** + Removes the last object in an RLMArray. + + @warning This method can only be called during a write transaction. +*/ +- (void)removeLastObject; + +/** + Removes all objects from an RLMArray. + + @warning This method can only be called during a write transaction. + */ +- (void)removeAllObjects; + +/** + Replaces an object at the given index with a new object. + + Throws an exception when the index exceeds the bounds of this RLMArray. + + @warning This method can only be called during a write transaction. + + @param index The array index of the object to be replaced. + @param anObject An object (of the same type as returned from the objectClassName selector). + */ +- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(RLMObjectArgument)anObject; + +/** + Moves the object at the given source index to the given destination index. + + Throws an exception when the index exceeds the bounds of this RLMArray. + + @warning This method can only be called during a write transaction. + + @param sourceIndex The index of the object to be moved. + @param destinationIndex The index to which the object at `sourceIndex` should be moved. + */ +- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex; + +/** + Exchanges the objects in the array at given indexes. + + Throws an exception when either index exceeds the bounds of this RLMArray. + + @warning This method can only be called during a write transaction. + + @param index1 The index of the object with which to replace the object at index `index2`. + @param index2 The index of the object with which to replace the object at index `index1`. + */ +- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2; + +#pragma mark - Querying an Array + +/** + Gets the index of an object. + + Returns NSNotFound if the object is not found in this RLMArray. + + @param object An object (of the same type as returned from the objectClassName selector). + */ +- (NSUInteger)indexOfObject:(RLMObjectArgument)object; + +/** + Gets the index of the first object matching the predicate. + + @param predicateFormat The predicate format string which can accept variable arguments. + + @return Index of object or NSNotFound if the object is not found in this RLMArray. + */ +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Gets the index of the first object matching the predicate. + + @param predicate The predicate to filter the objects. + + @return Index of object or NSNotFound if the object is not found in this RLMArray. + */ +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate; + +/** + Get objects matching the given predicate in the RLMArray. + + @param predicateFormat The predicate format string which can accept variable arguments. + + @return An RLMResults of objects that match the given predicate + */ +- (RLMResults RLM_GENERIC_RETURN*)objectsWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (RLMResults RLM_GENERIC_RETURN*)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Get objects matching the given predicate in the RLMArray. + + @param predicate The predicate to filter the objects. + + @return An RLMResults of objects that match the given predicate + */ +- (RLMResults RLM_GENERIC_RETURN*)objectsWithPredicate:(NSPredicate *)predicate; + +/** + Get a sorted RLMResults from an RLMArray + + @param property The property name to sort by. + @param ascending The direction to sort by. + + @return An RLMResults sorted by the specified property. + */ +- (RLMResults RLM_GENERIC_RETURN*)sortedResultsUsingProperty:(NSString *)property ascending:(BOOL)ascending; + +/** + Get a sorted RLMResults from an RLMArray + + @param properties An array of `RLMSortDescriptor`s to sort by. + + @return An RLMResults sorted by the specified properties. + */ +- (RLMResults RLM_GENERIC_RETURN*)sortedResultsUsingDescriptors:(NSArray *)properties; + +/// :nodoc: +- (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index; + +/// :nodoc: +- (void)setObject:(RLMObjectType)newValue atIndexedSubscript:(NSUInteger)index; + +#pragma mark - Notifications + +/** + Register a block to be called each time the RLMArray changes. + + The block will be asynchronously called with the initial array, and then + called again after each write transaction which changes the array or any + items contained in the array. You must retain the returned token for as long as + you want the block to continue to be called. To stop receiving updates, call + `-stop` on the token. + + The error parameter will always be `nil`, and is present only for compatiblity + with the RLMResults version of this method, which can potentially fail. + + @param block The block to be called each time the array changes. + @return A token which must be held for as long as you want notifications to be delivered. + */ +- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray RLM_GENERIC_RETURN *array, NSError *))block RLM_WARN_UNUSED_RESULT; + +#pragma mark - Unavailable Methods + +/** + -[RLMArray init] is not available because RLMArrays cannot be created directly. + RLMArray properties on RLMObjects are lazily created when accessed, or can be obtained by querying a Realm. + */ +- (instancetype)init __attribute__((unavailable("RLMArrays cannot be created directly"))); + +/** + +[RLMArray new] is not available because RLMArrays cannot be created directly. + RLMArray properties on RLMObjects are lazily created when accessed, or can be obtained by querying a Realm. + */ ++ (instancetype)new __attribute__((unavailable("RLMArrays cannot be created directly"))); + +@end + +/** + An RLMSortDescriptor stores a property name and a sort order for use with + `sortedResultsUsingDescriptors:`. It is similar to NSSortDescriptor, but supports + only the subset of functionality which can be efficiently run by the query + engine. RLMSortDescriptor instances are immutable. + */ +@interface RLMSortDescriptor : NSObject + +#pragma mark - Properties + +/** + The name of the property which this sort descriptor orders results by. + */ +@property (nonatomic, readonly) NSString *property; + +/** + Whether this descriptor sorts in ascending or descending order. + */ +@property (nonatomic, readonly) BOOL ascending; + +#pragma mark - Methods + +/** + Returns a new sort descriptor for the given property name and order. + */ ++ (instancetype)sortDescriptorWithProperty:(NSString *)propertyName ascending:(BOOL)ascending; + +/** + Returns a copy of the receiver with the sort order reversed. + */ +- (instancetype)reversedSortDescriptor; + +@end + +/// :nodoc: +@interface RLMArray (Swift) +// for use only in Swift class definitions +- (instancetype)initWithObjectClassName:(NSString *)objectClassName; +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMCollection.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMCollection.h new file mode 100644 index 000000000..a1a4efb05 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMCollection.h @@ -0,0 +1,184 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMRealm, RLMResults, RLMObject, RLMSortDescriptor, RLMNotificationToken; + +/** + A homogenous collection of `RLMObject`s like `RLMArray` or `RLMResults`. + */ +@protocol RLMCollection + +@required + +#pragma mark - Properties + +/** + Number of objects in the collection. + */ +@property (nonatomic, readonly, assign) NSUInteger count; + +/** + The class name (i.e. type) of the RLMObjects contained in this RLMCollection. + */ +@property (nonatomic, readonly, copy) NSString *objectClassName; + +/** + The Realm in which this collection is persisted. Returns nil for standalone collections. + */ +@property (nonatomic, readonly) RLMRealm *realm; + +#pragma mark - Accessing Objects from a Collection + +/** + Returns the object at the index specified. + + @param index The index to look up. + + @return An RLMObject of the type contained in this RLMCollection. + */ +- (id)objectAtIndex:(NSUInteger)index; + +/** + Returns the first object in the collection. + + Returns `nil` if called on an empty RLMCollection. + + @return An RLMObject of the type contained in this RLMCollection. + */ +- (nullable id)firstObject; + +/** + Returns the last object in the collection. + + Returns `nil` if called on an empty RLMCollection. + + @return An RLMObject of the type contained in this RLMCollection. + */ +- (nullable id)lastObject; + +#pragma mark - Querying a Collection + +/** + Gets the index of an object. + + Returns NSNotFound if the object is not found in this RLMCollection. + + @param object An object (of the same type as returned from the objectClassName selector). + */ +- (NSUInteger)indexOfObject:(RLMObject *)object; + +/** + Gets the index of the first object matching the predicate. + + @param predicateFormat The predicate format string which can accept variable arguments. + + @return Index of object or NSNotFound if the object is not found in this RLMCollection. + */ +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Gets the index of the first object matching the predicate. + + @param predicate The predicate to filter the objects. + + @return Index of object or NSNotFound if the object is not found in this RLMCollection. + */ +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate; + +/** + Get objects matching the given predicate in the RLMCollection. + + @param predicateFormat The predicate format string which can accept variable arguments. + + @return An RLMResults of objects that match the given predicate + */ +- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Get objects matching the given predicate in the RLMCollection. + + @param predicate The predicate to filter the objects. + + @return An RLMResults of objects that match the given predicate + */ +- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate; + +/** + Get a sorted RLMResults from an RLMCollection. + + @param property The property name to sort by. + @param ascending The direction to sort by. + + @return An RLMResults sorted by the specified property. + */ +- (RLMResults *)sortedResultsUsingProperty:(NSString *)property ascending:(BOOL)ascending; + +/** + Get a sorted RLMResults from an RLMCollection. + + @param properties An array of `RLMSortDescriptor`s to sort by. + + @return An RLMResults sorted by the specified properties. + */ +- (RLMResults *)sortedResultsUsingDescriptors:(NSArray RLM_GENERIC(RLMSortDescriptor *) *)properties; + +/// :nodoc: +- (id)objectAtIndexedSubscript:(NSUInteger)index; + +/** + Returns an NSArray containing the results of invoking `valueForKey:` using key on each of the collection's objects. + + @param key The name of the property. + + @return NSArray containing the results of invoking `valueForKey:` using key on each of the collection's objects. + */ +- (nullable id)valueForKey:(NSString *)key; + +/** + Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key. + + @warning This method can only be called during a write transaction. + + @param value The object value. + @param key The name of the property. + */ +- (void)setValue:(nullable id)value forKey:(NSString *)key; + +#pragma mark - Notifications + +/** + Register a block to be called each time the collection changes. + + @param block The block to be called each time the collection changes. + @return A token which must be held for as long as you want notifications to be delivered. + */ +- (RLMNotificationToken *)addNotificationBlock:(void (^)(id collection))block RLM_WARN_UNUSED_RESULT; + +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMConstants.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMConstants.h new file mode 100644 index 000000000..3befba119 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMConstants.h @@ -0,0 +1,131 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#pragma mark - Enums + +/** + Property types supported in Realm models. + + See [Realm Models](https://realm.io/docs/objc/latest/#models) + */ +// Make sure numbers match those in +typedef NS_ENUM(int32_t, RLMPropertyType) { + +#pragma mark - Primitive types + + /** Integer type: NSInteger, int, long, Int (Swift) */ + RLMPropertyTypeInt = 0, + /** Boolean type: BOOL, bool, Bool (Swift) */ + RLMPropertyTypeBool = 1, + /** Float type: float, Float (Swift) */ + RLMPropertyTypeFloat = 9, + /** Double type: double, Double (Swift) */ + RLMPropertyTypeDouble = 10, + +#pragma mark - Object types + + /** String type: NSString, String (Swift) */ + RLMPropertyTypeString = 2, + /** Data type: NSData */ + RLMPropertyTypeData = 4, + /** Any type: id, **not supported in Swift** */ + RLMPropertyTypeAny = 6, + /** Date type: NSDate */ + RLMPropertyTypeDate = 7, + +#pragma mark - Array/Linked object types + + /** Object type. See [Realm Models](https://realm.io/docs/objc/latest/#models) */ + RLMPropertyTypeObject = 12, + /** Array type. See [Realm Models](http://realms.io/docs/objc/latest/#models) */ + RLMPropertyTypeArray = 13, +}; + +/** + Enum representing all recoverable errors in Realm. + */ +typedef NS_ENUM(NSInteger, RLMError) { + /** Returned by RLMRealm if no other specific error is returned when a realm is opened. */ + RLMErrorFail = 1, + /** Returned by RLMRealm for any I/O related exception scenarios when a realm is opened. */ + RLMErrorFileAccess = 2, + /** Returned by RLMRealm if the user does not have permission to open or create + the specified file in the specified access mode when the realm is opened. */ + RLMErrorFilePermissionDenied = 3, + /** Returned by RLMRealm if the file already exists when a copy should be written. */ + RLMErrorFileExists = 4, + /** Returned by RLMRealm if no file was found when a realm was opened as + read-only or if the directory part of the specified path was not + found when a copy should be written. */ + RLMErrorFileNotFound = 5, + /** Returned by RLMRealm if a file format upgrade is required to open the file, but upgrades were explicilty disabled. */ + RLMErrorFileFormatUpgradeRequired = 6, + /** Returned by RLMRealm if the database file is currently open in another + process which cannot share with the current process due to an + architecture mismatch. */ + RLMErrorIncompatibleLockFile = 8, +}; + +#pragma mark - Constants + +#pragma mark - Notification Constants + +/** + Posted by RLMRealm when the data in the realm has changed. + + DidChange are posted after a realm has been refreshed to reflect a write + transaction, i.e. when an autorefresh occurs, `[RLMRealm refresh]` is + called, after an implicit refresh from `[RLMRealm beginWriteTransaction]`, + and after a local write transaction is committed. + */ +extern NSString * const RLMRealmRefreshRequiredNotification; + +/** + Posted by RLMRealm when a write transaction has been committed to an RLMRealm on + a different thread for the same file. This is not posted if + `[RLMRealm autorefresh]` is enabled or if the RLMRealm is + refreshed before the notifcation has a chance to run. + + Realms with autorefresh disabled should normally have a handler for this + notification which calls `[RLMRealm refresh]` after doing some work. + While not refreshing is allowed, it may lead to large Realm files as Realm has + to keep an extra copy of the data for the un-refreshed RLMRealm. + */ +extern NSString * const RLMRealmDidChangeNotification; + +#pragma mark - Other Constants + +/** Schema version used for uninitialized Realms */ +extern const uint64_t RLMNotVersioned; + +/** Error domain used in Realm. */ +extern NSString * const RLMErrorDomain; + +/** Key for name of Realm exceptions. */ +extern NSString * const RLMExceptionName; + +/** Key for Realm file version. */ +extern NSString * const RLMRealmVersionKey; + +/** Key for Realm core version. */ +extern NSString * const RLMRealmCoreVersionKey; + +/** Key for Realm invalidated property name. */ +extern NSString * const RLMInvalidatedKey; diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMDefines.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMDefines.h new file mode 100644 index 000000000..73afc0328 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMDefines.h @@ -0,0 +1,95 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMObject; + +#ifndef __has_feature +#define __has_feature(x) 0 +#endif + +#pragma mark - Generics + +#if __has_extension(objc_generics) +#define RLM_GENERIC(...) <__VA_ARGS__> +#define RLM_GENERIC_COLLECTION +#define RLM_GENERIC_RETURN +#define RLMObjectArgument RLMObjectType +#else +#define RLM_GENERIC(...) +#define RLM_GENERIC_COLLECTION +#define RLM_GENERIC_RETURN +typedef id RLMObjectType; +typedef RLMObject * RLMObjectArgument; +#endif + +#pragma mark - Nullability + +#if !__has_feature(nullability) +#ifndef __nullable +#define __nullable +#endif +#ifndef __nonnull +#define __nonnull +#endif +#ifndef __null_unspecified +#define __null_unspecified +#endif +#ifndef nullable +#define nullable +#endif +#ifndef nonnull +#define nonnull +#endif +#ifndef null_unspecified +#define null_unspecified +#endif +#endif + +#if defined(NS_ASSUME_NONNULL_BEGIN) && defined(NS_ASSUME_NONNULL_END) +#define RLM_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN +#define RLM_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END +#else +#define RLM_ASSUME_NONNULL_BEGIN +#define RLM_ASSUME_NONNULL_END +#endif + +#pragma mark - Escaping + +#if __has_attribute(noescape) +# define RLM_NOESCAPE __attribute__((noescape)) +#else +# define RLM_NOESCAPE +#endif + +#pragma mark - Unused Result + +#if __has_attribute(warn_unused_result) +# define RLM_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#else +# define RLM_WARN_UNUSED_RESULT +#endif + +#pragma mark - Swift Availability + +#if defined(NS_SWIFT_UNAVAILABLE) +# define RLM_SWIFT_UNAVAILABLE(msg) NS_SWIFT_UNAVAILABLE(msg) +#else +# define RLM_SWIFT_UNAVAILABLE(msg) +#endif diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMMigration.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMMigration.h new file mode 100644 index 000000000..3eb9b6727 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMMigration.h @@ -0,0 +1,107 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMSchema; +@class RLMArray; +@class RLMObject; + +/** +Provides both the old and new versions of an object in this Realm. Object properties can only be +accessed using keyed subscripting. + +@param oldObject Object in original RLMRealm (read-only). +@param newObject Object in migrated RLMRealm (read-write). +*/ +typedef void (^RLMObjectMigrationBlock)(RLMObject * __nullable oldObject, RLMObject * __nullable newObject); + +/** + RLMMigration is the object passed into a user defined RLMMigrationBlock when updating the version + of an RLMRealm instance. + + This object provides access to the RLMSchema current to this migration. + */ +@interface RLMMigration : NSObject + +#pragma mark - Properties + +/** + Get the old RLMSchema for the migration. This is the schema which describes the RLMRealm before the + migration is applied. + */ +@property (nonatomic, readonly) RLMSchema *oldSchema; + +/** + Get the new RLMSchema for the migration. This is the schema which describes the RLMRealm after applying + a migration. + */ +@property (nonatomic, readonly) RLMSchema *newSchema; + + +#pragma mark - Altering Objects during a Migration + +/** + Enumerates objects of a given type in this Realm, providing both the old and new versions of each object. + Objects properties can be accessed using keyed subscripting. + + @param className The name of the RLMObject class to enumerate. + + @warning All objects returned are of a type specific to the current migration and should not be casted + to className. Instead you should access them as RLMObjects and use keyed subscripting to access + properties. + */ +- (void)enumerateObjects:(NSString *)className block:(RLMObjectMigrationBlock)block; + +/** + Create an RLMObject of type `className` in the Realm being migrated. + + @param className The name of the RLMObject class to create. + @param value The value used to populate the created object. This can be any key/value coding compliant + object, or a JSON object such as those returned from the methods in NSJSONSerialization, or + an NSArray with one object for each persisted property. An exception will be + thrown if any required properties are not present and no default is set. + + When passing in an NSArray, all properties must be present, valid and in the same order as the properties defined in the model. + */ +-(RLMObject *)createObject:(NSString *)className withValue:(id)value; + +/** + Delete an object from a Realm during a migration. This can be called within `enumerateObjects:block:`. + + @param object Object to be deleted from the Realm being migrated. + */ +- (void)deleteObject:(RLMObject *)object; + +/** + Deletes the data for the class with the given name. + This deletes all objects of the given class, and if the RLMObject subclass no longer exists in your program, + cleans up any remaining metadata for the class in the Realm file. + + @param name The name of the RLMObject class to delete. + + @return whether there was any data to delete. + */ +- (BOOL)deleteDataForClassName:(NSString *)name; + +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObject.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObject.h new file mode 100644 index 000000000..0047be1b1 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObject.h @@ -0,0 +1,425 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMRealm; +@class RLMResults; +@class RLMObjectSchema; + +/** + + In Realm you define your model classes by subclassing `RLMObject` and adding properties to be persisted. + You then instantiate and use your custom subclasses instead of using the `RLMObject` class directly. + + // Dog.h + @interface Dog : RLMObject + @property NSString *name; + @property BOOL adopted; + @end + + // Dog.m + @implementation Dog + @end //none needed + + ### Supported property types + + - `NSString` + - `NSInteger`, `int`, `long`, `float`, and `double` + - `BOOL` or `bool` + - `NSDate` + - `NSData` + - `NSNumber`, where X is one of RLMInt, RLMFloat, RLMDouble or RLMBool, for optional number properties + - `RLMObject` subclasses, so you can have many-to-one relationships. + - `RLMArray`, where X is an `RLMObject` subclass, so you can have many-to-many relationships. + + ### Querying + + You can query an object directly via the class methods: `allObjects`, `objectsWhere:`, and `objectsWithPredicate:`. + These methods allow you to easily query a custom subclass for instances of this class in the + default Realm. To search in a Realm other than the default Realm use the interface on an RLMRealm instance. + + ### Relationships + + See our [Cocoa guide](https://realm.io/docs/objc/latest#relationships) for more details. + + ### Key-Value Observing + + All `RLMObject` properties (including properties you create in subclasses) are + [Key-Value Observing compliant](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html), + except for `realm` and `objectSchema`. There are several Realm-specific things + to keep in mind when observing Realm objects: + + 1. Unlike `NSMutableArray` properties, `RLMArray` properties do not require + using the proxy object returned from `-mutableArrayValueForKey:`, or defining + KVC mutation methods on the containing class. You can simply call methods on + the RLMArray directly and the changes will be observed by the containing + object. + 2. Standalone `RLMObjects` cannot be added to a Realm while they have any + observed properties. + 3. Modifying persisted `RLMObjects` in `-observeValueForKeyPath:ofObject:change:context:` + is problematic. Properties may change when the Realm is not in a write + transaction (for example, when `-[RLMRealm refresh]` is called after changes + are made on a different thread), and notifications sent prior to the change + being applied (when `NSKeyValueObservingOptionPrior` is used) may be sent at + times when you *cannot* begin a write transaction. + */ + +@interface RLMObject : RLMObjectBase + +#pragma mark - Creating & Initializing Objects + +/** + Initialize a standalone RLMObject + + Initialize an unpersisted instance of this object. + Call addObject: on an RLMRealm to add standalone object to a realm. + + @see [RLMRealm addObject:]: + */ +- (instancetype)init NS_DESIGNATED_INITIALIZER; + + +/** + Initialize a standalone RLMObject with values from an NSArray or NSDictionary + + Initialize an unpersisted instance of this object. + Call addObject: on an RLMRealm to add standalone object to a realm. + + @see [RLMRealm addObject:]: + */ +- (instancetype)initWithValue:(id)value NS_DESIGNATED_INITIALIZER; + + +/** + Helper to return the class name for an RLMObject subclass. + + @warning Do not override. Realm relies on this method returning the exact class + name. + + @return The class name for the model class. + */ ++ (NSString *)className; + +/** + Create an RLMObject in the default Realm with a given value. + + Creates an instance of this object and adds it to the default Realm populating + the object with the given value. + + If nested objects are included in the argument, `createInDefaultRealmWithValue:` will be called + on them. + + @param value The value used to populate the object. This can be any key/value coding compliant + object, or a JSON object such as those returned from the methods in NSJSONSerialization, or + an NSArray with one object for each persisted property. An exception will be + thrown if any required properties are not present and no default is set. + + When passing in an NSArray, all properties must be present, valid and in the same order as the properties defined in the model. + + @see defaultPropertyValues + */ ++ (instancetype)createInDefaultRealmWithValue:(id)value; + +/** + Create an RLMObject in a Realm with a given object. + + Creates an instance of this object and adds it to the given Realm populating + the object with the given object. + + If nested objects are included in the argument, `createInRealm:withValue:` will be called + on them. + + @param realm The Realm in which this object is persisted. + @param value The value used to populate the object. This can be any key/value coding compliant + object, or a JSON object such as those returned from the methods in NSJSONSerialization, or + an NSArray with one object for each persisted property. An exception will be + thrown if any required properties are not present and no default is set. + + When passing in an NSArray, all properties must be present, valid and in the same order as the properties defined in the model. + + @see defaultPropertyValues + */ ++ (instancetype)createInRealm:(RLMRealm *)realm withValue:(id)value; + +/** + Create or update an RLMObject in the default Realm with a given object. + + This method can only be called on object types with a primary key defined. If there is already + an object with the same primary key value in the default RLMRealm its values are updated and the object + is returned. Otherwise this creates and populates a new instance of this object in the default Realm. + + If nested objects are included in the argument, `createOrUpdateInDefaultRealmWithValue:` will be + called on them if have a primary key (`createInDefaultRealmWithValue:` otherwise). + + This is a no-op if the argument is an RLMObject of the same type already backed by the target realm. + + @param value The value used to populate the object. This can be any key/value coding compliant + object, or a JSON object such as those returned from the methods in NSJSONSerialization, or + an NSArray with one object for each persisted property. An exception will be + thrown if any required properties are not present and no default is set. + + When passing in an NSArray, all properties must be present, valid and in the same order as the properties defined in the model. + + @see defaultPropertyValues, primaryKey + */ ++ (instancetype)createOrUpdateInDefaultRealmWithValue:(id)value; + +/** + Create or update an RLMObject with a given object. + + This method can only be called on object types with a primary key defined. If there is already + an object with the same primary key value in the provided RLMRealm its values are updated and the object + is returned. Otherwise this creates and populates a new instance of this object in the provided Realm. + + If nested objects are included in the argument, `createOrUpdateInRealm:withValue:` will be + called on them if have a primary key (`createInRealm:withValue:` otherwise). + + This is a no-op if the argument is an RLMObject of the same type already backed by the target realm. + + @param realm The Realm in which this object is persisted. + @param value The value used to populate the object. This can be any key/value coding compliant + object, or a JSON object such as those returned from the methods in NSJSONSerialization, or + an NSArray with one object for each persisted property. An exception will be + thrown if any required properties are not present and no default is set. + + When passing in an NSArray, all properties must be present, valid and in the same order as the properties defined in the model. + + @see defaultPropertyValues, primaryKey + */ ++ (instancetype)createOrUpdateInRealm:(RLMRealm *)realm withValue:(id)value; + +#pragma mark - Properties + +/** + The Realm in which this object is persisted. Returns nil for standalone objects. + */ +@property (nonatomic, readonly, nullable) RLMRealm *realm; + +/** + The ObjectSchema which lists the persisted properties for this object. + */ +@property (nonatomic, readonly) RLMObjectSchema *objectSchema; + +/** + Indicates if an object can no longer be accessed. + + An object can no longer be accessed if the object has been deleted from the containing `realm` or + if `invalidate` is called on the containing `realm`. + */ +@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; + + +#pragma mark - Customizing your Objects + +/** + Return an array of property names for properties which should be indexed. Only supported + for string and int properties. + @return NSArray of property names. + */ ++ (NSArray RLM_GENERIC(NSString *) *)indexedProperties; + +/** + Implement to indicate the default values to be used for each property. + + @return NSDictionary mapping property names to their default values. + */ ++ (nullable NSDictionary *)defaultPropertyValues; + +/** + Implement to designate a property as the primary key for an RLMObject subclass. Only properties of + type RLMPropertyTypeString and RLMPropertyTypeInt can be designated as the primary key. Primary key + properties enforce uniqueness for each value whenever the property is set which incurs some overhead. + Indexes are created automatically for primary key properties. + + @return Name of the property designated as the primary key. + */ ++ (nullable NSString *)primaryKey; + +/** + Implement to return an array of property names to ignore. These properties will not be persisted + and are treated as transient. + + @return NSArray of property names to ignore. + */ ++ (nullable NSArray RLM_GENERIC(NSString *) *)ignoredProperties; + +/** + Implement to return an array of property names that should not allow storing nil. + + By default, all properties of a type that support storing nil are considered optional properties. + To require that an object in a Realm always have a non-nil value for a property, + add the name of the property to the array returned from this method. + + Currently Object properties cannot be required. Array and NSNumber properties + can, but it makes little sense to do so: arrays do not support storing nil, and + if you want a non-optional number you should instead use the primitive type. + + @return NSArray of property names that are required. + */ ++ (NSArray RLM_GENERIC(NSString *) *)requiredProperties; + + +#pragma mark - Getting & Querying Objects from the Default Realm + +/** + Get all objects of this type from the default Realm. + + @return An RLMResults of all objects of this type in the default Realm. + */ ++ (RLMResults *)allObjects; + +/** + Get objects matching the given predicate for this type from the default Realm. + + @param predicateFormat The predicate format string which can accept variable arguments. + + @return An RLMResults of objects of the subclass type in the default Realm that match the given predicate + */ ++ (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: ++ (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + + +/** + Get objects matching the given predicate for this type from the default Realm. + + @param predicate The predicate to filter the objects. + + @return An RLMResults of objects of the subclass type in the default Realm that match the given predicate + */ ++ (RLMResults *)objectsWithPredicate:(nullable NSPredicate *)predicate; + +/** + Get the single object with the given primary key from the default Realm. + + Returns the object from the default Realm which has the given primary key, or + `nil` if the object does not exist. This is slightly faster than the otherwise + equivalent `[[SubclassName objectsWhere:@"primaryKeyPropertyName = %@", key] firstObject]`. + + This method requires that `primaryKey` be overridden on the receiving subclass. + + @return An object of the subclass type or nil if an object with the given primary key does not exist. + @see -primaryKey + */ ++ (nullable instancetype)objectForPrimaryKey:(nullable id)primaryKey; + + +#pragma mark - Querying Specific Realms + +/** + Get all objects of this type from the specified Realm. + + @param realm The Realm instance to query. + + @return An RLMResults of all objects of this type in the specified Realm. + */ ++ (RLMResults *)allObjectsInRealm:(RLMRealm *)realm; + +/** + Get objects matching the given predicate for this type from the specified Realm. + + @param predicateFormat The predicate format string which can accept variable arguments. + @param realm The Realm instance to query. + + @return An RLMResults of objects of the subclass type in the specified Realm that match the given predicate + */ ++ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat, ...; + +/// :nodoc: ++ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat args:(va_list)args; + +/** + Get objects matching the given predicate for this type from the specified Realm. + + @param predicate The predicate to filter the objects. + @param realm The Realm instance to query. + + @return An RLMResults of objects of the subclass type in the specified Realm that match the given predicate + */ ++ (RLMResults *)objectsInRealm:(RLMRealm *)realm withPredicate:(nullable NSPredicate *)predicate; + +/** + Get the single object with the given primary key from the specified Realm. + + Returns the object from the specified Realm which has the given primary key, or + `nil` if the object does not exist. This is slightly faster than the otherwise + equivalent `[[SubclassName objectsInRealm:realm where:@"primaryKeyPropertyName = %@", key] firstObject]`. + + This method requires that `primaryKey` be overridden on the receiving subclass. + + @return An object of the subclass type or nil if an object with the given primary key does not exist. + @see -primaryKey + */ ++ (nullable instancetype)objectInRealm:(RLMRealm *)realm forPrimaryKey:(nullable id)primaryKey; + +#pragma mark - Other Instance Methods + +/** + Get an `NSArray` of objects of type `className` which have this object as the given property value. This can + be used to get the inverse relationship value for `RLMObject` and `RLMArray` properties. + + @param className The type of object on which the relationship to query is defined. + @param property The name of the property which defines the relationship. + + @return An NSArray of objects of type `className` which have this object as their value for the `property` property. + */ +- (NSArray *)linkingObjectsOfClass:(NSString *)className forProperty:(NSString *)property; + +/** + Returns YES if another RLMObject points to the same object in an RLMRealm. For RLMObject types + with a primary, key, `isEqual:` is overridden to use this method (along with a corresponding + implementation for `hash`. + + @param object The object to compare to. + + @return YES if the object represents the same object in the same RLMRealm. + */ +- (BOOL)isEqualToObject:(RLMObject *)object; + +#pragma mark - Dynamic Accessors + +/// :nodoc: +- (nullable id)objectForKeyedSubscript:(NSString *)key; + +/// :nodoc: +- (void)setObject:(nullable id)obj forKeyedSubscript:(NSString *)key; + +@end + +#pragma mark - RLMArray Property Declaration + +/** + Properties on RLMObjects of type RLMArray must have an associated type. A type is associated + with an RLMArray property by defining a protocol for the object type which the RLMArray will + hold. To define the protocol for an object you can use the macro RLM_ARRAY_TYPE: + + RLM_ARRAY_TYPE(ObjectType) + ... + @property RLMArray *arrayOfObjectTypes; + */ +#define RLM_ARRAY_TYPE(RLM_OBJECT_SUBCLASS)\ +@protocol RLM_OBJECT_SUBCLASS \ +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObjectBase.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObjectBase.h new file mode 100644 index 000000000..739e0f088 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObjectBase.h @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMRealm; +@class RLMSchema; +@class RLMObjectSchema; + +/// :nodoc: +@interface RLMObjectBase : NSObject + +@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; + +- (instancetype)init; + ++ (NSString *)className; + +// Returns whether the class is included in the default set of classes persisted in a Realm. ++ (BOOL)shouldIncludeInDefaultSchema; + +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObjectBase_Dynamic.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObjectBase_Dynamic.h new file mode 100644 index 000000000..247bdf1b6 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObjectBase_Dynamic.h @@ -0,0 +1,84 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMObjectSchema, RLMRealm; + +/** + This function is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to retrieve `realm` via `RLMObject`. + + @param object an RLMObjectBase obtained via a Swift Object or RLMObject + + @return The Realm in which this object is persisted. Returns nil for standalone objects. + */ +FOUNDATION_EXTERN RLMRealm *RLMObjectBaseRealm(RLMObjectBase *object); + +/** + This function is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to retrieve `objectSchema` via `RLMObject`. + + @param object an RLMObjectBase obtained via a Swift Object or RLMObject + + @return The ObjectSchema which lists the persisted properties for this object. + */ +FOUNDATION_EXTERN RLMObjectSchema *RLMObjectBaseObjectSchema(RLMObjectBase *object); + +/** + This function is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to retrieve the linking objects via `RLMObject`. + + @param object an RLMObjectBase obtained via a Swift Object or RLMObject + @param className The type of object on which the relationship to query is defined. + @param property The name of the property which defines the relationship. + + @return An NSArray of objects of type `className` which have this object as their value for the `property` property. + */ +FOUNDATION_EXTERN NSArray *RLMObjectBaseLinkingObjectsOfClass(RLMObjectBase *object, NSString *className, NSString *property); + +/** + This function is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to retrieve key values via `RLMObject`. + + @warning Will throw `NSUndefinedKeyException` if key is not present on the object + + @param object an RLMObjectBase obtained via a Swift Object or RLMObject + @param key The name of the property + + @return the object for the property requested + */ +FOUNDATION_EXTERN id RLMObjectBaseObjectForKeyedSubscript(RLMObjectBase *object, NSString *key); + +/** + This function is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to set key values via `RLMObject`. + + @warning Will throw `NSUndefinedKeyException` if key is not present on the object + + @param object an RLMObjectBase obtained via a Swift Object or RLMObject + @param key The name of the property + @param obj The object to set as the value of the key + */ +FOUNDATION_EXTERN void RLMObjectBaseSetObjectForKeyedSubscript(RLMObjectBase *object, NSString *key, id obj); + diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObjectSchema.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObjectSchema.h new file mode 100644 index 000000000..3aa15d7cc --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMObjectSchema.h @@ -0,0 +1,73 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMProperty; + +/** + This class represents Realm model object schemas. + + When using Realm, RLMObjectSchema objects allow performing migrations and + introspecting the database's schema. + + Object schemas map to tables in the core database. + */ +@interface RLMObjectSchema : NSObject + +#pragma mark - Properties + +/** + Array of persisted RLMProperty objects for an object. + + @see RLMProperty + */ +@property (nonatomic, readonly, copy) NSArray RLM_GENERIC(RLMProperty *) *properties; + +/** + The name of the class this schema describes. + */ +@property (nonatomic, readonly) NSString *className; + +/** + The property which is the primary key for this object (if any). + */ +@property (nonatomic, readonly, nullable) RLMProperty *primaryKeyProperty; + +#pragma mark - Methods + +/** + Retrieve an RLMProperty object by name. + + @param propertyName The property's name. + + @return RLMProperty object or nil if there is no property with the given name. + */ +- (nullable RLMProperty *)objectForKeyedSubscript:(id )propertyName; + +/** + Returns YES if equal to objectSchema +*/ +- (BOOL)isEqualToObjectSchema:(RLMObjectSchema *)objectSchema; + +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMPlatform.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMPlatform.h new file mode 100644 index 000000000..e72f1f569 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMPlatform.h @@ -0,0 +1,22 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#if TARGET_OS_IPHONE +#error Attempting to use Realm's OSX framework in an iOS project. +#endif + diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMProperty.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMProperty.h new file mode 100644 index 000000000..2f610208b --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMProperty.h @@ -0,0 +1,95 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +/// :nodoc: +@protocol RLMInt +@end + +/// :nodoc: +@protocol RLMBool +@end + +/// :nodoc: +@protocol RLMDouble +@end + +/// :nodoc: +@protocol RLMFloat +@end + +/// :nodoc: +@interface NSNumber () +@end + +/** + This class models properties persisted to Realm in an RLMObjectSchema. + + When using Realm, RLMProperty objects allow performing migrations and + introspecting the database's schema. + + These properties map to columns in the core database. + */ +@interface RLMProperty : NSObject + +#pragma mark - Properties + +/** + Property name. + */ +@property (nonatomic, readonly) NSString *name; + +/** + Property type. + + @see RLMPropertyType + */ +@property (nonatomic, readonly) RLMPropertyType type; + +/** + Indicates if this property is indexed. + + @see RLMObject + */ +@property (nonatomic, readonly) BOOL indexed; + +/** + Object class name - specify object types for RLMObject and RLMArray properties. + */ +@property (nonatomic, readonly, copy, nullable) NSString *objectClassName; + +/** + Whether this property is optional. + */ +@property (nonatomic, readonly) BOOL optional; + +#pragma mark - Methods + +/** + Returns YES if property objects are equal. + */ +- (BOOL)isEqualToProperty:(RLMProperty *)property; + +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMRealm.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMRealm.h new file mode 100644 index 000000000..0672725b6 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMRealm.h @@ -0,0 +1,519 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +@class RLMRealmConfiguration, RLMObject, RLMSchema, RLMMigration, RLMNotificationToken; + +RLM_ASSUME_NONNULL_BEGIN + +/** + An RLMRealm instance (also referred to as "a realm") represents a Realm + database. + + Realms can either be stored on disk (see +[RLMRealm realmWithPath:]) or in + memory (see RLMRealmConfiguration). + + RLMRealm instances are cached internally, and constructing equivalent RLMRealm + objects (with the same path or identifier) multiple times on a single thread + within a single iteration of the run loop will normally return the same + RLMRealm object. If you specifically want to ensure a RLMRealm object is + destroyed (for example, if you wish to open a realm, check some property, and + then possibly delete the realm file and re-open it), place the code which uses + the realm within an `@autoreleasepool {}` and ensure you have no other + strong references to it. + + @warning RLMRealm instances are not thread safe and can not be shared across + threads or dispatch queues. You must call this method on each thread you want + to interact with the realm on. For dispatch queues, this means that you must + call it in each block which is dispatched, as a queue is not guaranteed to run + on a consistent thread. + */ + +@interface RLMRealm : NSObject + +#pragma mark - Creating & Initializing a Realm + +/** + Obtains an instance of the default Realm. + + The default Realm is used by the `RLMObject` class methods + which do not take a `RLMRealm` parameter, but is otherwise not special. The + default Realm is persisted as default.realm under the Documents directory of + your Application on iOS, and in your application's Application Support + directory on OS X. + + The default Realm is created using the default `RLMRealmConfiguration`, which + can be changed via `+[RLMRealmConfiguration setDefaultConfiguration:]`. + + @return The default `RLMRealm` instance for the current thread. + */ ++ (instancetype)defaultRealm; + +/** + Obtains an `RLMRealm` instance with the given configuration. + + @param configuration The configuration for the realm. + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return An `RLMRealm` instance. + */ ++ (nullable instancetype)realmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error; + +/** + Obtains an `RLMRealm` instance persisted at a specific file path. + + @param path Path to the file you want the data saved in. + + @return An `RLMRealm` instance. + */ ++ (instancetype)realmWithPath:(NSString *)path; + +/** + Path to the file where this Realm is persisted. + */ +@property (nonatomic, readonly) NSString *path; + +/** + Indicates if this Realm was opened in read-only mode. + */ +@property (nonatomic, readonly, getter = isReadOnly) BOOL readOnly; + +/** + The RLMSchema used by this RLMRealm. + */ +@property (nonatomic, readonly, null_unspecified) RLMSchema *schema; + +/** + Indicates if this Realm is currently in a write transaction. + + @warning Wrapping mutating operations in a write transaction if this property returns `NO` + may cause a large number of write transactions to be created, which could negatively + impact Realm's performance. Always prefer performing multiple mutations in a single + transaction when possible. + */ +@property (nonatomic, readonly) BOOL inWriteTransaction; + +/** + Returns the `RLMRealmConfiguration` that was used to create this `RLMRealm` instance. + */ +@property (nonatomic, readonly) RLMRealmConfiguration *configuration; + +/** + Indicates if this Realm contains any objects. + */ +@property (nonatomic, readonly) BOOL isEmpty; + +#pragma mark - Notifications + +/// Block to run when the data in a Realm was modified. +typedef void (^RLMNotificationBlock)(NSString *notification, RLMRealm *realm); + +#pragma mark - Receiving Notification when a Realm Changes + +/** + Add a notification handler for changes in this RLMRealm. + + Notification handlers are called after each write transaction is committed, + either on the current thread or other threads. The block is called on the same + thread as they were added on, and can only be added on threads which are + currently within a run loop. Unless you are specifically creating and running a + run loop on a background thread, this normally will only be the main thread. + + The block has the following definition: + + typedef void(^RLMNotificationBlock)(NSString *notification, RLMRealm *realm); + + It receives the following parameters: + + - `NSString` \***notification**: The name of the incoming notification. See + RLMRealmNotification for information on what + notifications are sent. + - `RLMRealm` \***realm**: The realm for which this notification occurred + + @param block A block which is called to process RLMRealm notifications. + + @return A token object which must be stored as long as you wish to continue + receiving change notifications. + */ +- (RLMNotificationToken *)addNotificationBlock:(RLMNotificationBlock)block RLM_WARN_UNUSED_RESULT; + +/** + Remove a previously registered notification handler using the token returned + from `-addNotificationBlock:` + + @param notificationToken The token returned from `-addNotificationBlock:` + corresponding to the notification block to remove. + */ +- (void)removeNotification:(RLMNotificationToken *)notificationToken; + +#pragma mark - Transactions + + +#pragma mark - Writing to a Realm + +/** + Begins a write transaction in an `RLMRealm`. + + Only one write transaction can be open at a time. Write transactions cannot be + nested, and trying to begin a write transaction on a `RLMRealm` which is + already in a write transaction will throw an exception. Calls to + `beginWriteTransaction` from `RLMRealm` instances in other threads will block + until the current write transaction completes. + + Before beginning the write transaction, `beginWriteTransaction` updates the + `RLMRealm` to the latest Realm version, as if refresh was called, and + generates notifications if applicable. This has no effect if the `RLMRealm` + was already up to date. + + It is rarely a good idea to have write transactions span multiple cycles of + the run loop, but if you do wish to do so you will need to ensure that the + `RLMRealm` in the write transaction is kept alive until the write transaction + is committed. + */ +- (void)beginWriteTransaction; + +/** + Commits all write operations in the current write transaction, and ends the + transaction. + + @warning This method can only be called during a write transaction. + */ +- (void)commitWriteTransaction RLM_SWIFT_UNAVAILABLE(""); + +/** + Commits all write operations in the current write transaction, and ends the + transaction. + + @warning This method can only be called during a write transaction. + + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return Whether the transaction succeeded. + */ +- (BOOL)commitWriteTransaction:(NSError **)error; + +/** + Reverts all writes made in the current write transaction and ends the transaction. + + This rolls back all objects in the Realm to the state they were in at the + beginning of the write transaction, and then ends the transaction. + + This restores the data for deleted objects, but does not revive invalidated + object instances. Any `RLMObject`s which were added to the Realm will be + invalidated rather than switching back to standalone objects. + Given the following code: + + ObjectType *oldObject = [[ObjectType objectsWhere:@"..."] firstObject]; + ObjectType *newObject = [[ObjectType alloc] init]; + + [realm beginWriteTransaction]; + [realm addObject:newObject]; + [realm deleteObject:oldObject]; + [realm cancelWriteTransaction]; + + Both `oldObject` and `newObject` will return `YES` for `isInvalidated`, + but re-running the query which provided `oldObject` will once again return + the valid object. + + @warning This method can only be called during a write transaction. + */ +- (void)cancelWriteTransaction; + +/** + Helper to perform a block within a transaction. + */ +- (void)transactionWithBlock:(RLM_NOESCAPE void(^)(void))block RLM_SWIFT_UNAVAILABLE(""); + +/** + Performs actions contained within the given block inside a write transation. + + Write transactions cannot be nested, and trying to execute a write transaction + on a `RLMRealm` which is already in a write transaction will throw an + exception. Calls to `transactionWithBlock:` from `RLMRealm` instances in other + threads will block until the current write transaction completes. + + Before beginning the write transaction, `transactionWithBlock:` updates the + `RLMRealm` to the latest Realm version, as if refresh was called, and + generates notifications if applicable. This has no effect if the `RLMRealm` + was already up to date. + + @param block The block to perform. + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return Whether the transaction succeeded. + */ +- (BOOL)transactionWithBlock:(RLM_NOESCAPE void(^)(void))block error:(NSError **)error; + +/** + Update an `RLMRealm` and outstanding objects to point to the most recent data for this `RLMRealm`. + + @return Whether the realm had any updates. Note that this may return YES even if no data has actually changed. + */ +- (BOOL)refresh; + +/** + Set to YES to automatically update this Realm when changes happen in other threads. + + If set to YES (the default), changes made on other threads will be reflected + in this Realm on the next cycle of the run loop after the changes are + committed. If set to NO, you must manually call `-refresh` on the Realm to + update it to get the latest version. + + Note that by default, background threads do not have an active run loop and you + will need to manually call `-refresh` in order to update to the latest version, + even if `autorefresh` is set to `true`. + + Even with this enabled, you can still call `-refresh` at any time to update the + Realm before the automatic refresh would occur. + + Notifications are sent when a write transaction is committed whether or not + this is enabled. + + Disabling this on an `RLMRealm` without any strong references to it will not + have any effect, and it will switch back to YES the next time the `RLMRealm` + object is created. This is normally irrelevant as it means that there is + nothing to refresh (as persisted `RLMObject`s, `RLMArray`s, and `RLMResults` have strong + references to the containing `RLMRealm`), but it means that setting + `RLMRealm.defaultRealm.autorefresh = NO` in + `application:didFinishLaunchingWithOptions:` and only later storing Realm + objects will not work. + + Defaults to YES. + */ +@property (nonatomic) BOOL autorefresh; + +/** + Write a compacted copy of the RLMRealm to the given path. + + The destination file cannot already exist. + + Note that if this is called from within a write transaction it writes the + *current* data, and not data when the last write transaction was committed. + + @param path Path to save the Realm to. + @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. + @return YES if the realm was copied successfully. Returns NO if an error occurred. +*/ +- (BOOL)writeCopyToPath:(NSString *)path error:(NSError **)error; + +/** + Write an encrypted and compacted copy of the RLMRealm to the given path. + + The destination file cannot already exist. + + Note that if this is called from within a write transaction it writes the + *current* data, and not data when the last write transaction was committed. + + @param path Path to save the Realm to. + @param key 64-byte encryption key to encrypt the new file with + @param error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. + @return YES if the realm was copied successfully. Returns NO if an error occurred. +*/ +- (BOOL)writeCopyToPath:(NSString *)path encryptionKey:(NSData *)key error:(NSError **)error; + +/** + Invalidate all RLMObjects and RLMResults read from this Realm. + + An RLMRealm holds a read lock on the version of the data accessed by it, so + that changes made to the Realm on different threads do not modify or delete the + data seen by this RLMRealm. Calling this method releases the read lock, + allowing the space used on disk to be reused by later write transactions rather + than growing the file. This method should be called before performing long + blocking operations on a background thread on which you previously read data + from the Realm which you no longer need. + + All `RLMObject`, `RLMResults` and `RLMArray` instances obtained from this + `RLMRealm` on the current thread are invalidated, and can not longer be used. + The `RLMRealm` itself remains valid, and a new read transaction is implicitly + begun the next time data is read from the Realm. + + Calling this method multiple times in a row without reading any data from the + Realm, or before ever reading any data from the Realm is a no-op. This method + cannot be called on a read-only Realm. + */ +- (void)invalidate; + +#pragma mark - Accessing Objects + + +#pragma mark - Adding and Removing Objects from a Realm + +/** + Adds an object to be persisted in this Realm. + + Once added, this object can be retrieved using the `objectsWhere:` selectors + on `RLMRealm` and on subclasses of `RLMObject`. When added, all (child) + relationships referenced by this object will also be added to the Realm if they are + not already in it. If the object or any related objects already belong to a + different Realm an exception will be thrown. Use + `-[RLMObject createInRealm:withObject]` to insert a copy of a persisted object + into a different Realm. + + The object to be added must be valid and cannot have been previously deleted + from a Realm (i.e. `isInvalidated`) must be false. + + @warning This method can only be called during a write transaction. + + @param object Object to be added to this Realm. + */ +- (void)addObject:(RLMObject *)object; + +/** + Adds objects in the given array to be persisted in this Realm. + + This is the equivalent of `addObject:` except for an array of objects. + + @warning This method can only be called during a write transaction. + + @param array An enumerable object such as NSArray or RLMResults which contains objects to be added to + this Realm. + + @see addObject: + */ +- (void)addObjects:(id)array; + +/** + Adds or updates an object to be persisted in this Realm. The object provided must have a designated + primary key. If no objects exist in the RLMRealm instance with the same primary key value, the object is + inserted. Otherwise, the existing object is updated with any changed values. + + As with `addObject:`, the object cannot already be persisted in a different + Realm. Use `-[RLMObject createOrUpdateInRealm:withValue:]` to copy values to + a different Realm. + + @warning This method can only be called during a write transaction. + + @param object Object to be added or updated. + */ +- (void)addOrUpdateObject:(RLMObject *)object; + +/** + Adds or updates objects in the given array to be persisted in this Realm. + + This is the equivalent of `addOrUpdateObject:` except for an array of objects. + + @warning This method can only be called during a write transaction. + + @param array `NSArray`, `RLMArray`, or `RLMResults` of `RLMObject`s (or subclasses) to be added to this Realm. + + @see addOrUpdateObject: + */ +- (void)addOrUpdateObjectsFromArray:(id)array; + +/** + Delete an object from this Realm. + + @warning This method can only be called during a write transaction. + + @param object Object to be deleted from this Realm. + */ +- (void)deleteObject:(RLMObject *)object; + +/** + Delete an `NSArray`, `RLMArray`, or `RLMResults` of objects from this Realm. + + @warning This method can only be called during a write transaction. + + @param array `RLMArray`, `NSArray`, or `RLMResults` of `RLMObject`s to be deleted. + */ +- (void)deleteObjects:(id)array; + +/** + Deletes all objects in this Realm. + + @warning This method can only be called during a write transaction. + */ +- (void)deleteAllObjects; + + +#pragma mark - Migrations + +/** + Migration block used to migrate a Realm. + + @param migration `RLMMigration` object used to perform the migration. The + migration object allows you to enumerate and alter any + existing objects which require migration. + + @param oldSchemaVersion The schema version of the `RLMRealm` being migrated. + */ +typedef void (^RLMMigrationBlock)(RLMMigration *migration, uint64_t oldSchemaVersion); + +/** + Get the schema version for a Realm at a given path. + + @param realmPath Path to a Realm file + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return The version of the Realm at `realmPath` or RLMNotVersioned if the version cannot be read. + */ ++ (uint64_t)schemaVersionAtPath:(NSString *)realmPath error:(NSError **)error; + +/** + Get the schema version for an encrypted Realm at a given path. + + @param realmPath Path to a Realm file + @param key 64-byte encryption key. + @param error If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in `NULL`. + + @return The version of the Realm at `realmPath` or RLMNotVersioned if the version cannot be read. + */ ++ (uint64_t)schemaVersionAtPath:(NSString *)realmPath encryptionKey:(nullable NSData *)key error:(NSError **)error; + +/** + Performs the given Realm configuration's migration block on a Realm at the given path. + + This method is called automatically when opening a Realm for the first time and does + not need to be called explicitly. You can choose to call this method to control + exactly when and how migrations are performed. + + @param configuration The Realm configuration used to open and migrate the Realm. + @return The error that occurred while applying the migration, if any. + + @see RLMMigration + */ ++ (NSError *)migrateRealm:(RLMRealmConfiguration *)configuration; + +@end + +/** + A token which is returned from methods which subscribe to changes to a Realm. + + Change subscriptions in Realm return an RLMNotificationToken which can be used + to unsubscribe from the changes. You must store a strong reference to the token + for as long as you want to continue to receive notifications. When you wish to + stop, call the `-stop` method. + */ +@interface RLMNotificationToken : NSObject +/// Stop receiving notifications for the subcription that returned this token. +- (void)stop; +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMRealmConfiguration.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMRealmConfiguration.h new file mode 100644 index 000000000..094016fd1 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMRealmConfiguration.h @@ -0,0 +1,79 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +/** + An `RLMRealmConfiguration` is used to describe the different options used to + create an `RLMRealm` instance. + + `RLMRealmConfiguration` instances are just plain NSObjects, and unlike RLMRealm + and RLMObjects can be freely shared between threads as long as you do not + mutate them. Creating configuration objects for class subsets (by setting the + `objectClasses` property) can be expensive, and so you will normally want to + cache and reuse a single configuration object for each distinct configuration + that you are using rather than creating a new one each time you open a Realm. + */ +@interface RLMRealmConfiguration : NSObject + +#pragma mark - Default Configuration + +/** + Returns the default configuration used to create Realms when no other + configuration is explicitly specified (i.e. `+[RLMRealm defaultRealm]`). + + @return The default Realm configuration. + */ ++ (instancetype)defaultConfiguration; + +/** + Sets the default configuration to the given `RLMRealmConfiguration`. + + @param configuration The new default Realm configuration. + */ ++ (void)setDefaultConfiguration:(RLMRealmConfiguration *)configuration; + +#pragma mark - Properties + +/// The path to the realm file. Mutually exclusive with `inMemoryIdentifier`. +@property (nonatomic, copy, nullable) NSString *path; + +/// A string used to identify a particular in-memory Realm. Mutually exclusive with `path`. +@property (nonatomic, copy, nullable) NSString *inMemoryIdentifier; + +/// 64-byte key to use to encrypt the data. +@property (nonatomic, copy, nullable) NSData *encryptionKey; + +/// Whether the Realm is read-only (must be YES for read-only files). +@property (nonatomic) BOOL readOnly; + +/// The current schema version. +@property (nonatomic) uint64_t schemaVersion; + +/// The block which migrates the Realm to the current version. +@property (nonatomic, copy, nullable) RLMMigrationBlock migrationBlock; + +/// The classes persisted in the Realm. +@property (nonatomic, copy, nullable) NSArray *objectClasses; + +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMRealm_Dynamic.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMRealm_Dynamic.h new file mode 100644 index 000000000..d778678c7 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMRealm_Dynamic.h @@ -0,0 +1,130 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import +#import + +@class RLMResults; + +@interface RLMRealm (Dynamic) + +#pragma mark - Getting Objects from a Realm + +/** + This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to use the class methods on `RLMObject`. + + Get all objects of a given type in this Realm. + + The preferred way to get objects of a single class is to use the class methods on RLMObject. + + @warning This method is useful only in specialized circumstances. + + @param className The name of the RLMObject subclass to retrieve on e.g. `MyClass.className`. + + @return An RLMResults of all objects in this realm of the given type. + + @see RLMObject allObjects + */ +- (RLMResults *)allObjects:(NSString *)className; + +/** + This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to use the class methods on `RLMObject`. + + Get objects matching the given predicate from the this Realm. + + The preferred way to get objects of a single class is to use the class methods on RLMObject. + + @warning This method is useful only in specialized circumstances. + + @param className The type of objects you are looking for (name of the class). + @param predicateFormat The predicate format string which can accept variable arguments. + + @return An RLMResults of results matching the given predicate. + + @see RLMObject objectsWhere: + */ +- (RLMResults *)objects:(NSString *)className where:(NSString *)predicateFormat, ...; + +/** + This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to use the class methods on `RLMObject`. + + Get objects matching the given predicate from the this Realm. + + The preferred way to get objects of a single class is to use the class methods on RLMObject. + + @warning This method is useful only in specialized circumstances. + + @param className The type of objects you are looking for (name of the class). + @param predicate The predicate to filter the objects. + + @return An RLMResults of results matching the given predicate. + + @see RLMObject objectsWhere: + */ +- (RLMResults *)objects:(NSString *)className withPredicate:(NSPredicate *)predicate; + +/** + This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to use the class methods on `RLMObject`. + + Get an object of a given class name with a primary key + + The preferred way to get an object of a single class is to use the class methods on RLMObject. + + @warning This method is useful only in specialized circumstances. + + @param className The class name for the object you are looking for + @param primaryKey The primary key value for the object you are looking for + + @return An object or nil if an object with the given primary key does not exist. + + @see RLMObject objectForPrimaryKey: + */ +- (RLMObject *)objectWithClassName:(NSString *)className forPrimaryKey:(id)primaryKey; + +/** + This method is useful only in specialized circumstances, for example, when building components + that integrate with Realm. If you are simply building an app on Realm, it is + recommended to use [RLMObject createInDefaultRealmWithValue:]. + + Create an RLMObject of type `className` in the Realm with a given object. + + @warning This method is useful only in specialized circumstances. + + @param value The value used to populate the object. This can be any key/value coding compliant + object, or a JSON object such as those returned from the methods in NSJSONSerialization, or + an NSArray with one object for each persisted property. An exception will be + thrown if any required properties are not present and no default is set. + + When passing in an NSArray, all properties must be present, valid and in the same order as + the properties defined in the model. + + @return An RLMObject of type `className` + */ +-(RLMObject *)createObject:(NSString *)className withValue:(id)value; + +@end diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMResults.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMResults.h new file mode 100644 index 000000000..6f355fe93 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMResults.h @@ -0,0 +1,280 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMObject, RLMRealm, RLMNotificationToken; + +/** + RLMResults is an auto-updating container type in Realm returned from object + queries. + + RLMResults can be queried with the same predicates as RLMObject and RLMArray + and you can chain queries to further filter query results. + + RLMResults always reflect the current state of the Realm on the current thread, + including during write transactions on the current thread. The one exception to + this is when using `for...in` fast enumeration, which will always enumerate + over the objects which matched the query when the enumeration is begun, even if + some of them are deleted or modified to be excluded by the filter during the + enumeration. + + RLMResults are initially lazily evaluated, and only run queries when the result + of the query is requested. This means that chaining several temporary + RLMResults to sort and filter your data does not perform any extra work + processing the intermediate state. + + Once the results have been evaluated or a notification block has been added, + the results are eagerly kept up-to-date, with the work done to keep them + up-to-date done on a background thread whenever possible. + + RLMResults cannot be created directly. + */ +@interface RLMResults RLM_GENERIC_COLLECTION : NSObject + +#pragma mark - Properties + +/** + Number of objects in the results. + */ +@property (nonatomic, readonly, assign) NSUInteger count; + +/** + The class name (i.e. type) of the RLMObjects contained in this RLMResults. + */ +@property (nonatomic, readonly, copy) NSString *objectClassName; + +/** + The Realm this `RLMResults` is associated with. + */ +@property (nonatomic, readonly) RLMRealm *realm; + +#pragma mark - Accessing Objects from an RLMResults + +/** + Returns the object at the index specified. + + @param index The index to look up. + + @return An RLMObject of the type contained in this RLMResults. + */ +- (RLMObjectType)objectAtIndex:(NSUInteger)index; + +/** + Returns the first object in the results. + + Returns `nil` if called on an empty RLMResults. + + @return An RLMObject of the type contained in this RLMResults. + */ +- (nullable RLMObjectType)firstObject; + +/** + Returns the last object in the results. + + Returns `nil` if called on an empty RLMResults. + + @return An RLMObject of the type contained in this RLMResults. + */ +- (nullable RLMObjectType)lastObject; + +#pragma mark - Querying Results + +/** + Gets the index of an object. + + Returns NSNotFound if the object is not found in this RLMResults. + + @param object An object (of the same type as returned from the objectClassName selector). + */ +- (NSUInteger)indexOfObject:(RLMObjectArgument)object; + +/** + Gets the index of the first object matching the predicate. + + @param predicateFormat The predicate format string which can accept variable arguments. + + @return Index of object or NSNotFound if the object is not found in this RLMResults. + */ +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Gets the index of the first object matching the predicate. + + @param predicate The predicate to filter the objects. + + @return Index of object or NSNotFound if the object is not found in this RLMResults. + */ +- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate; + +/** + Get objects matching the given predicate in the RLMResults. + + @param predicateFormat The predicate format string which can accept variable arguments. + + @return An RLMResults of objects that match the given predicate + */ +- (RLMResults RLM_GENERIC_RETURN*)objectsWhere:(NSString *)predicateFormat, ...; + +/// :nodoc: +- (RLMResults RLM_GENERIC_RETURN*)objectsWhere:(NSString *)predicateFormat args:(va_list)args; + +/** + Get objects matching the given predicate in the RLMResults. + + @param predicate The predicate to filter the objects. + + @return An RLMResults of objects that match the given predicate + */ +- (RLMResults RLM_GENERIC_RETURN*)objectsWithPredicate:(NSPredicate *)predicate; + +/** + Get a sorted `RLMResults` from an existing `RLMResults` sorted by a property. + + @param property The property name to sort by. + @param ascending The direction to sort by. + + @return An RLMResults sorted by the specified property. + */ +- (RLMResults RLM_GENERIC_RETURN*)sortedResultsUsingProperty:(NSString *)property ascending:(BOOL)ascending; + +/** + Get a sorted `RLMResults` from an existing `RLMResults` sorted by an `NSArray`` of `RLMSortDescriptor`s. + + @param properties An array of `RLMSortDescriptor`s to sort by. + + @return An RLMResults sorted by the specified properties. + */ +- (RLMResults RLM_GENERIC_RETURN*)sortedResultsUsingDescriptors:(NSArray *)properties; + +#pragma mark - Notifications + +/** + Register a block to be called each time the RLMResults changes. + + The block will be asynchronously called with the initial results, and then + called again after each write transaction which causes the results to change. + You must retain the returned token for as long as you want the results to + continue to be sent to the block. To stop receiving updates, call -stop on the + token. + + The determination for whether or not a write transaction has changed the + results is currently very coarse, and the block may be called even if no + changes occurred. The opposite (not being called despite changes) will not + happen. This will become more precise in future versions. + + If an error occurs the block will be called with `nil` for the results + parameter and a non-`nil` error. Currently the only errors that can occur are + when opening the RLMRealm on the background worker thread or the destination + queue fails. + + At the time when the block is called, the RLMResults object will be fully + evaluated and up-to-date, and as long as you do not perform a write transaction + on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will + never perform blocking work. + + @warning This method cannot be called during a write transaction, or when the + containing realm is read-only. + + @param block The block to be called with the evaluated results. + @return A token which must be held for as long as you want query results to be delivered. + */ +- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults RLM_GENERIC_RETURN *__nullable results, NSError *__nullable error))block RLM_WARN_UNUSED_RESULT; + +#pragma mark - Aggregating Property Values + +/** + Returns the minimum (lowest) value of the given property + + NSNumber *min = [results minOfProperty:@"age"]; + + @warning You cannot use this method on RLMObject, RLMArray, and NSData properties. + + @param property The property to look for a minimum on. Only properties of type int, float, double and NSDate are supported. + + @return The minimum value for the property amongst objects in an RLMResults. + */ +- (nullable id)minOfProperty:(NSString *)property; + +/** + Returns the maximum (highest) value of the given property of objects in an RLMResults + + NSNumber *max = [results maxOfProperty:@"age"]; + + @warning You cannot use this method on RLMObject, RLMArray, and NSData properties. + + @param property The property to look for a maximum on. Only properties of type int, float, double and NSDate are supported. + + @return The maximum value for the property amongst objects in an RLMResults + */ +- (nullable id)maxOfProperty:(NSString *)property; + +/** + Returns the sum of the given property for objects in an RLMResults. + + NSNumber *sum = [results sumOfProperty:@"age"]; + + @warning You cannot use this method on RLMObject, RLMArray, and NSData properties. + + @param property The property to calculate sum on. Only properties of type int, float and double are supported. + + @return The sum of the given property over all objects in an RLMResults. + */ +- (NSNumber *)sumOfProperty:(NSString *)property; + +/** + Returns the average of a given property for objects in an RLMResults. + + NSNumber *average = [results averageOfProperty:@"age"]; + + @warning You cannot use this method on RLMObject, RLMArray, and NSData properties. + + @param property The property to calculate average on. Only properties of type int, float and double are supported. + + @return The average for the given property amongst objects in an RLMResults. This will be of type double for both + float and double properties. + */ +- (nullable NSNumber *)averageOfProperty:(NSString *)property; + +/// :nodoc: +- (id)objectAtIndexedSubscript:(NSUInteger)index; + +#pragma mark - Unavailable Methods + +/** + -[RLMResults init] is not available because RLMResults cannot be created directly. + RLMResults can be obtained by querying a Realm. + */ +- (instancetype)init __attribute__((unavailable("RLMResults cannot be created directly"))); + +/** + +[RLMResults new] is not available because RLMResults cannot be created directly. + RLMResults can be obtained by querying a Realm. + */ ++ (instancetype)new __attribute__((unavailable("RLMResults cannot be created directly"))); + +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMSchema.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMSchema.h new file mode 100644 index 000000000..65497069d --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/RLMSchema.h @@ -0,0 +1,76 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMObjectSchema; + +/** + This class represents the collection of model object schemas persisted to Realm. + + When using Realm, RLMSchema objects allow performing migrations and + introspecting the database's schema. + + Schemas map to collections of tables in the core database. + */ +@interface RLMSchema : NSObject + +#pragma mark - Properties + +/** + An NSArray containing RLMObjectSchemas for all object types in this Realm. Meant + to be used during migrations for dynamic introspection. + + @see RLMObjectSchema + */ +@property (nonatomic, readonly, copy) NSArray RLM_GENERIC(RLMObjectSchema *) *objectSchema; + +#pragma mark - Methods + +/** + Returns an RLMObjectSchema for the given class name in this RLMSchema. + + @param className The object class name. + @return RLMObjectSchema for the given class in this RLMSchema. + + @see RLMObjectSchema + */ +- (nullable RLMObjectSchema *)schemaForClassName:(NSString *)className; + +/** + Look up an RLMObjectSchema for the given class name in this Realm. Throws + an exception if there is no object of type className in this RLMSchema instance. + + @param className The object class name. + @return RLMObjectSchema for the given class in this Realm. + + @see RLMObjectSchema + */ +- (RLMObjectSchema *)objectForKeyedSubscript:(id )className; + +/** + Returns YES if equal to schema + */ +- (BOOL)isEqualToSchema:(RLMSchema *)schema; + +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/Realm.h b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/Realm.h new file mode 100644 index 000000000..886f19e83 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Headers/Realm.h @@ -0,0 +1,30 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Modules/module.modulemap b/Tests/Performance/Realm/Realm.framework/Versions/A/Modules/module.modulemap new file mode 100644 index 000000000..18b5e2ecb --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Modules/module.modulemap @@ -0,0 +1,27 @@ +framework module Realm { + umbrella header "Realm.h" + + export * + module * { export * } + + explicit module Private { + header "RLMAccessor.h" + header "RLMArray_Private.h" + header "RLMListBase.h" + header "RLMMigration_Private.h" + header "RLMObjectSchema_Private.h" + header "RLMObjectStore.h" + header "RLMObject_Private.h" + header "RLMOptionalBase.h" + header "RLMProperty_Private.h" + header "RLMRealmConfiguration_Private.h" + header "RLMRealm_Private.h" + header "RLMResults_Private.h" + header "RLMSchema_Private.h" + } + + explicit module Dynamic { + header "RLMRealm_Dynamic.h" + header "RLMObjectBase_Dynamic.h" + } +} diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMAccessor.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMAccessor.h new file mode 100644 index 000000000..23a4317d2 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMAccessor.h @@ -0,0 +1,64 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import + +@class RLMObjectSchema, RLMProperty, RLMObjectBase, RLMProperty; + +#ifdef __cplusplus +typedef NSUInteger RLMCreationOptions; +#else +typedef NS_OPTIONS(NSUInteger, RLMCreationOptions); +#endif + +RLM_ASSUME_NONNULL_BEGIN + +// +// Accessors Class Creation/Caching +// + +// get accessor classes for an object class - generates classes if not cached +Class RLMAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema, NSString *prefix); +Class RLMStandaloneAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema); + +// Check if a given class is a generated accessor class +bool RLMIsGeneratedClass(Class cls); + +// +// Dynamic getters/setters +// +FOUNDATION_EXTERN void RLMDynamicValidatedSet(RLMObjectBase *obj, NSString *propName, id __nullable val); +FOUNDATION_EXTERN RLMProperty *RLMValidatedGetProperty(RLMObjectBase *obj, NSString *propName); +FOUNDATION_EXTERN id __nullable RLMDynamicGet(RLMObjectBase *obj, RLMProperty *prop); + +// by property/column +FOUNDATION_EXTERN void RLMDynamicSet(RLMObjectBase *obj, RLMProperty *prop, id val, RLMCreationOptions options); + +// +// Class modification +// + +// Replace className method for the given class +void RLMReplaceClassNameMethod(Class accessorClass, NSString *className); + +// Replace sharedSchema method for the given class +void RLMReplaceSharedSchemaMethod(Class accessorClass, RLMObjectSchema * __nullable schema); + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMArray_Private.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMArray_Private.h new file mode 100644 index 000000000..592dd57f8 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMArray_Private.h @@ -0,0 +1,24 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@interface RLMArray () +- (instancetype)initWithObjectClassName:(NSString *)objectClassName; +- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth; +@end diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMListBase.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMListBase.h new file mode 100644 index 000000000..a8057a682 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMListBase.h @@ -0,0 +1,29 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMArray; + +// A base class for Swift generic Lists to make it possible to interact with +// them from obj-c +@interface RLMListBase : NSObject +@property (nonatomic, strong) RLMArray *_rlmArray; + +- (instancetype)initWithArray:(RLMArray *)array; +@end diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMMigration_Private.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMMigration_Private.h new file mode 100644 index 000000000..4b54c891a --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMMigration_Private.h @@ -0,0 +1,34 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import +#import + +typedef void (^RLMObjectBaseMigrationBlock)(RLMObjectBase *oldObject, RLMObjectBase *newObject); + +@interface RLMMigration () + +@property (nonatomic, strong) RLMRealm *oldRealm; +@property (nonatomic, strong) RLMRealm *realm; + +- (instancetype)initWithRealm:(RLMRealm *)realm oldRealm:(RLMRealm *)oldRealm; + +- (void)execute:(RLMMigrationBlock)block; + +@end diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMObjectSchema_Private.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMObjectSchema_Private.h new file mode 100644 index 000000000..10b6473ff --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMObjectSchema_Private.h @@ -0,0 +1,70 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMRealm; + +// RLMObjectSchema private +@interface RLMObjectSchema () + +// writable redecleration +@property (nonatomic, readwrite, copy) NSArray RLM_GENERIC(RLMProperty *) *properties; +@property (nonatomic, readwrite, assign) bool isSwiftClass; + +// class used for this object schema +@property (nonatomic, readwrite, assign) Class objectClass; +@property (nonatomic, readwrite, assign) Class accessorClass; +@property (nonatomic, readwrite, assign) Class standaloneClass; + +@property (nonatomic, readwrite, nullable) RLMProperty *primaryKeyProperty; + +@property (nonatomic, readonly) NSArray RLM_GENERIC(RLMProperty *) *propertiesInDeclaredOrder; + +// The Realm retains its object schemas, so they need to not retain the Realm +@property (nonatomic, unsafe_unretained, nullable) RLMRealm *realm; +// returns a cached or new schema for a given object class ++ (instancetype)schemaForObjectClass:(Class)objectClass; + +- (void)sortPropertiesByColumn; + +@end + +@interface RLMObjectSchema (Dynamic) +/** + This method is useful only in specialized circumstances, for example, when accessing objects + in a Realm produced externally. If you are simply building an app on Realm, it is not recommened + to use this method as an [RLMObjectSchema](RLMObjectSchema) is generated automatically for every [RLMObject](RLMObject) subclass. + + Initialize an RLMObjectSchema with classname, objectClass, and an array of properties + + @warning This method is useful only in specialized circumstances. + + @param objectClassName The name of the class used to refer to objects of this type. + @param objectClass The objective-c class used when creating instances of this type. + @param properties An array RLMProperty describing the persisted properties for this type. + + @return An initialized instance of RLMObjectSchema. + */ +- (instancetype)initWithClassName:(NSString *)objectClassName objectClass:(Class)objectClass properties:(NSArray *)properties; +@end + +RLM_ASSUME_NONNULL_END diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMObjectStore.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMObjectStore.h new file mode 100644 index 000000000..590d0ef1e --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMObjectStore.h @@ -0,0 +1,99 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#ifdef __cplusplus +extern "C" { +#endif + +@class RLMRealm, RLMSchema, RLMObjectSchema, RLMObjectBase, RLMResults, RLMProperty; + +// +// Accessor Creation +// + +// create or get cached accessors for the given schema +void RLMRealmCreateAccessors(RLMSchema *schema); + +// Clear the cache of created accessor classes +void RLMClearAccessorCache(); + + +// +// Options for object creation +// +typedef NS_OPTIONS(NSUInteger, RLMCreationOptions) { + // Normal object creation + RLMCreationOptionsNone = 0, + // If the property is a link or array property, upsert the linked objects + // if they have a primary key, and insert them otherwise. + RLMCreationOptionsCreateOrUpdate = 1 << 0, + // Allow standalone objects to be promoted to persisted objects + // if false objects are copied during object creation + RLMCreationOptionsPromoteStandalone = 1 << 1, +}; + + +// +// Adding, Removing, Getting Objects +// + +// add an object to the given realm +void RLMAddObjectToRealm(RLMObjectBase *object, RLMRealm *realm, bool createOrUpdate); + +// delete an object from its realm +void RLMDeleteObjectFromRealm(RLMObjectBase *object, RLMRealm *realm); + +// deletes all objects from a realm +void RLMDeleteAllObjectsFromRealm(RLMRealm *realm); + +// get objects of a given class +RLMResults *RLMGetObjects(RLMRealm *realm, NSString *objectClassName, NSPredicate *predicate) NS_RETURNS_RETAINED; + +// get an object with the given primary key +id RLMGetObject(RLMRealm *realm, NSString *objectClassName, id key) NS_RETURNS_RETAINED; + +// create object from array or dictionary +RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className, id value, bool createOrUpdate) NS_RETURNS_RETAINED; + + +// +// Accessor Creation +// + + +// switch List<> properties from being backed by standalone RLMArrays to RLMArrayLinkView +void RLMInitializeSwiftAccessorGenerics(RLMObjectBase *object); + +#ifdef __cplusplus +} + +namespace realm { + class Table; + template class BasicRowExpr; + using RowExpr = BasicRowExpr; +} +// Create accessors +RLMObjectBase *RLMCreateObjectAccessor(RLMRealm *realm, + RLMObjectSchema *objectSchema, + NSUInteger index) NS_RETURNS_RETAINED; +RLMObjectBase *RLMCreateObjectAccessor(RLMRealm *realm, + RLMObjectSchema *objectSchema, + realm::RowExpr row) NS_RETURNS_RETAINED; +#endif diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMObject_Private.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMObject_Private.h new file mode 100644 index 000000000..2c7e96f4d --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMObject_Private.h @@ -0,0 +1,89 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +// RLMObject accessor and read/write realm +@interface RLMObjectBase () { + @public + RLMRealm *_realm; + // objectSchema is a cached pointer to an object stored in the RLMSchema + // owned by _realm, so it's guaranteed to stay alive as long as this object + // without retaining it (and retaining it makes iteration slower) + __unsafe_unretained RLMObjectSchema *_objectSchema; +} + +// standalone initializer +- (instancetype)initWithValue:(id)value schema:(RLMSchema *)schema; + +// live accessor initializer +- (instancetype)initWithRealm:(__unsafe_unretained RLMRealm *const)realm + schema:(__unsafe_unretained RLMObjectSchema *const)schema; + +// shared schema for this class ++ (RLMObjectSchema *)sharedSchema; + +// provide injection point for alternative Swift object util class ++ (Class)objectUtilClass:(BOOL)isSwift; + +@end + +@interface RLMDynamicObject : RLMObject + +@end + +// +// Getters and setters for RLMObjectBase ivars for realm and objectSchema +// +FOUNDATION_EXTERN void RLMObjectBaseSetRealm(RLMObjectBase *object, RLMRealm *realm); +FOUNDATION_EXTERN RLMRealm *RLMObjectBaseRealm(RLMObjectBase *object); +FOUNDATION_EXTERN void RLMObjectBaseSetObjectSchema(RLMObjectBase *object, RLMObjectSchema *objectSchema); +FOUNDATION_EXTERN RLMObjectSchema *RLMObjectBaseObjectSchema(RLMObjectBase *object); + +// Get linking objects for an RLMObjectBase +FOUNDATION_EXTERN NSArray *RLMObjectBaseLinkingObjectsOfClass(RLMObjectBase *object, NSString *className, NSString *property); + +// Dynamic access to RLMObjectBase properties +FOUNDATION_EXTERN id RLMObjectBaseObjectForKeyedSubscript(RLMObjectBase *object, NSString *key); +FOUNDATION_EXTERN void RLMObjectBaseSetObjectForKeyedSubscript(RLMObjectBase *object, NSString *key, id obj); + +// Calls valueForKey: and re-raises NSUndefinedKeyExceptions +FOUNDATION_EXTERN id RLMValidatedValueForProperty(id object, NSString *key, NSString *className); + +// Compare two RLObjectBases +FOUNDATION_EXTERN BOOL RLMObjectBaseAreEqual(RLMObjectBase *o1, RLMObjectBase *o2); + +// Get ObjectUil class for objc or swift +FOUNDATION_EXTERN Class RLMObjectUtilClass(BOOL isSwift); + +FOUNDATION_EXTERN const NSUInteger RLMDescriptionMaxDepth; + +@class RLMProperty, RLMArray; +@interface RLMObjectUtil : NSObject + ++ (NSArray RLM_GENERIC(NSString *) *)ignoredPropertiesForClass:(Class)cls; ++ (NSArray RLM_GENERIC(NSString *) *)indexedPropertiesForClass:(Class)cls; + ++ (NSArray RLM_GENERIC(NSString *) *)getGenericListPropertyNames:(id)obj; ++ (void)initializeListProperty:(RLMObjectBase *)object property:(RLMProperty *)property array:(RLMArray *)array; ++ (void)initializeOptionalProperty:(RLMObjectBase *)object property:(RLMProperty *)property; + ++ (NSDictionary RLM_GENERIC(NSString *, NSNumber *) *)getOptionalProperties:(id)obj; ++ (NSArray RLM_GENERIC(NSString *) *)requiredPropertiesForClass:(Class)cls; + +@end diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMOptionalBase.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMOptionalBase.h new file mode 100644 index 000000000..bab04a57c --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMOptionalBase.h @@ -0,0 +1,34 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import + +@class RLMObjectBase, RLMProperty; + +@interface RLMOptionalBase : NSProxy + +- (instancetype)init; + +@property (nonatomic, weak) RLMObjectBase *object; + +@property (nonatomic, unsafe_unretained) RLMProperty *property; + +@property (nonatomic, strong) id underlyingValue; + +@end diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMProperty_Private.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMProperty_Private.h new file mode 100644 index 000000000..52237645e --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMProperty_Private.h @@ -0,0 +1,93 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +#import + +@class RLMObjectBase; + +FOUNDATION_EXTERN BOOL RLMPropertyTypeIsNullable(RLMPropertyType propertyType); +FOUNDATION_EXTERN BOOL RLMPropertyTypeIsNumeric(RLMPropertyType propertyType); + +// private property interface +@interface RLMProperty () + +- (instancetype)initWithName:(NSString *)name + indexed:(BOOL)indexed + property:(objc_property_t)property; + +- (instancetype)initSwiftPropertyWithName:(NSString *)name + indexed:(BOOL)indexed + property:(objc_property_t)property + instance:(RLMObjectBase *)objectInstance; + +- (instancetype)initSwiftListPropertyWithName:(NSString *)name + ivar:(Ivar)ivar + objectClassName:(NSString *)objectClassName; + +- (instancetype)initSwiftOptionalPropertyWithName:(NSString *)name + indexed:(BOOL)indexed + ivar:(Ivar)ivar + propertyType:(RLMPropertyType)propertyType; + +// private setters +@property (nonatomic, assign) NSUInteger column; +@property (nonatomic, readwrite, assign) RLMPropertyType type; +@property (nonatomic, readwrite) BOOL indexed; +@property (nonatomic, readwrite) BOOL optional; +@property (nonatomic, copy) NSString *objectClassName; + +// private properties +@property (nonatomic, assign) char objcType; +@property (nonatomic, copy) NSString *objcRawType; +@property (nonatomic, assign) BOOL isPrimary; +@property (nonatomic, assign) Ivar swiftIvar; +@property (nonatomic, assign) NSUInteger declarationIndex; + +// getter and setter names +@property (nonatomic, copy) NSString *getterName; +@property (nonatomic, copy) NSString *setterName; +@property (nonatomic) SEL getterSel; +@property (nonatomic) SEL setterSel; + +@end + +@interface RLMProperty (Dynamic) +/** + This method is useful only in specialized circumstances, for example, in conjunction with + +[RLMObjectSchema initWithClassName:objectClass:properties:]. If you are simply building an + app on Realm, it is not recommened to use this method. + + Initialize an RLMProperty + + @warning This method is useful only in specialized circumstances. + + @param name The property name. + @param type The property type. + @param objectClassName The object type used for Object and Array types. + + @return An initialized instance of RLMProperty. + */ +- (instancetype)initWithName:(NSString *)name + type:(RLMPropertyType)type + objectClassName:(NSString *)objectClassName + indexed:(BOOL)indexed + optional:(BOOL)optional; +@end + diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMRealmConfiguration_Private.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMRealmConfiguration_Private.h new file mode 100644 index 000000000..91770a290 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMRealmConfiguration_Private.h @@ -0,0 +1,38 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2015 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMSchema; + +@interface RLMRealmConfiguration () + +@property (nonatomic, readwrite) bool cache; +@property (nonatomic, readwrite) bool dynamic; +@property (nonatomic, readwrite) bool disableFormatUpgrade; +@property (nonatomic, copy) RLMSchema *customSchema; + +// Get the default confiugration without copying it ++ (RLMRealmConfiguration *)rawDefaultConfiguration; + ++ (void)resetRealmConfigurationState; +@end + +// Get a path in the platform-appropriate documents directory with the given filename +FOUNDATION_EXTERN NSString *RLMRealmPathForFile(NSString *fileName); +FOUNDATION_EXTERN NSString *RLMRealmPathForFileAndBundleIdentifier(NSString *fileName, NSString *mainBundleIdentifier); diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMRealmUtil.hpp b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMRealmUtil.hpp new file mode 100644 index 000000000..b69c727d0 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMRealmUtil.hpp @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import +#import +#import + +@class RLMRealm; + +namespace realm { + class BindingContext; +} + +// Add a Realm to the weak cache +void RLMCacheRealm(std::string const& path, RLMRealm *realm); +// Get a Realm for the given path which can be used on the current thread +RLMRealm *RLMGetThreadLocalCachedRealmForPath(std::string const& path); +// Get a Realm for the given path +RLMRealm *RLMGetAnyCachedRealmForPath(std::string const& path); +// Clear the weak cache of Realms +void RLMClearRealmCache(); + +// Install an uncaught exception handler that cancels write transactions +// for all cached realms on the current thread +void RLMInstallUncaughtExceptionHandler(); + +std::unique_ptr RLMCreateBindingContext(RLMRealm *realm); diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMRealm_Private.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMRealm_Private.h new file mode 100644 index 000000000..68b3b82b2 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMRealm_Private.h @@ -0,0 +1,86 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMFastEnumerator; + +// Disable syncing files to disk. Cannot be re-enabled. Use only for tests. +FOUNDATION_EXTERN void RLMDisableSyncToDisk(); + +FOUNDATION_EXTERN NSData *RLMRealmValidatedEncryptionKey(NSData *key); + +// Translate an in-flight exception resulting from opening a SharedGroup to +// an NSError or NSException (if error is nil) +void RLMRealmTranslateException(NSError **error); + +// RLMRealm private members +@interface RLMRealm () + +@property (nonatomic, readonly) BOOL dynamic; +@property (nonatomic, readwrite) RLMSchema *schema; + ++ (void)resetRealmState; + +/** + This method is useful only in specialized circumstances, for example, when opening Realm files + retrieved externally that contain a different schema than defined in your application. + If you are simply building an app on Realm you should consider using: + [defaultRealm]([RLMRealm defaultRealm]) or [realmWithPath:]([RLMRealm realmWithPath:]) + + Obtains an `RLMRealm` instance with persistence to a specific file path with + options. + + @warning This method is useful only in specialized circumstances. + + @param path Path to the file you want the data saved in. + @param key 64-byte key to use to encrypt the data. + @param readonly `BOOL` indicating if this Realm is read-only (must use for read-only files) + @param inMemory `BOOL` indicating if this Realm is in-memory + @param dynamic `BOOL` indicating if this Realm is dynamic + @param customSchema `RLMSchema` object representing the schema for the Realm + @param outError If an error occurs, upon return contains an `NSError` object + that describes the problem. If you are not interested in + possible errors, pass in NULL. + + @return An `RLMRealm` instance. + + @see RLMRealm defaultRealm + @see RLMRealm realmWithPath: + @see RLMRealm realmWithPath:readOnly:error: + @see RLMRealm realmWithPath:encryptionKey:readOnly:error: + */ ++ (instancetype)realmWithPath:(NSString *)path + key:(NSData *)key + readOnly:(BOOL)readonly + inMemory:(BOOL)inMemory + dynamic:(BOOL)dynamic + schema:(RLMSchema *)customSchema + error:(NSError **)outError; + +- (void)registerEnumerator:(RLMFastEnumerator *)enumerator; +- (void)unregisterEnumerator:(RLMFastEnumerator *)enumerator; +- (void)detachAllEnumerators; + +- (void)sendNotifications:(NSString *)notification; +- (void)verifyThread; +- (void)verifyNotificationsAreSupported; + ++ (NSString *)writeableTemporaryPathForFile:(NSString *)fileName; + +@end diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMResults_Private.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMResults_Private.h new file mode 100644 index 000000000..7bdfa8412 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMResults_Private.h @@ -0,0 +1,25 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#import + +@class RLMObjectSchema; + +@interface RLMResults () +@property (nonatomic, unsafe_unretained) RLMObjectSchema *objectSchema; +@end diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMSchema_Private.h b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMSchema_Private.h new file mode 100644 index 000000000..e95155386 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/PrivateHeaders/RLMSchema_Private.h @@ -0,0 +1,66 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2014 Realm Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +#import +#import + +RLM_ASSUME_NONNULL_BEGIN + +@class RLMRealm; + +// +// RLMSchema private interface +// +@interface RLMSchema () + +/** + Returns an `RLMSchema` containing only the given `RLMObject` subclasses. + + @param classes The classes to be included in the schema. + + @return An `RLMSchema` containing only the given classes. + */ ++ (instancetype)schemaWithObjectClasses:(NSArray RLM_GENERIC(Class) *)classes; + +@property (nonatomic, readwrite, copy) NSArray RLM_GENERIC(RLMObjectSchema *) *objectSchema; + +// schema based on runtime objects ++ (instancetype)sharedSchema; + +// schema based upon all currently registered object classes ++ (instancetype)partialSharedSchema; + +// class for string ++ (nullable Class)classForString:(NSString *)className; + +// shallow copy for reusing schema properties accross the same Realm on multiple threads +- (instancetype)shallowCopy; + ++ (RLMObjectSchema *)sharedSchemaForClass:(Class)cls; + +@end + +RLM_ASSUME_NONNULL_END + +#ifdef __cplusplus +} +#endif diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Realm b/Tests/Performance/Realm/Realm.framework/Versions/A/Realm new file mode 100755 index 000000000..93b632304 Binary files /dev/null and b/Tests/Performance/Realm/Realm.framework/Versions/A/Realm differ diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/CHANGELOG.md b/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/CHANGELOG.md new file mode 100644 index 000000000..b5407cdba --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/CHANGELOG.md @@ -0,0 +1,1484 @@ +0.98.4 Release notes (2016-03-10) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* None. + +### Bugfixes + +* Properly report changes made by adding an object to a Realm with + addOrUpdate:/createOrUpdate: to KVO observers for existing objects with that + primary key. +* Fix crashes and assorted issues when a migration which added object link + properties is rolled back due to an error in the migration block. +* Fix assertion failures when deleting objects within a migration block of a + type which had an object link property added in that migration. +* Fix an assertion failure in `Query::apply_patch` when updating certain kinds + of queries after a write transaction is committed. + +0.98.3 Release notes (2016-02-26) +============================================================= + +### Enhancements + +* Initializing the shared schema is 3x faster. + +### Bugfixes + +* Using Realm Objective-C from Swift while having Realm Swift linked no longer causes that the + declared `ignoredProperties` are not taken into account. +* Fix assertion failures when rolling back a migration which added Object link + properties to a class. +* Fix potential errors when cancelling a write transaction which modified + multiple `RLMArray`/`List` properties. +* Report the correct value for inWriteTransaction after attempting to commit a + write transaction fails. +* Support CocoaPods 1.0 beginning from prerelease 1.0.0.beta.4 while retaining + backwards compatibility with 0.39. + +0.98.2 Release notes (2016-02-18) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* Aggregate operations (`ANY`, `NONE`, `@count`, `SUBQUERY`, etc.) are now supported for key paths + that begin with an object relationship so long as there is a `RLMArray`/`List` property at some + point in a key path. +* Predicates of the form `%@ IN arrayProperty` are now supported. + +### Bugfixes + +* Use of KVC collection operators on Swift collection types no longer throws an exception. +* Fix reporting of inWriteTransaction in notifications triggered by + `beginWriteTransaction`. +* The contents of `List` and `Optional` properties are now correctly preserved when copying + a Swift object from one Realm to another, and performing other operations that result in a + Swift object graph being recursively traversed from Objective-C. +* Fix a deadlock when queries are performed within a Realm notification block. +* The `ANY` / `SOME` / `NONE` qualifiers are now required in comparisons involving a key path that + traverse a `RLMArray`/`List` property. Previously they were only required if the first key in the + key path was an `RLMArray`/`List` property. +* Fix several scenarios where the default schema would be initialized + incorrectly if the first Realm opened used a restricted class subset (via + `objectClasses`/`objectTypes`). + +0.98.1 Release notes (2016-02-10) +============================================================= + +### Bugfixes + +* Fix crashes when deleting an object containing an `RLMArray`/`List` which had + previously been queried. +* Fix a crash when deleting an object containing an `RLMArray`/`List` with + active notification blocks. +* Fix duplicate file warnings when building via CocoaPods. +* Fix crash or incorrect results when calling `indexOfObject:` on an + `RLMResults` derived from an `RLMArray`. + +0.98.0 Release notes (2016-02-04) +============================================================= + +### API breaking changes + +* `+[RLMRealm realmWithPath:]`/`Realm.init(path:)` now inherits from the default + configuration. +* Swift 1.2 is no longer supported. + +### Enhancements + +* Add `addNotificationBlock` to `RLMResults`, `Results`, `RLMArray`, and + `List`, which calls the given block whenever the collection changes. +* Do a lot of the work for keeping `RLMResults`/`Results` up-to-date after + write transactions on a background thread to help avoid blocking the main + thread. +* `NSPredicate`'s `SUBQUERY` operator is now supported. It has the following limitations: + * `@count` is the only operator that may be applied to the `SUBQUERY` expression. + * The `SUBQUERY(…).@count` expression must be compared with a constant. + * Correlated subqueries are not yet supported. + +### Bugfixes + +* None. + +0.97.1 Release notes (2016-01-29) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* Swift: Added `Error` enum allowing to catch errors e.g. thrown on initializing + `RLMRealm`/`Realm` instances. +* Fail with `RLMErrorFileNotFound` instead of the more generic `RLMErrorFileAccess`, + if no file was found when a realm was opened as read-only or if the directory part + of the specified path was not found when a copy should be written. +* Greatly improve performance when deleting objects with one or more indexed + properties. +* Indexing `BOOL`/`Bool` and `NSDate` properties are now supported. +* Swift: Add support for indexing optional properties. + +### Bugfixes + +* Fix incorrect results or crashes when using `-[RLMResults setValue:forKey:]` + on an RLMResults which was filtered on the key being set. +* Fix crashes when an RLMRealm is deallocated from the wrong thread. +* Fix incorrect results from aggregate methods on `Results`/`RLMResults` after + objects which were previously in the results are deleted. +* Fix a crash when adding a new property to an existing class with over a + million objects in the Realm. +* Fix errors when opening encrypted Realm files created with writeCopyToPath. +* Fix crashes or incorrect results for queries that use relationship equality + in cases where the `RLMResults` is kept alive and instances of the target class + of the relationship are deleted. + +0.97.0 Release notes (2015-12-17) +============================================================= + +### API breaking changes + +* All functionality deprecated in previous releases has been removed entirely. +* Add generic type annotations to NSArrays and NSDictionaries in public APIs. +* Adding a Realm notification block on a thread not currently running from + within a run loop throws an exception rather than silently never calling the + notification block. + +### Enhancements + +* Support for tvOS. +* Support for building Realm Swift from source when using Carthage. +* The block parameter of `-[RLMRealm transactionWithBlock:]`/`Realm.write(_:)` is + now marked as `__attribute__((noescape))`/`@noescape`. +* Many forms of queries with key paths on both sides of the comparison operator + are now supported. +* Add support for KVC collection operators in `RLMResults` and `RLMArray`. +* Fail instead of deadlocking in `+[RLMRealm sharedSchema]`, if a Swift property is initialized + to a computed value, which attempts to open a Realm on its own. + +### Bugfixes + +* Fix poor performance when calling `-[RLMRealm deleteObjects:]` on an + `RLMResults` which filtered the objects when there are other classes linking + to the type of the deleted objects. +* An exception is now thrown when defining `Object` properties of an unsupported + type. + +0.96.3 Release notes (2015-12-04) +============================================================= + +### Enhancements + +* Queries are no longer limited to 16 levels of grouping. +* Rework the implementation of encrypted Realms to no longer interfere with + debuggers. + +### Bugfixes + +* Fix crash when trying to retrieve object instances via `dynamicObjects`. +* Throw an exception when querying on a link providing objects, which are from a different Realm. +* Return empty results when querying on a link providing an unattached object. +* Fix crashes or incorrect results when calling `-[RLMRealm refresh]` during + fast enumeration. +* Add `Int8` support for `RealmOptional`, `MinMaxType` and `AddableType`. +* Set the default value for newly added non-optional NSData properties to a + zero-byte NSData rather than nil. +* Fix a potential crash when deleting all objects of a class. +* Fix performance problems when creating large numbers of objects with + `RLMArray`/`List` properties. +* Fix memory leak when using Object(value:) for subclasses with + `List` or `RealmOptional` properties. +* Fix a crash when computing the average of an optional integer property. +* Fix incorrect search results for some queries on integer properties. +* Add error-checking for nil realm parameters in many methods such as + `+[RLMObject allObjectsInRealm:]`. +* Fix a race condition between commits and opening Realm files on new threads + that could lead to a crash. +* Fix several crashes when opening Realm files. +* `-[RLMObject createInRealm:withValue:]`, `-[RLMObject createOrUpdateInRealm:withValue:]`, and + their variants for the default Realm now always match the contents of an `NSArray` against properties + in the same order as they are defined in the model. + +0.96.2 Release notes (2015-10-26) +============================================================= + +Prebuilt frameworks are now built with Xcode 7.1. + +### Bugfixes + +* Fix ignoring optional properties in Swift. +* Fix CocoaPods installation on case-sensitive file systems. + +0.96.1 Release notes (2015-10-20) +============================================================= + +### Bugfixes + +* Support assigning `Results` to `List` properties via KVC. +* Honor the schema version set in the configuration in `+[RLMRealm migrateRealm:]`. +* Fix crash when using optional Int16/Int32/Int64 properties in Swift. + +0.96.0 Release notes (2015-10-14) +============================================================= + +* No functional changes since beta2. + +0.96.0-beta2 Release notes (2015-10-08) +============================================================= + +### Bugfixes + +* Add RLMOptionalBase.h to the podspec. + +0.96.0-beta Release notes (2015-10-07) +============================================================= + +### API breaking changes + +* CocoaPods v0.38 or greater is now required to install Realm and RealmSwift + as pods. + +### Enhancements + +* Functionality common to both `List` and `Results` is now declared in a + `RealmCollectionType` protocol that both types conform to. +* `Results.realm` now returns an `Optional` in order to conform to + `RealmCollectionType`, but will always return `.Some()` since a `Results` + cannot exist independently from a `Realm`. +* Aggregate operations are now available on `List`: `min`, `max`, `sum`, + `average`. +* Committing write transactions (via `commitWrite` / `commitWriteTransaction` and + `write` / `transactionWithBlock`) now optionally allow for handling errors when + the disk is out of space. +* Added `isEmpty` property on `RLMRealm`/`Realm` to indicate if it contains any + objects. +* The `@count`, `@min`, `@max`, `@sum` and `@avg` collection operators are now + supported in queries. + +### Bugfixes + +* Fix assertion failure when inserting NSData between 8MB and 16MB in size. +* Fix assertion failure when rolling back a migration which removed an object + link or `RLMArray`/`List` property. +* Add the path of the file being opened to file open errors. +* Fix a crash that could be triggered by rapidly opening and closing a Realm + many times on multiple threads at once. +* Fix several places where exception messages included the name of the wrong + function which failed. + +0.95.3 Release notes (2015-10-05) +============================================================= + +### Bugfixes + +* Compile iOS Simulator framework architectures with `-fembed-bitcode-marker`. +* Fix crashes when the first Realm opened uses a class subset and later Realms + opened do not. +* Fix inconsistent errors when `Object(value: ...)` is used to initialize the + default value of a property of an `Object` subclass. +* Throw an exception when a class subset has objects with array or object + properties of a type that are not part of the class subset. + +0.95.2 Release notes (2015-09-24) +============================================================= + +* Enable bitcode for iOS and watchOS frameworks. +* Build libraries with Xcode 7 final rather than the GM. + +0.95.1 Release notes (2015-09-23) +============================================================= + +### Enhancements + +* Add missing KVO handling for moving and exchanging objects in `RLMArray` and + `List`. + +### Bugfixes + +* Setting the primary key property on persisted `RLMObject`s / `Object`s + via subscripting or key-value coding will cause an exception to be thrown. +* Fix crash due to race condition in `RLMRealmConfiguration` where the default + configuration was in the process of being copied in one thread, while + released in another. +* Fix crash when a migration which removed an object or array property is + rolled back due to an error. + +0.95.0 Release notes (2015-08-25) +============================================================= + +### API breaking changes + +* The following APIs have been deprecated in favor of the new `RLMRealmConfiguration` class in Realm Objective-C: + +| Deprecated API | New API | +|:------------------------------------------------------------------|:---------------------------------------------------------------------------------| +| `+[RLMRealm realmWithPath:readOnly:error:]` | `+[RLMRealm realmWithConfiguration:error:]` | +| `+[RLMRealm realmWithPath:encryptionKey:readOnly:error:]` | `+[RLMRealm realmWithConfiguration:error:]` | +| `+[RLMRealm setEncryptionKey:forRealmsAtPath:]` | `-[RLMRealmConfiguration setEncryptionKey:]` | +| `+[RLMRealm inMemoryRealmWithIdentifier:]` | `+[RLMRealm realmWithConfiguration:error:]` | +| `+[RLMRealm defaultRealmPath]` | `+[RLMRealmConfiguration defaultConfiguration]` | +| `+[RLMRealm setDefaultRealmPath:]` | `+[RLMRealmConfiguration setDefaultConfiguration:]` | +| `+[RLMRealm setDefaultRealmSchemaVersion:withMigrationBlock]` | `RLMRealmConfiguration.schemaVersion` and `RLMRealmConfiguration.migrationBlock` | +| `+[RLMRealm setSchemaVersion:forRealmAtPath:withMigrationBlock:]` | `RLMRealmConfiguration.schemaVersion` and `RLMRealmConfiguration.migrationBlock` | +| `+[RLMRealm migrateRealmAtPath:]` | `+[RLMRealm migrateRealm:]` | +| `+[RLMRealm migrateRealmAtPath:encryptionKey:]` | `+[RLMRealm migrateRealm:]` | + +* The following APIs have been deprecated in favor of the new `Realm.Configuration` struct in Realm Swift for Swift 1.2: + +| Deprecated API | New API | +|:--------------------------------------------------------------|:-----------------------------------------------------------------------------| +| `Realm.defaultPath` | `Realm.Configuration.defaultConfiguration` | +| `Realm(path:readOnly:encryptionKey:error:)` | `Realm(configuration:error:)` | +| `Realm(inMemoryIdentifier:)` | `Realm(configuration:error:)` | +| `Realm.setEncryptionKey(:forPath:)` | `Realm(configuration:error:)` | +| `setDefaultRealmSchemaVersion(schemaVersion:migrationBlock:)` | `Realm.Configuration.schemaVersion` and `Realm.Configuration.migrationBlock` | +| `setSchemaVersion(schemaVersion:realmPath:migrationBlock:)` | `Realm.Configuration.schemaVersion` and `Realm.Configuration.migrationBlock` | +| `migrateRealm(path:encryptionKey:)` | `migrateRealm(configuration:)` | + +* The following APIs have been deprecated in favor of the new `Realm.Configuration` struct in Realm Swift for Swift 2.0: + +| Deprecated API | New API | +|:--------------------------------------------------------------|:-----------------------------------------------------------------------------| +| `Realm.defaultPath` | `Realm.Configuration.defaultConfiguration` | +| `Realm(path:readOnly:encryptionKey:) throws` | `Realm(configuration:) throws` | +| `Realm(inMemoryIdentifier:)` | `Realm(configuration:) throws` | +| `Realm.setEncryptionKey(:forPath:)` | `Realm(configuration:) throws` | +| `setDefaultRealmSchemaVersion(schemaVersion:migrationBlock:)` | `Realm.Configuration.schemaVersion` and `Realm.Configuration.migrationBlock` | +| `setSchemaVersion(schemaVersion:realmPath:migrationBlock:)` | `Realm.Configuration.schemaVersion` and `Realm.Configuration.migrationBlock` | +| `migrateRealm(path:encryptionKey:)` | `migrateRealm(configuration:)` | + +* `List.extend` in Realm Swift for Swift 2.0 has been replaced with `List.appendContentsOf`, + mirroring changes to `RangeReplaceableCollectionType`. + +* Object properties on `Object` subclasses in Realm Swift must be marked as optional, + otherwise a runtime exception will be thrown. + +### Enhancements + +* Persisted properties of `RLMObject`/`Object` subclasses are now Key-Value + Observing compliant. +* The different options used to create Realm instances have been consolidated + into a single `RLMRealmConfiguration`/`Realm.Configuration` object. +* Enumerating Realm collections (`RLMArray`, `RLMResults`, `List<>`, + `Results<>`) now enumerates over a copy of the collection, making it no + longer an error to modify a collection during enumeration (either directly, + or indirectly by modifying objects to make them no longer match a query). +* Improve performance of object insertion in Swift to bring it roughly in line + with Objective-C. +* Allow specifying a specific list of `RLMObject` / `Object` subclasses to include + in a given Realm via `RLMRealmConfiguration.objectClasses` / `Realm.Configuration.objectTypes`. + +### Bugfixes + +* Subscripting on `RLMObject` is now marked as nullable. + +0.94.1 Release notes (2015-08-10) +============================================================= + +### API breaking changes + +* Building for watchOS requires Xcode 7 beta 5. + +### Enhancements + +* `Object.className` is now marked as `final`. + +### Bugfixes + +* Fix crash when adding a property to a model without updating the schema + version. +* Fix unnecessary redownloading of the core library when building from source. +* Fix crash when sorting by an integer or floating-point property on iOS 7. + +0.94.0 Release notes (2015-07-29) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* Reduce the amount of memory used by RLMRealm notification listener threads. +* Avoid evaluating results eagerly when filtering and sorting. +* Add nullability annotations to the Objective-C API to provide enhanced compiler + warnings and bridging to Swift. +* Make `RLMResult`s and `RLMArray`s support Objective-C generics. +* Add support for building watchOS and bitcode-compatible apps. +* Make the exceptions thrown in getters and setters more informative. +* Add `-[RLMArray exchangeObjectAtIndex:withObjectAtIndex]` and `List.swap(_:_:)` + to allow exchanging the location of two objects in the given `RLMArray` / `List`. +* Added anonymous analytics on simulator/debugger runs. +* Add `-[RLMArray moveObjectAtIndex:toIndex:]` and `List.move(from:to:)` to + allow moving objects in the given `RLMArray` / `List`. + +### Bugfixes + +* Processes crashing due to an uncaught exception inside a write transaction will + no longer cause other processes using the same Realm to hang indefinitely. +* Fix incorrect results when querying for < or <= on ints that + require 64 bits to represent with a CPU that supports SSE 4.2. +* An exception will no longer be thrown when attempting to reset the schema + version or encryption key on an open Realm to the current value. +* Date properties on 32 bit devices will retain 64 bit second precision. +* Wrap calls to the block passed to `enumerate` in an autoreleasepool to reduce + memory growth when migrating a large amount of objects. +* In-memory realms no longer write to the Documents directory on iOS or + Application Support on OS X. + +0.93.2 Release notes (2015-06-12) +============================================================= + +### Bugfixes + +* Fixed an issue where the packaged OS X Realm.framework was built with + `GCC_GENERATE_TEST_COVERAGE_FILES` and `GCC_INSTRUMENT_PROGRAM_FLOW_ARCS` + enabled. +* Fix a memory leak when constructing standalone Swift objects with NSDate + properties. +* Throw an exception rather than asserting when an invalidated object is added + to an RLMArray. +* Fix a case where data loss would occur if a device was hard-powered-off + shortly after a write transaction was committed which had to expand the Realm + file. + +0.93.1 Release notes (2015-05-29) +============================================================= + +### Bugfixes + +* Objects are no longer copied into standalone objects during object creation. This fixes an issue where + nested objects with a primary key are sometimes duplicated rather than updated. +* Comparison predicates with a constant on the left of the operator and key path on the right now give + correct results. An exception is now thrown for predicates that do not yet support this ordering. +* Fix some crashes in `index_string.cpp` with int primary keys or indexed int properties. + +0.93.0 Release notes (2015-05-27) +============================================================= + +### API breaking changes + +* Schema versions are now represented as `uint64_t` (Objective-C) and `UInt64` (Swift) so that they have + the same representation on all architectures. + +### Enhancements + +* Swift: `Results` now conforms to `CVarArgType` so it can + now be passed as an argument to `Results.filter(_:...)` + and `List.filter(_:...)`. +* Swift: Made `SortDescriptor` conform to the `Equatable` and + `StringLiteralConvertible` protocols. +* Int primary keys are once again automatically indexed. +* Improve error reporting when attempting to mark a property of a type that + cannot be indexed as indexed. + +### Bugfixes + +* Swift: `RealmSwift.framework` no longer embeds `Realm.framework`, + which now allows apps using it to pass iTunes Connect validation. + +0.92.4 Release notes (2015-05-22) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* Swift: Made `Object.init()` a required initializer. +* `RLMObject`, `RLMResults`, `Object` and `Results` can now be safely + deallocated (but still not used) from any thread. +* Improve performance of `-[RLMArray indexOfObjectWhere:]` and `-[RLMArray + indexOfObjectWithPredicate:]`, and implement them for standalone RLMArrays. +* Improved performance of most simple queries. + +### Bugfixes + +* The interprocess notification mechanism no longer uses dispatch worker threads, preventing it from + starving other GCD clients of the opportunity to execute blocks when dozens of Realms are open at once. + +0.92.3 Release notes (2015-05-13) +============================================================= + +### API breaking changes + +* Swift: `Results.average(_:)` now returns an optional, which is `nil` if and only if the results + set is empty. + +### Enhancements + +* Swift: Added `List.invalidated`, which returns if the given `List` is no longer + safe to be accessed, and is analogous to `-[RLMArray isInvalidated]`. +* Assertion messages are automatically logged to Crashlytics if it's loaded + into the current process to make it easier to diagnose crashes. + +### Bugfixes + +* Swift: Enumerating through a standalone `List` whose objects themselves + have list properties won't crash. +* Swift: Using a subclass of `RealmSwift.Object` in an aggregate operator of a predicate + no longer throws a spurious type error. +* Fix incorrect results for when using OR in a query on a `RLMArray`/`List<>`. +* Fix incorrect values from `[RLMResults count]`/`Results.count` when using + `!=` on an int property with no other query conditions. +* Lower the maximum doubling threshold for Realm file sizes from 128MB to 16MB + to reduce the amount of wasted space. + +0.92.2 Release notes (2015-05-08) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* Exceptions raised when incorrect object types are used with predicates now contain more detailed information. +* Added `-[RLMMigration deleteDataForClassName:]` and `Migration.deleteData(_:)` + to enable cleaning up after removing object subclasses + +### Bugfixes + +* Prevent debugging of an application using an encrypted Realm to work around + frequent LLDB hangs. Until the underlying issue is addressed you may set + REALM_DISABLE_ENCRYPTION=YES in your application's environment variables to + have requests to open an encrypted Realm treated as a request for an + unencrypted Realm. +* Linked objects are properly updated in `createOrUpdateInRealm:withValue:`. +* List properties on Objects are now properly initialized during fast enumeration. + +0.92.1 Release notes (2015-05-06) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* `-[RLMRealm inWriteTransaction]` is now public. +* Realm Swift is now available on CoocaPods. + +### Bugfixes + +* Force code re-signing after stripping architectures in `strip-frameworks.sh`. + +0.92.0 Release notes (2015-05-05) +============================================================= + +### API breaking changes + +* Migration blocks are no longer called when a Realm file is first created. +* The following APIs have been deprecated in favor of newer method names: + +| Deprecated API | New API | +|:-------------------------------------------------------|:------------------------------------------------------| +| `-[RLMMigration createObject:withObject:]` | `-[RLMMigration createObject:withValue:]` | +| `-[RLMObject initWithObject:]` | `-[RLMObject initWithValue:]` | +| `+[RLMObject createInDefaultRealmWithObject:]` | `+[RLMObject createInDefaultRealmWithValue:]` | +| `+[RLMObject createInRealm:withObject:]` | `+[RLMObject createInRealm:withValue:]` | +| `+[RLMObject createOrUpdateInDefaultRealmWithObject:]` | `+[RLMObject createOrUpdateInDefaultRealmWithValue:]` | +| `+[RLMObject createOrUpdateInRealm:withObject:]` | `+[RLMObject createOrUpdateInRealm:withValue:]` | + +### Enhancements + +* `Int8` properties defined in Swift are now treated as integers, rather than + booleans. +* NSPredicates created using `+predicateWithValue:` are now supported. + +### Bugfixes + +* Compound AND predicates with no subpredicates now correctly match all objects. + +0.91.5 Release notes (2015-04-28) +============================================================= + +### Bugfixes + +* Fix issues with removing search indexes and re-enable it. + +0.91.4 Release notes (2015-04-27) +============================================================= + +### Bugfixes + +* Temporarily disable removing indexes from existing columns due to bugs. + +0.91.3 Release notes (2015-04-17) +============================================================= + +### Bugfixes + +* Fix `Extra argument 'objectClassName' in call` errors when building via + CocoaPods. + +0.91.2 Release notes (2015-04-16) +============================================================= + +* Migration blocks are no longer called when a Realm file is first created. + +### Enhancements + +* `RLMCollection` supports collection KVC operations. +* Sorting `RLMResults` is 2-5x faster (typically closer to 2x). +* Refreshing `RLMRealm` after a write transaction which inserts or modifies + strings or `NSData` is committed on another thread is significantly faster. +* Indexes are now added and removed from existing properties when a Realm file + is opened, rather than only when properties are first added. + +### Bugfixes + +* `+[RLMSchema dynamicSchemaForRealm:]` now respects search indexes. +* `+[RLMProperty isEqualToProperty:]` now checks for equal `indexed` properties. + +0.91.1 Release notes (2015-03-12) +============================================================= + +### Enhancements + +* The browser will automatically refresh when the Realm has been modified + from another process. +* Allow using Realm in an embedded framework by setting + `APPLICATION_EXTENSION_API_ONLY` to YES. + +### Bugfixes + +* Fix a crash in CFRunLoopSourceInvalidate. + +0.91.0 Release notes (2015-03-10) +============================================================= + +### API breaking changes + +* `attributesForProperty:` has been removed from `RLMObject`. You now specify indexed + properties by implementing the `indexedProperties` method. +* An exception will be thrown when calling `setEncryptionKey:forRealmsAtPath:`, + `setSchemaVersion:forRealmAtPath:withMigrationBlock:`, and `migrateRealmAtPath:` + when a Realm at the given path is already open. +* Object and array properties of type `RLMObject` will no longer be allowed. + +### Enhancements + +* Add support for sharing Realm files between processes. +* The browser will no longer show objects that have no persisted properties. +* `RLMSchema`, `RLMObjectSchema`, and `RLMProperty` now have more useful descriptions. +* Opening an encrypted Realm while a debugger is attached to the process no + longer throws an exception. +* `RLMArray` now exposes an `isInvalidated` property to indicate if it can no + longer be accessed. + +### Bugfixes + +* An exception will now be thrown when calling `-beginWriteTransaction` from within a notification + triggered by calling `-beginWriteTransaction` elsewhere. +* When calling `delete:` we now verify that the object being deleted is persisted in the target Realm. +* Fix crash when calling `createOrUpdate:inRealm` with nested linked objects. +* Use the key from `+[RLMRealm setEncryptionKey:forRealmsAtPath:]` in + `-writeCopyToPath:error:` and `+migrateRealmAtPath:`. +* Comparing an RLMObject to a non-RLMObject using `-[RLMObject isEqual:]` or + `-isEqualToObject:` now returns NO instead of crashing. +* Improved error message when an `RLMObject` subclass is defined nested within + another Swift declaration. +* Fix crash when the process is terminated by the OS on iOS while encrypted realms are open. +* Fix crash after large commits to encrypted realms. + +0.90.6 Release notes (2015-02-20) +============================================================= + +### Enhancements + +* Improve compatiblity of encrypted Realms with third-party crash reporters. + +### Bugfixes + +* Fix incorrect results when using aggregate functions on sorted RLMResults. +* Fix data corruption when using writeCopyToPath:encryptionKey:. +* Maybe fix some assertion failures. + +0.90.5 Release notes (2015-02-04) +============================================================= + +### Bugfixes + +* Fix for crashes when encryption is enabled on 64-bit iOS devices. + +0.90.4 Release notes (2015-01-29) +============================================================= + +### Bugfixes + +* Fix bug that resulted in columns being dropped and recreated during migrations. + +0.90.3 Release notes (2015-01-27) +============================================================= + +### Enhancements + +* Calling `createInDefaultRealmWithObject:`, `createInRealm:withObject:`, + `createOrUpdateInDefaultRealmWithObject:` or `createOrUpdateInRealm:withObject:` + is a no-op if the argument is an RLMObject of the same type as the receiver + and is already backed by the target realm. + +### Bugfixes + +* Fix incorrect column type assertions when the first Realm file opened is a + read-only file that is missing tables. +* Throw an exception when adding an invalidated or deleted object as a link. +* Throw an exception when calling `createOrUpdateInRealm:withObject:` when the + receiver has no primary key defined. + +0.90.1 Release notes (2015-01-22) +============================================================= + +### Bugfixes + +* Fix for RLMObject being treated as a model object class and showing up in the browser. +* Fix compilation from the podspec. +* Fix for crash when calling `objectsWhere:` with grouping in the query on `allObjects`. + +0.90.0 Release notes (2015-01-21) +============================================================= + +### API breaking changes + +* Rename `-[RLMRealm encryptedRealmWithPath:key:readOnly:error:]` to + `-[RLMRealm realmWithPath:encryptionKey:readOnly:error:]`. +* `-[RLMRealm setSchemaVersion:withMigrationBlock]` is no longer global and must be called + for each individual Realm path used. You can now call `-[RLMRealm setDefaultRealmSchemaVersion:withMigrationBlock]` + for the default Realm and `-[RLMRealm setSchemaVersion:forRealmAtPath:withMigrationBlock:]` for all others; + +### Enhancements + +* Add `-[RLMRealm writeCopyToPath:encryptionKey:error:]`. +* Add support for comparing string columns to other string columns in queries. + +### Bugfixes + +* Roll back changes made when an exception is thrown during a migration. +* Throw an exception if the number of items in a RLMResults or RLMArray changes + while it's being fast-enumerated. +* Also encrypt the temporary files used when encryption is enabled for a Realm. +* Fixed crash in JSONImport example on OS X with non-en_US locale. +* Fixed infinite loop when opening a Realm file in the Browser at the same time + as it is open in a 32-bit simulator. +* Fixed a crash when adding primary keys to older realm files with no primary + keys on any objects. +* Fixed a crash when removing a primary key in a migration. +* Fixed a crash when multiple write transactions with no changes followed by a + write transaction with changes were committed without the main thread + RLMRealm getting a chance to refresh. +* Fixed incomplete results when querying for non-null relationships. +* Improve the error message when a Realm file is opened in multiple processes + at once. + +0.89.2 Release notes (2015-01-02) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* None. + +### Bugfixes + +* Fix an assertion failure when invalidating a Realm which is in a write + transaction, has already been invalidated, or has never been used. +* Fix an assertion failure when sorting an empty RLMArray property. +* Fix a bug resulting in the browser never becoming visible on 10.9. +* Write UTF-8 when generating class files from a realm file in the Browser. + +0.89.1 Release notes (2014-12-22) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* Improve the error message when a Realm can't be opened due to lacking write + permissions. + +### Bugfixes + +* Fix an assertion failure when inserting rows after calling `deleteAllObjects` + on a Realm. +* Separate dynamic frameworks are now built for the simulator and devices to + work around App Store submission errors due to the simulator version not + being automatically stripped from dynamic libraries. + +0.89.0 Release notes (2014-12-18) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* Add support for encrypting Realm files on disk. +* Support using KVC-compliant objects without getters or with custom getter + names to initialize RLMObjects with `createObjectInRealm` and friends. + +### Bugfixes + +* Merge native Swift default property values with defaultPropertyValues(). +* Don't leave the database schema partially updated when opening a realm fails + due to a migration being needed. +* Fixed issue where objects with custom getter names couldn't be used to + initialize other objects. +* Fix a major performance regression on queries on string properties. +* Fix a memory leak when circularly linked objects are added to a Realm. + +0.88.0 Release notes (2014-12-02) +============================================================= + +### API breaking changes + +* Deallocating an RLMRealm instance in a write transaction lacking an explicit + commit/cancel will now be automatically cancelled instead of committed. +* `-[RLMObject isDeletedFromRealm]` has been renamed to `-[RLMObject isInvalidated]`. + +### Enhancements + +* Add `-[RLMRealm writeCopyToPath:]` to write a compacted copy of the Realm + another file. +* Add support for case insensitive, BEGINSWITH, ENDSWITH and CONTAINS string + queries on array properties. +* Make fast enumeration of `RLMArray` and `RLMResults` ~30% faster and + `objectAtIndex:` ~55% faster. +* Added a lldb visualizer script for displaying the contents of persisted + RLMObjects when debugging. +* Added method `-setDefaultRealmPath:` to change the default Realm path. +* Add `-[RLMRealm invalidate]` to release data locked by the current thread. + +### Bugfixes + +* Fix for crash when running many simultaneous write transactions on background threads. +* Fix for crashes caused by opening Realms at multiple paths simultaneously which have had + properties re-ordered during migration. +* Don't run the query twice when `firstObject` or `lastObject` are called on an + `RLMResults` which has not had its results accessed already. +* Fix for bug where schema version is 0 for new Realm created at the latest version. +* Fix for error message where no migration block is specified when required. + +0.87.4 Release notes (2014-11-07) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* None. + +### Bugfixes + +* Fix browser location in release zip. + +0.87.3 Release notes (2014-11-06) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* Added method `-linkingObjectsOfClass:forProperty:` to RLMObject to expose inverse + relationships/backlinks. + +### Bugfixes + +* Fix for crash due to missing search index when migrating an object with a string primary key + in a database created using an older versions (0.86.3 and earlier). +* Throw an exception when passing an array containing a + non-RLMObject to -[RLMRealm addObjects:]. +* Fix for crash when deleting an object from multiple threads. + +0.87.0 Release notes (2014-10-21) +============================================================= + +### API breaking changes + +* RLMArray has been split into two classes, `RLMArray` and `RLMResults`. RLMArray is + used for object properties as in previous releases. Moving forward all methods used to + enumerate, query, and sort objects return an instance of a new class `RLMResults`. This + change was made to support diverging apis and the future addition of change notifications + for queries. +* The api for migrations has changed. You now call `setSchemaVersion:withMigrationBlock:` to + register a global migration block and associated version. This block is applied to Realms as + needed when opened for Realms at a previous version. The block can be applied manually if + desired by calling `migrateRealmAtPath:`. +* `arraySortedByProperty:ascending:` was renamed to `sortedResultsUsingProperty:ascending` +* `addObjectsFromArray:` on both `RLMRealm` and `RLMArray` has been renamed to `addObjects:` + and now accepts any container class which implements `NSFastEnumeration` +* Building with Swift support now requires Xcode 6.1 + +### Enhancements + +* Add support for sorting `RLMArray`s by multiple columns with `sortedResultsUsingDescriptors:` +* Added method `deleteAllObjects` on `RLMRealm` to clear a Realm. +* Added method `createObject:withObject:` on `RLMMigration` which allows object creation during migrations. +* Added method `deleteObject:` on `RLMMigration` which allows object deletion during migrations. +* Updating to core library version 0.85.0. +* Implement `objectsWhere:` and `objectsWithPredicate:` for array properties. +* Add `cancelWriteTransaction` to revert all changes made in a write transaction and end the transaction. +* Make creating `RLMRealm` instances on background threads when an instance + exists on another thread take a fifth of the time. +* Support for partial updates when calling `createOrUpdateWithObject:` and `addOrUpdateObject:` +* Re-enable Swift support on OS X + +### Bugfixes + +* Fix exceptions when trying to set `RLMObject` properties after rearranging + the properties in a `RLMObject` subclass. +* Fix crash on IN query with several thousand items. +* Fix crash when querying indexed `NSString` properties. +* Fixed an issue which prevented in-memory Realms from being used accross multiple threads. +* Preserve the sort order when querying a sorted `RLMResults`. +* Fixed an issue with migrations where if a Realm file is deleted after a Realm is initialized, + the newly created Realm can be initialized with an incorrect schema version. +* Fix crash in `RLMSuperSet` when assigning to a `RLMArray` property on a standalone object. +* Add an error message when the protocol for an `RLMArray` property is not a + valid object type. +* Add an error message when an `RLMObject` subclass is defined nested within + another Swift class. + +0.86.3 Release notes (2014-10-09) +============================================================= + +### Enhancements + +* Add support for != in queries on object relationships. + +### Bugfixes + +* Re-adding an object to its Realm no longer throws an exception and is now a no-op + (as it was previously). +* Fix another bug which would sometimes result in subclassing RLMObject + subclasses not working. + +0.86.2 Release notes (2014-10-06) +============================================================= + +### Bugfixes + +* Fixed issues with packaging "Realm Browser.app" for release. + +0.86.1 Release notes (2014-10-03) +============================================================= + +### Bugfixes + +* Fix a bug which would sometimes result in subclassing RLMObject subclasses + not working. + +0.86.0 Release notes (2014-10-03) +============================================================= + +### API breaking changes + +* Xcode 6 is now supported from the main Xcode project `Realm.xcodeproj`. + Xcode 5 is no longer supported. + +### Enhancements + +* Support subclassing RLMObject models. Although you can now persist subclasses, + polymorphic behavior is not supported (i.e. setting a property to an + instance of its subclass). +* Add support for sorting RLMArray properties. +* Speed up inserting objects with `addObject:` by ~20%. +* `readonly` properties are automatically ignored rather than having to be + added to `ignoredProperties`. +* Updating to core library version 0.83.1. +* Return "[deleted object]" rather than throwing an exception when + `-description` is called on a deleted RLMObject. +* Significantly improve performance of very large queries. +* Allow passing any enumerable to IN clauses rather than just NSArray. +* Add `objectForPrimaryKey:` and `objectInRealm:forPrimaryKey:` convenience + methods to fetch an object by primary key. + +### Bugfixes + +* Fix error about not being able to persist property 'hash' with incompatible + type when building for devices with Xcode 6. +* Fix spurious notifications of new versions of Realm. +* Fix for updating nested objects where some types do not have primary keys. +* Fix for inserting objects from JSON with NSNull values when default values + should be used. +* Trying to add a persisted RLMObject to a different Realm now throws an + exception rather than creating an uninitialized object. +* Fix validation errors when using IN on array properties. +* Fix errors when an IN clause has zero items. +* Fix for chained queries ignoring all but the last query's conditions. + +0.85.0 Release notes (2014-09-15) +============================================================= + +### API breaking changes + +* Notifications for a refresh being needed (when autorefresh is off) now send + the notification type RLMRealmRefreshRequiredNotification rather than + RLMRealmDidChangeNotification. + +### Enhancements + +* Updating to core library version 0.83.0. +* Support for primary key properties (for int and string columns). Declaring a property + to be the primary key ensures uniqueness for that property for all objects of a given type. + At the moment indexes on primary keys are not yet supported but this will be added in a future + release. +* Added methods to update or insert (upsert) for objects with primary keys defined. +* `[RLMObject initWithObject:]` and `[RLMObject createInRealmWithObject:]` now support + any object type with kvc properties. +* The Swift support has been reworked to work around Swift not being supported + in Frameworks on iOS 7. +* Improve performance when getting the count of items matching a query but not + reading any of the objects in the results. +* Add a return value to `-[RLMRealm refresh]` that indicates whether or not + there was anything to refresh. +* Add the class name to the error message when an RLMObject is missing a value + for a property without a default. +* Add support for opening Realms in read-only mode. +* Add an automatic check for updates when using Realm in a simulator (the + checker code is not compiled into device builds). This can be disabled by + setting the REALM_DISABLE_UPDATE_CHECKER environment variable to any value. +* Add support for Int16 and Int64 properties in Swift classes. + +### Bugfixes + +* Realm change notifications when beginning a write transaction are now sent + after updating rather than before, to match refresh. +* `-isEqual:` now uses the default `NSObject` implementation unless a primary key + is specified for an RLMObject. When a primary key is specified, `-isEqual:` calls + `-isEqualToObject:` and a corresponding implementation for `-hash` is also implemented. + +0.84.0 Release notes (2014-08-28) +============================================================= + +### API breaking changes + +* The timer used to trigger notifications has been removed. Notifications are now + only triggered by commits made in other threads, and can not currently be triggered + by changes made by other processes. Interprocess notifications will be re-added in + a future commit with an improved design. + +### Enhancements + +* Updating to core library version 0.82.2. +* Add property `deletedFromRealm` to RLMObject to indicate objects which have been deleted. +* Add support for the IN operator in predicates. +* Add support for the BETWEEN operator in link queries. +* Add support for multi-level link queries in predicates (e.g. `foo.bar.baz = 5`). +* Switch to building the SDK from source when using CocoaPods and add a + Realm.Headers subspec for use in targets that should not link a copy of Realm + (such as test targets). +* Allow unregistering from change notifications in the change notification + handler block. +* Significant performance improvements when holding onto large numbers of RLMObjects. +* Realm-Xcode6.xcodeproj now only builds using Xcode6-Beta6. +* Improved performance during RLMArray iteration, especially when mutating + contained objects. + +### Bugfixes + +* Fix crashes and assorted bugs when sorting or querying a RLMArray returned + from a query. +* Notifications are no longer sent when initializing new RLMRealm instances on background + threads. +* Handle object cycles in -[RLMObject description] and -[RLMArray description]. +* Lowered the deployment target for the Xcode 6 projects and Swift examples to + iOS 7.0, as they didn't actually require 8.0. +* Support setting model properties starting with the letter 'z' +* Fixed crashes that could result from switching between Debug and Relase + builds of Realm. + +0.83.0 Release notes (2014-08-13) +============================================================= + +### API breaking changes + +* Realm-Xcode6.xcodeproj now only builds using Xcode6-Beta5. +* Properties to be persisted in Swift classes must be explicitly declared as `dynamic`. +* Subclasses of RLMObject subclasses now throw an exception on startup, rather + than when added to a Realm. + +### Enhancements + +* Add support for querying for nil object properties. +* Improve error message when specifying invalid literals when creating or + initializing RLMObjects. +* Throw an exception when an RLMObject is used from the incorrect thread rather + than crashing in confusing ways. +* Speed up RLMRealm instantiation and array property iteration. +* Allow array and objection relation properties to be missing or null when + creating a RLMObject from a NSDictionary. + +### Bugfixes + +* Fixed a memory leak when querying for objects. +* Fixed initializing array properties on standalone Swift RLMObject subclasses. +* Fix for queries on 64bit integers. + +0.82.0 Release notes (2014-08-05) +============================================================= + +### API breaking changes + +* Realm-Xcode6.xcodeproj now only builds using Xcode6-Beta4. + +### Enhancements + +* Updating to core library version 0.80.5. +* Now support disabling the `autorefresh` property on RLMRealm instances. +* Building Realm-Xcode6 for iOS now builds a universal framework for Simulator & Device. +* Using NSNumber properties (unsupported) now throws a more informative exception. +* Added `[RLMRealm defaultRealmPath]` +* Proper implementation for [RLMArray indexOfObjectWhere:] +* The default Realm path on OS X is now ~/Library/Application Support/[bundle + identifier]/default.realm rather than ~/Documents +* We now check that the correct framework (ios or osx) is used at compile time. + +### Bugfixes + +* Fixed rapid growth of the realm file size. +* Fixed a bug which could cause a crash during RLMArray destruction after a query. +* Fixed bug related to querying on float properties: `floatProperty = 1.7` now works. +* Fixed potential bug related to the handling of array properties (RLMArray). +* Fixed bug where array properties accessed the wrong property. +* Fixed bug that prevented objects with custom getters to be added to a Realm. +* Fixed a bug where initializing a standalone object with an array literal would + trigger an exception. +* Clarified exception messages when using unsupported NSPredicate operators. +* Clarified exception messages when using unsupported property types on RLMObject subclasses. +* Fixed a memory leak when breaking out of a for-in loop on RLMArray. +* Fixed a memory leak when removing objects from a RLMArray property. +* Fixed a memory leak when querying for objects. + + +0.81.0 Release notes (2014-07-22) +============================================================= + +### API breaking changes + +* None. + +### Enhancements + +* Updating to core library version 0.80.3. +* Added support for basic querying of RLMObject and RLMArray properties (one-to-one and one-to-many relationships). + e.g. `[Person objectsWhere:@"dog.name == 'Alfonso'"]` or `[Person objectsWhere:@"ANY dogs.name == 'Alfonso'"]` + Supports all normal operators for numeric and date types. Does not support NSData properties or `BEGINSWITH`, `ENDSWITH`, `CONTAINS` + and other options for string properties. +* Added support for querying for object equality in RLMObject and RLMArray properties (one-to-one and one-to-many relationships). + e.g. `[Person objectsWhere:@"dog == %@", myDog]` `[Person objectsWhere:@"ANY dogs == %@", myDog]` `[Person objectsWhere:@"ANY friends.dog == %@", dog]` + Only supports comparing objects for equality (i.e. ==) +* Added a helper method to RLMRealm to perform a block inside a transaction. +* OSX framework now supported in CocoaPods. + +### Bugfixes + +* Fixed Unicode support in property names and string contents (Chinese, Russian, etc.). Closing #612 and #604. +* Fixed bugs related to migration when properties are removed. +* Fixed keyed subscripting for standalone RLMObjects. +* Fixed bug related to double clicking on a .realm file to launch the Realm Browser (thanks to Dean Moore). + + +0.80.0 Release notes (2014-07-15) +============================================================= + +### API breaking changes + +* Rename migration methods to -migrateDefaultRealmWithBlock: and -migrateRealmAtPath:withBlock: +* Moved Realm specific query methods from RLMRealm to class methods on RLMObject (-allObjects: to +allObjectsInRealm: ect.) + +### Enhancements + +* Added +createInDefaultRealmWithObject: method to RLMObject. +* Added support for array and object literals when calling -createWithObject: and -initWithObject: variants. +* Added method -deleteObjects: to batch delete objects from a Realm +* Support for defining RLMObject models entirely in Swift (experimental, see known issues). +* RLMArrays in Swift support Sequence-style enumeration (for obj in array). +* Implemented -indexOfObject: for RLMArray + +### Known Issues for Swift-defined models + +* Properties other than String, NSData and NSDate require a default value in the model. This can be an empty (but typed) array for array properties. +* The previous caveat also implies that not all models defined in Objective-C can be used for object properties. Only Objective-C models with only implicit (i.e. primitives) or explicit default values can be used. However, any Objective-C model object can be used in a Swift array property. +* Array property accessors don't work until its parent object has been added to a realm. +* Realm-Bridging-Header.h is temporarily exposed as a public header. This is temporary and will be private again once rdar://17633863 is fixed. +* Does not leverage Swift generics and still uses RLM-prefix everywhere. This is coming in #549. + + +0.22.0 Release notes +============================================================= + +### API breaking changes + +* Rename schemaForObject: to schemaForClassName: on RLMSchema +* Removed -objects:where: and -objects:orderedBy:where: from RLMRealm +* Removed -indexOfObjectWhere:, -objectsWhere: and -objectsOrderedBy:where: from RLMArray +* Removed +objectsWhere: and +objectsOrderedBy:where: from RLMObject + +### Enhancements + +* New Xcode 6 project for experimental swift support. +* New Realm Editor app for reading and editing Realm db files. +* Added support for migrations. +* Added support for RLMArray properties on objects. +* Added support for creating in-memory default Realm. +* Added -objectsWithClassName:predicateFormat: and -objectsWithClassName:predicate: to RLMRealm +* Added -indexOfObjectWithPredicateFormat:, -indexOfObjectWithPredicate:, -objectsWithPredicateFormat:, -objectsWithPredi +* Added +objectsWithPredicateFormat: and +objectsWithPredicate: to RLMObject +* Now allows predicates comparing two object properties of the same type. + + +0.20.0 Release notes (2014-05-28) +============================================================= + +Completely rewritten to be much more object oriented. + +### API breaking changes + +* Everything + +### Enhancements + +* None. + +### Bugfixes + +* None. + + +0.11.0 Release notes (not released) +============================================================= + +The Objective-C API has been updated and your code will break! + +### API breaking changes + +* `RLMTable` objects can only be created with an `RLMRealm` object. +* Renamed `RLMContext` to `RLMTransactionManager` +* Renamed `RLMContextDidChangeNotification` to `RLMRealmDidChangeNotification` +* Renamed `contextWithDefaultPersistence` to `managerForDefaultRealm` +* Renamed `contextPersistedAtPath:` to `managerForRealmWithPath:` +* Renamed `realmWithDefaultPersistence` to `defaultRealm` +* Renamed `realmWithDefaultPersistenceAndInitBlock` to `defaultRealmWithInitBlock` +* Renamed `find:` to `firstWhere:` +* Renamed `where:` to `allWhere:` +* Renamed `where:orderBy:` to `allWhere:orderBy:` + +### Enhancements + +* Added `countWhere:` on `RLMTable` +* Added `sumOfColumn:where:` on `RLMTable` +* Added `averageOfColumn:where:` on `RLMTable` +* Added `minOfProperty:where:` on `RLMTable` +* Added `maxOfProperty:where:` on `RLMTable` +* Added `toJSONString` on `RLMRealm`, `RLMTable` and `RLMView` +* Added support for `NOT` operator in predicates +* Added support for default values +* Added validation support in `createInRealm:withObject:` + +### Bugfixes + +* None. + + +0.10.0 Release notes (2014-04-23) +============================================================= + +TightDB is now Realm! The Objective-C API has been updated +and your code will break! + +### API breaking changes + +* All references to TightDB have been changed to Realm. +* All prefixes changed from `TDB` to `RLM`. +* `TDBTransaction` and `TDBSmartContext` have merged into `RLMRealm`. +* Write transactions now take an optional rollback parameter (rather than needing to return a boolean). +* `addColumnWithName:` and variant methods now return the index of the newly created column if successful, `NSNotFound` otherwise. + +### Enhancements + +* `createTableWithName:columns:` has been added to `RLMRealm`. +* Added keyed subscripting for RLMTable's first column if column is of type RLMPropertyTypeString. +* `setRow:atIndex:` has been added to `RLMTable`. +* `RLMRealm` constructors now have variants that take an writable initialization block +* New object interface - tables created/retrieved using `tableWithName:objectClass:` return custom objects + +### Bugfixes + +* None. + + +0.6.0 Release notes (2014-04-11) +============================================================= + +### API breaking changes + +* `contextWithPersistenceToFile:error:` renamed to `contextPersistedAtPath:error:` in `TDBContext` +* `readWithBlock:` renamed to `readUsingBlock:` in `TDBContext` +* `writeWithBlock:error:` renamed to `writeUsingBlock:error:` in `TDBContext` +* `readTable:withBlock:` renamed to `readTable:usingBlock:` in `TDBContext` +* `writeTable:withBlock:error:` renamed to `writeTable:usingBlock:error:` in `TDBContext` +* `findFirstRow` renamed to `indexOfFirstMatchingRow` on `TDBQuery`. +* `findFirstRowFromIndex:` renamed to `indexOfFirstMatchingRowFromIndex:` on `TDBQuery`. +* Return `NSNotFound` instead of -1 when appropriate. +* Renamed `castClass` to `castToTytpedTableClass` on `TDBTable`. +* `removeAllRows`, `removeRowAtIndex`, `removeLastRow`, `addRow` and `insertRow` methods + on table now return void instead of BOOL. + +### Enhancements +* A `TDBTable` can now be queried using `where:` and `where:orderBy:` taking + `NSPredicate` and `NSSortDescriptor` as arguments. +* Added `find:` method on `TDBTable` to find first row matching predicate. +* `contextWithDefaultPersistence` class method added to `TDBContext`. Will create a context persisted + to a file in app/documents folder. +* `renameColumnWithIndex:to:` has been added to `TDBTable`. +* `distinctValuesInColumnWithIndex` has been added to `TDBTable`. +* `dateIsBetween::`, `doubleIsBetween::`, `floatIsBetween::` and `intIsBetween::` + have been added to `TDBQuery`. +* Column names in Typed Tables can begin with non-capital letters too. The generated `addX` + selector can look odd. For example, a table with one column with name `age`, + appending a new row will look like `[table addage:7]`. +* Mixed typed values are better validated when rows are added, inserted, + or modified as object literals. +* `addRow`, `insertRow`, and row updates can be done using objects + derived from `NSObject`. +* `where` has been added to `TDBView`and `TDBViewProtocol`. +* Adding support for "smart" contexts (`TDBSmartContext`). + +### Bugfixes + +* Modifications of a `TDBView` and `TDBQuery` now throw an exception in a readtransaction. + + +0.5.0 Release notes (2014-04-02) +============================================================= + +The Objective-C API has been updated and your code will break! +Of notable changes a fast interface has been added. +This interface includes specific methods to get and set values into Tightdb. +To use these methods import ``. + +### API breaking changes + +* `getTableWithName:` renamed to `tableWithName:` in `TDBTransaction`. +* `addColumnWithName:andType:` renamed to `addColumnWithName:type:` in `TDBTable`. +* `columnTypeOfColumn:` renamed to `columnTypeOfColumnWithIndex` in `TDBTable`. +* `columnNameOfColumn:` renamed to `nameOfColumnWithIndex:` in `TDBTable`. +* `addColumnWithName:andType:` renamed to `addColumnWithName:type:` in `TDBDescriptor`. +* Fast getters and setters moved from `TDBRow.h` to `TDBRowFast.h`. + +### Enhancements + +* Added `minDateInColumnWithIndex` and `maxDateInColumnWithIndex` to `TDBQuery`. +* Transactions can now be started directly on named tables. +* You can create dynamic tables with initial schema. +* `TDBTable` and `TDBView` now have a shared protocol so they can easier be used interchangeably. + +### Bugfixes + +* Fixed bug in 64 bit iOS when inserting BOOL as NSNumber. + + +0.4.0 Release notes (2014-03-26) +============================================================= + +### API breaking changes + +* Typed interface Cursor has now been renamed to Row. +* TDBGroup has been renamed to TDBTransaction. +* Header files are renamed so names match class names. +* Underscore (_) removed from generated typed table classes. +* TDBBinary has been removed; use NSData instead. +* Underscope (_) removed from generated typed table classes. +* Constructor for TDBContext has been renamed to contextWithPersistenceToFile: +* Table findFirstRow and min/max/sum/avg operations has been hidden. +* Table.appendRow has been renamed to addRow. +* getOrCreateTable on Transaction has been removed. +* set*:inColumnWithIndex:atRowIndex: methods have been prefixed with TDB +* *:inColumnWithIndex:atRowIndex: methods have been prefixed with TDB +* addEmptyRow on table has been removed. Use [table addRow:nil] instead. +* TDBMixed removed. Use id and NSObject instead. +* insertEmptyRow has been removed from table. Use insertRow:nil atIndex:index instead. + +#### Enhancements + +* Added firstRow, lastRow selectors on view. +* firstRow and lastRow on table now return nil if table is empty. +* getTableWithName selector added on group. +* getting and creating table methods on group no longer take error argument. +* [TDBQuery parent] and [TDBQuery subtable:] selectors now return self. +* createTable method added on Transaction. Throws exception if table with same name already exists. +* Experimental support for pinning transactions on Context. +* TDBView now has support for object subscripting. + +### Bugfixes + +* None. + + +0.3.0 Release notes (2014-03-14) +============================================================= + +The Objective-C API has been updated and your code will break! + +### API breaking changes + +* Most selectors have been renamed in the binding! +* Prepend TDB-prefix on all classes and types. + +### Enhancements + +* Return types and parameters changed from size_t to NSUInteger. +* Adding setObject to TightdbTable (t[2] = @[@1, @"Hello"] is possible). +* Adding insertRow to TightdbTable. +* Extending appendRow to accept NSDictionary. + +### Bugfixes + +* None. + + +0.2.0 Release notes (2014-03-07) +============================================================= + +The Objective-C API has been updated and your code will break! + +### API breaking changes + +* addRow renamed to addEmptyRow + +### Enhancements + +* Adding a simple class for version numbering. +* Adding get-version and set-version targets to build.sh. +* tableview now supports sort on column with column type bool, date and int +* tableview has method for checking the column type of a specified column +* tableview has method for getting the number of columns +* Adding methods getVersion, getCoreVersion and isAtLeast. +* Adding appendRow to TightdbTable. +* Adding object subscripting. +* Adding method removeColumn on table. + +### Bugfixes + +* None. diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/Info.plist b/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/Info.plist new file mode 100644 index 000000000..1ee29a399 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/Info.plist @@ -0,0 +1,53 @@ + + + + + BuildMachineOSBuild + 14F27 + CFBundleDevelopmentRegion + English + CFBundleExecutable + Realm + CFBundleIdentifier + io.Realm.Realm + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + Realm + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.98.4 + CFBundleSignature + ???? + CFBundleSupportedPlatforms + + MacOSX + + CFBundleVersion + 0.98.4 + DTCompiler + com.apple.compilers.llvm.clang.1_0 + DTPlatformBuild + 7C1002 + DTPlatformVersion + GM + DTSDKBuild + 15C43 + DTSDKName + macosx10.11 + DTXcode + 0721 + DTXcodeBuild + 7C1002 + NSHumanReadableCopyright + Copyright © 2014 Realm. All rights reserved. + UIDeviceFamily + + 3 + 2 + 1 + 4 + + + diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/LICENSE b/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/LICENSE new file mode 100644 index 000000000..a19434667 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/LICENSE @@ -0,0 +1,269 @@ +TABLE OF CONTENTS + +1. Apache License version 2.0 +2. Realm Components +3. Export Compliance + +------------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +REALM COMPONENTS + +This software contains components with separate copyright and license terms. +Your use of these components is subject to the terms and conditions of the +following licenses. + +For the Realm Core component + + Realm Core Binary License + + Copyright (c) 2011-2014 Realm Inc All rights reserved + + Redistribution and use in binary form, with or without modification, is + permitted provided that the following conditions are met: + + 1. You agree not to attempt to decompile, disassemble, reverse engineer or + otherwise discover the source code from which the binary code was derived. + You may, however, access and obtain a separate license for most of the + source code from which this Software was created, at + http://realm.io/pricing/. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + +EXPORT COMPLIANCE + +You understand that the Software may contain cryptographic functions that may be +subject to export restrictions, and you represent and warrant that you are not +located in a country that is subject to United States export restriction or embargo, +including Cuba, Iran, North Korea, Sudan, Syria or the Crimea region, and that you +are not on the Department of Commerce list of Denied Persons, Unverified Parties, +or affiliated with a Restricted Entity. + +You agree to comply with all export, re-export and import restrictions and +regulations of the Department of Commerce or other agency or authority of the +United States or other applicable countries. You also agree not to transfer, or +authorize the transfer of, directly or indirectly, the Software to any prohibited +country, including Cuba, Iran, North Korea, Sudan, Syria or the Crimea region, +or to any person or organization on or affiliated with the Department of +Commerce lists of Denied Persons, Unverified Parties or Restricted Entities, or +otherwise in violation of any such restrictions or regulations. diff --git a/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/strip-frameworks.sh b/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/strip-frameworks.sh new file mode 100644 index 000000000..80814abba --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/A/Resources/strip-frameworks.sh @@ -0,0 +1,72 @@ +################################################################################ +# +# Copyright 2015 Realm Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# This script strips all non-valid architectures from dynamic libraries in +# the application's `Frameworks` directory. +# +# The following environment variables are required: +# +# BUILT_PRODUCTS_DIR +# FRAMEWORKS_FOLDER_PATH +# VALID_ARCHS +# EXPANDED_CODE_SIGN_IDENTITY + + +# Signs a framework with the provided identity +code_sign() { + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements $1" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1" +} + +# Set working directory to product’s embedded frameworks +cd "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +if [ "$ACTION" = "install" ]; then + echo "Copy .bcsymbolmap files to .xcarchive" + find . -name '*.bcsymbolmap' -type f -exec mv {} "${CONFIGURATION_BUILD_DIR}" \; +else + # Delete *.bcsymbolmap files from framework bundle unless archiving + find . -name '*.bcsymbolmap' -type f -exec rm -rf "{}" +\; +fi + +echo "Stripping frameworks" + +for file in $(find . -type f -perm +111); do + # Skip non-dynamic libraries + if ! [[ "$(file "$file")" == *"dynamically linked shared library"* ]]; then + continue + fi + # Get architectures for current file + archs="$(lipo -info "${file}" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$file" "$file" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" != "" ]]; then + echo "Stripped $file of architectures:$stripped" + if [ "${CODE_SIGNING_REQUIRED}" == "YES" ]; then + code_sign "${file}" + fi + fi +done diff --git a/Tests/Performance/Realm/Realm.framework/Versions/Current b/Tests/Performance/Realm/Realm.framework/Versions/Current new file mode 120000 index 000000000..8c7e5a667 --- /dev/null +++ b/Tests/Performance/Realm/Realm.framework/Versions/Current @@ -0,0 +1 @@ +A \ No newline at end of file diff --git a/Tests/Performance/Realm/RealmSwift.framework/Headers b/Tests/Performance/Realm/RealmSwift.framework/Headers new file mode 120000 index 000000000..a177d2a6b --- /dev/null +++ b/Tests/Performance/Realm/RealmSwift.framework/Headers @@ -0,0 +1 @@ +Versions/Current/Headers \ No newline at end of file diff --git a/Tests/Performance/Realm/RealmSwift.framework/Modules b/Tests/Performance/Realm/RealmSwift.framework/Modules new file mode 120000 index 000000000..5736f3186 --- /dev/null +++ b/Tests/Performance/Realm/RealmSwift.framework/Modules @@ -0,0 +1 @@ +Versions/Current/Modules \ No newline at end of file diff --git a/Tests/Performance/Realm/RealmSwift.framework/RealmSwift b/Tests/Performance/Realm/RealmSwift.framework/RealmSwift new file mode 120000 index 000000000..d2aa14626 --- /dev/null +++ b/Tests/Performance/Realm/RealmSwift.framework/RealmSwift @@ -0,0 +1 @@ +Versions/Current/RealmSwift \ No newline at end of file diff --git a/Tests/Performance/Realm/RealmSwift.framework/Resources b/Tests/Performance/Realm/RealmSwift.framework/Resources new file mode 120000 index 000000000..953ee36f3 --- /dev/null +++ b/Tests/Performance/Realm/RealmSwift.framework/Resources @@ -0,0 +1 @@ +Versions/Current/Resources \ No newline at end of file diff --git a/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Headers/RealmSwift-Swift.h b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Headers/RealmSwift-Swift.h new file mode 100644 index 000000000..5b04c264f --- /dev/null +++ b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Headers/RealmSwift-Swift.h @@ -0,0 +1,311 @@ +// Generated by Apple Swift version 2.1.1 (swiftlang-700.1.101.15 clang-700.1.81) +#pragma clang diagnostic push + +#if defined(__has_include) && __has_include() +# include +#endif + +#pragma clang diagnostic ignored "-Wauto-import" +#include +#include +#include +#include + +#if defined(__has_include) && __has_include() +# include +#elif !defined(__cplusplus) || __cplusplus < 201103L +typedef uint_least16_t char16_t; +typedef uint_least32_t char32_t; +#endif + +typedef struct _NSZone NSZone; + +#if !defined(SWIFT_PASTE) +# define SWIFT_PASTE_HELPER(x, y) x##y +# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) +#endif +#if !defined(SWIFT_METATYPE) +# define SWIFT_METATYPE(X) Class +#endif + +#if defined(__has_attribute) && __has_attribute(objc_runtime_name) +# define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) +#else +# define SWIFT_RUNTIME_NAME(X) +#endif +#if defined(__has_attribute) && __has_attribute(swift_name) +# define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) +#else +# define SWIFT_COMPILE_NAME(X) +#endif +#if !defined(SWIFT_CLASS_EXTRA) +# define SWIFT_CLASS_EXTRA +#endif +#if !defined(SWIFT_PROTOCOL_EXTRA) +# define SWIFT_PROTOCOL_EXTRA +#endif +#if !defined(SWIFT_ENUM_EXTRA) +# define SWIFT_ENUM_EXTRA +#endif +#if !defined(SWIFT_CLASS) +# if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted) +# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA +# define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA +# else +# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA +# define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA +# endif +#endif + +#if !defined(SWIFT_PROTOCOL) +# define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA +# define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA +#endif + +#if !defined(SWIFT_EXTENSION) +# define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) +#endif + +#if !defined(OBJC_DESIGNATED_INITIALIZER) +# if defined(__has_attribute) && __has_attribute(objc_designated_initializer) +# define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) +# else +# define OBJC_DESIGNATED_INITIALIZER +# endif +#endif +#if !defined(SWIFT_ENUM) +# define SWIFT_ENUM(_type, _name) enum _name : _type _name; enum SWIFT_ENUM_EXTRA _name : _type +#endif +typedef float swift_float2 __attribute__((__ext_vector_type__(2))); +typedef float swift_float3 __attribute__((__ext_vector_type__(3))); +typedef float swift_float4 __attribute__((__ext_vector_type__(4))); +typedef double swift_double2 __attribute__((__ext_vector_type__(2))); +typedef double swift_double3 __attribute__((__ext_vector_type__(3))); +typedef double swift_double4 __attribute__((__ext_vector_type__(4))); +typedef int swift_int2 __attribute__((__ext_vector_type__(2))); +typedef int swift_int3 __attribute__((__ext_vector_type__(3))); +typedef int swift_int4 __attribute__((__ext_vector_type__(4))); +#if defined(__has_feature) && __has_feature(modules) +@import Realm; +@import Realm.Private; +@import Foundation; +@import ObjectiveC; +#endif + +#pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" +#pragma clang diagnostic ignored "-Wduplicate-method-arg" +@class RLMRealm; +@class RLMObjectSchema; +@class RLMSchema; +@class RLMProperty; +@class RLMListBase; +@class RLMOptionalBase; + + +/// In Realm you define your model classes by subclassing Object and adding properties to be persisted. You then instantiate and use your custom subclasses instead of using the Object class directly. +/// +/// class Dog: Object { +/// dynamic var name: String = "" +/// dynamic var adopted: Bool = false +/// let siblings = List() +/// } +/// +/// +///

Supported property types

+///
  • String +/// , NSString +///
  • Int +///
  • Int8 +/// , Int16 +/// , Int32 +/// , Int64 +///
  • Float +///
  • Double +///
  • Bool +///
  • NSDate +///
  • NSData +///
  • RealmOptional +/// for optional numeric properties
  • Object +/// subclasses for to-one relationships
  • List +/// for to-many relationships
+/// String +/// , NSString +/// , NSDate +/// , NSData +/// and Object +/// subclass properties can be +/// optional. Int +/// , Int8 +/// , Int16, Int32 +/// , Int64 +/// , Float +/// , Double +/// , Bool +/// +/// and List +/// properties cannot. To store an optional number, instead use +/// RealmOptional +/// , RealmOptional +/// , RealmOptional +/// , or +/// RealmOptional +/// instead, which wraps an optional value of the generic type. +/// +/// All property types except for List +/// and RealmOptional +/// must be declared as +/// dynamic var +/// . List +/// and RealmOptional +/// properties must be declared as +/// non-dynamic let +/// properties. +/// +///

Querying

+/// You can gets Results +/// of an Object subclass via the objects(_:) +/// instance +/// method on Realm +/// . +/// +///

Relationships

+/// See our Cocoa guide for more details. +SWIFT_CLASS_NAMED("Object") +@interface RealmSwiftObject : RLMObjectBase + +/// Initialize a standalone (unpersisted) Object. Call add(_:) on a Realm to add standalone objects to a realm. +/// +///
  • see: Realm().add(_:)
+- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; + +/// Initialize a standalone (unpersisted) Object with values from an Array or Dictionary. Call add(_:) on a Realm to add standalone objects to a realm. +/// +/// \param value The value used to populate the object. This can be any key/value coding compliant +/// object, or a JSON object such as those returned from the methods in NSJSONSerialization +/// , +/// or an Array +/// with one object for each persisted property. An exception will be +/// thrown if any required properties are not present and no default is set. +- (nonnull instancetype)initWithValue:(id __nonnull)value OBJC_DESIGNATED_INITIALIZER; + +/// Indicates if an object can no longer be accessed. +/// +/// An object can no longer be accessed if the object has been deleted from the containing +/// realm +/// or if invalidate +/// is called on the containing realm +/// . +@property (nonatomic, readonly, getter=isInvalidated) BOOL invalidated; + +/// Returns a human-readable description of this object. +@property (nonatomic, readonly, copy) NSString * __nonnull description; + +/// Helper to return the class name for an Object subclass. +@property (nonatomic, readonly, copy) NSString * __nonnull className; + +/// WARNING: This is an internal helper method not intended for public use. :nodoc: ++ (Class __nonnull)objectUtilClass:(BOOL)isSwift; + +/// Override to designate a property as the primary key for an Object subclass. Only properties of type String and Int can be designated as the primary key. Primary key properties enforce uniqueness for each value whenever the property is set which incurs some overhead. Indexes are created automatically for primary key properties. +/// +/// \returns Name of the property designated as the primary key, or nil +/// if the model has no primary key. ++ (NSString * __nullable)primaryKey; + +/// Override to return an array of property names to ignore. These properties will not be persisted and are treated as transient. +/// +/// \returns Array +/// of property names to ignore. ++ (NSArray * __nonnull)ignoredProperties; + +/// Return an array of property names for properties which should be indexed. Only supported for string and int properties. +/// +/// \returns Array +/// of property names to index. ++ (NSArray * __nonnull)indexedProperties; +- (id __nullable)objectForKeyedSubscript:(NSString * __nonnull)key; +- (void)setObject:(id __nullable)value forKeyedSubscript:(NSString * __nonnull)key; + +/// Returns whether both objects are equal. +/// +/// Objects are considered equal when they are both from the same Realm and point to the same +/// underlying object in the database. +/// +/// \param object Object to compare for equality. +- (BOOL)isEqual:(id __nullable)object; + +/// WARNING: This is an internal initializer not intended for public use. :nodoc: +- (nonnull instancetype)initWithRealm:(RLMRealm * __nonnull)realm schema:(RLMObjectSchema * __nonnull)schema OBJC_DESIGNATED_INITIALIZER; + +/// WARNING: This is an internal initializer not intended for public use. :nodoc: +- (nonnull instancetype)initWithValue:(id __nonnull)value schema:(RLMSchema * __nonnull)schema OBJC_DESIGNATED_INITIALIZER; +- (RLMListBase * __nonnull)listForProperty:(RLMProperty * __nonnull)prop; +- (RLMOptionalBase * __nonnull)optionalForProperty:(RLMProperty * __nonnull)prop; +@end + + + +/// Object interface which allows untyped getters and setters for Objects. :nodoc: +SWIFT_CLASS("_TtC10RealmSwift13DynamicObject") +@interface DynamicObject : RealmSwiftObject +- (RLMListBase * __nonnull)listForProperty:(RLMProperty * __nonnull)prop; +- (RLMOptionalBase * __nonnull)optionalForProperty:(RLMProperty * __nonnull)prop; + +/// :nodoc: +- (id __nullable)valueForUndefinedKey:(NSString * __nonnull)key; + +/// :nodoc: +- (void)setValue:(id __nullable)value forUndefinedKey:(NSString * __nonnull)key; + +/// :nodoc: ++ (BOOL)shouldIncludeInDefaultSchema; +- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; +- (nonnull instancetype)initWithValue:(id __nonnull)value OBJC_DESIGNATED_INITIALIZER; +- (nonnull instancetype)initWithRealm:(RLMRealm * __nonnull)realm schema:(RLMObjectSchema * __nonnull)schema OBJC_DESIGNATED_INITIALIZER; +- (nonnull instancetype)initWithValue:(id __nonnull)value schema:(RLMSchema * __nonnull)schema OBJC_DESIGNATED_INITIALIZER; +@end + +@class RLMArray; + + +/// :nodoc: Internal class. Do not use directly. +SWIFT_CLASS("_TtC10RealmSwift8ListBase") +@interface ListBase : RLMListBase + +/// Returns a human-readable description of the objects contained in the List. +@property (nonatomic, readonly, copy) NSString * __nonnull description; + +/// Returns the number of objects in this List. +@property (nonatomic, readonly) NSInteger count; +- (null_unspecified instancetype)initWithArray:(RLMArray * __null_unspecified)array OBJC_DESIGNATED_INITIALIZER; +- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; +@end + + +@interface NSDate (SWIFT_EXTENSION(RealmSwift)) +@end + + + + +/// :nodoc: Internal class. Do not use directly. +SWIFT_CLASS_NAMED("ObjectUtil") +@interface RealmSwiftObjectUtil : NSObject +- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; +@end + +@class RLMResults; + + +/// :nodoc: Internal class. Do not use directly. +SWIFT_CLASS("_TtC10RealmSwift11ResultsBase") +@interface ResultsBase : NSObject +@property (nonatomic, readonly, strong) RLMResults * __nonnull rlmResults; + +/// Returns a human-readable description of the objects contained in these results. +@property (nonatomic, readonly, copy) NSString * __nonnull description; +- (nonnull instancetype)init:(RLMResults * __nonnull)rlmResults OBJC_DESIGNATED_INITIALIZER; +- (NSInteger)countByEnumeratingWithState:(NSFastEnumerationState * __null_unspecified)state objects:(id __nullable * __null_unspecified)buffer count:(NSInteger)len; +@end + +#pragma clang diagnostic pop diff --git a/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Modules/RealmSwift.swiftmodule/x86_64.swiftdoc b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Modules/RealmSwift.swiftmodule/x86_64.swiftdoc new file mode 100644 index 000000000..c56420ea7 Binary files /dev/null and b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Modules/RealmSwift.swiftmodule/x86_64.swiftdoc differ diff --git a/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Modules/RealmSwift.swiftmodule/x86_64.swiftmodule b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Modules/RealmSwift.swiftmodule/x86_64.swiftmodule new file mode 100644 index 000000000..df6aeadfa Binary files /dev/null and b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Modules/RealmSwift.swiftmodule/x86_64.swiftmodule differ diff --git a/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Modules/module.modulemap b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Modules/module.modulemap new file mode 100644 index 000000000..293772c62 --- /dev/null +++ b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Modules/module.modulemap @@ -0,0 +1,3 @@ +framework module RealmSwift { + header "RealmSwift-Swift.h" +} diff --git a/Tests/Performance/Realm/RealmSwift.framework/Versions/A/RealmSwift b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/RealmSwift new file mode 100755 index 000000000..8eaaf3fe4 Binary files /dev/null and b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/RealmSwift differ diff --git a/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Resources/Info.plist b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Resources/Info.plist new file mode 100644 index 000000000..8f6eef2d4 --- /dev/null +++ b/Tests/Performance/Realm/RealmSwift.framework/Versions/A/Resources/Info.plist @@ -0,0 +1,46 @@ + + + + + BuildMachineOSBuild + 14F27 + CFBundleDevelopmentRegion + English + CFBundleExecutable + RealmSwift + CFBundleIdentifier + io.realm.RealmSwit + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + RealmSwift + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.98.4 + CFBundleSignature + ???? + CFBundleSupportedPlatforms + + MacOSX + + CFBundleVersion + 0.98.4 + DTCompiler + com.apple.compilers.llvm.clang.1_0 + DTPlatformBuild + 7C1002 + DTPlatformVersion + GM + DTSDKBuild + 15C43 + DTSDKName + macosx10.11 + DTXcode + 0721 + DTXcodeBuild + 7C1002 + NSHumanReadableCopyright + Copyright © 2014 Realm. All rights reserved. + + diff --git a/Tests/Performance/Realm/RealmSwift.framework/Versions/Current b/Tests/Performance/Realm/RealmSwift.framework/Versions/Current new file mode 120000 index 000000000..8c7e5a667 --- /dev/null +++ b/Tests/Performance/Realm/RealmSwift.framework/Versions/Current @@ -0,0 +1 @@ +A \ No newline at end of file diff --git a/Tests/Private/DatabasePoolReleaseMemoryTests.swift b/Tests/Private/DatabasePoolReleaseMemoryTests.swift new file mode 100644 index 000000000..c7c2d8f9d --- /dev/null +++ b/Tests/Private/DatabasePoolReleaseMemoryTests.swift @@ -0,0 +1,315 @@ +import XCTest +@testable import GRDB + +class DatabasePoolReleaseMemoryTests: GRDBTestCase { + + func testDatabasePoolDeinitClosesAllConnections() { + assertNoError { + let countQueue = dispatch_queue_create(nil, nil) + var openConnectionCount = 0 + var totalOpenConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + dispatch_sync(countQueue) { + totalOpenConnectionCount += 1 + openConnectionCount += 1 + } + } + + dbConfiguration.SQLiteConnectionDidClose = { + dispatch_sync(countQueue) { + openConnectionCount -= 1 + } + } + + // write & read + + try dbPool.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for _ in 0..<2 { + try dbPool.execute("INSERT INTO items (id) VALUES (NULL)") + } + _ = Int.fetchOne(dbPool, "SELECT COUNT(*) FROM items") + + // Release + dbPool = nil + + // One reader, one writer + XCTAssertEqual(totalOpenConnectionCount, 2) + + // All connections are closed + XCTAssertEqual(openConnectionCount, 0) + } + } + + func testDatabasePoolReleaseMemoryClosesReaderConnections() { + assertNoError { + let countQueue = dispatch_queue_create(nil, nil) + var openConnectionCount = 0 + var totalOpenConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + dispatch_sync(countQueue) { + totalOpenConnectionCount += 1 + openConnectionCount += 1 + } + } + + dbConfiguration.SQLiteConnectionDidClose = { + dispatch_sync(countQueue) { + openConnectionCount -= 1 + } + } + + try dbPool.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for _ in 0..<2 { + try dbPool.execute("INSERT INTO items (id) VALUES (NULL)") + } + + // Block 1 Block 2 Block3 + // SELECT * FROM items + // step + // > + let s1 = dispatch_semaphore_create(0) + // SELECT * FROM items + // step + // > + let s2 = dispatch_semaphore_create(0) + // step step + // > + let s3 = dispatch_semaphore_create(0) + // end end releaseMemory + + let block1 = { () in + self.dbPool.read { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s3) + XCTAssertTrue(generator.next() == nil) + } + } + let block2 = { () in + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + self.dbPool.read { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s2) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() == nil) + } + } + let block3 = { () in + dispatch_semaphore_wait(s3, DISPATCH_TIME_FOREVER) + self.dbPool.releaseMemory() + } + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + dispatch_apply(3, queue) { index in + [block1, block2, block3][index]() + } + + // Two readers, one writer + XCTAssertEqual(totalOpenConnectionCount, 3) + + // Writer is still open + XCTAssertEqual(openConnectionCount, 1) + } + } + + func testBlocksRetainConnection() { + assertNoError { + let countQueue = dispatch_queue_create(nil, nil) + var openConnectionCount = 0 + var totalOpenConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + dispatch_sync(countQueue) { + totalOpenConnectionCount += 1 + openConnectionCount += 1 + } + } + + dbConfiguration.SQLiteConnectionDidClose = { + dispatch_sync(countQueue) { + openConnectionCount -= 1 + } + } + + try self.dbPool.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + + // Block 1 Block 2 + // read { + // > + let s1 = dispatch_semaphore_create(0) + // dbPool = nil + // > + let s2 = dispatch_semaphore_create(0) + // use database + // } + + let (block1, block2) = { () -> (() -> (), () -> ()) in + let block1 = { () in + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + self.dbPool = nil + dispatch_semaphore_signal(s2) + } + let dbPool = self.dbPool + let block2 = { [weak dbPool] () in + if let dbPool = dbPool { + dbPool.read { db in + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items"), 0) + } + } else { + XCTFail("expect non nil dbPool") + } + } + return (block1, block2) + }() + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + let blocks = [block1, block2] + dispatch_apply(blocks.count, queue) { index in + blocks[index]() + } + + // one writer, one reader + XCTAssertEqual(totalOpenConnectionCount, 2) + + // All connections are closed + XCTAssertEqual(openConnectionCount, 0) + } + } + + func testDatabaseGeneratorRetainConnection() { + assertNoError { + let countQueue = dispatch_queue_create(nil, nil) + var openConnectionCount = 0 + var totalOpenConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + dispatch_sync(countQueue) { + totalOpenConnectionCount += 1 + openConnectionCount += 1 + } + } + + dbConfiguration.SQLiteConnectionDidClose = { + dispatch_sync(countQueue) { + openConnectionCount -= 1 + } + } + + try self.dbPool.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try self.dbPool.execute("INSERT INTO items (id) VALUES (NULL)") + try self.dbPool.execute("INSERT INTO items (id) VALUES (NULL)") + + // Block 1 Block 2 + // write { + // SELECT + // step + // > + let s1 = dispatch_semaphore_create(0) + // dbPool = nil + // > + let s2 = dispatch_semaphore_create(0) + // step + // end + // } + + let (block1, block2) = { () -> (() -> (), () -> ()) in + let block1 = { () in + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + self.dbPool = nil + dispatch_semaphore_signal(s2) + } + let dbPool = self.dbPool + let block2 = { [weak dbPool] () in + weak var connection: Database? = nil + var generator: DatabaseGenerator? = nil + do { + if let dbPool = dbPool { + dbPool.write { db in + connection = db + generator = Int.fetch(db, "SELECT id FROM items").generate() + XCTAssertTrue(generator!.next() != nil) + dispatch_semaphore_signal(s1) + } + } else { + XCTFail("expect non nil dbPool") + } + } + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + do { + XCTAssertTrue(dbPool == nil) + XCTAssertTrue(generator!.next() != nil) + XCTAssertTrue(generator!.next() == nil) + generator = nil + XCTAssertTrue(connection == nil) + } + } + return (block1, block2) + }() + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + let blocks = [block1, block2] + dispatch_apply(blocks.count, queue) { index in + blocks[index]() + } + + // one writer + XCTAssertEqual(totalOpenConnectionCount, 1) + + // All connections are closed + XCTAssertEqual(openConnectionCount, 0) + } + } + + func testStatementDoNotRetainDatabaseConnection() { + assertNoError { + // Block 1 Block 2 + // create statement INSERT + // > + let s1 = dispatch_semaphore_create(0) + // dbPool = nil + // > + let s2 = dispatch_semaphore_create(0) + // dbPool is nil + + let (block1, block2) = { () -> (() -> (), () -> ()) in + let block1 = { () in + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + self.dbPool = nil + dispatch_semaphore_signal(s2) + } + let dbPool = self.dbPool + let block2 = { [weak dbPool] () in + var statement: UpdateStatement? = nil + do { + if let dbPool = dbPool { + do { + try dbPool.write { db in + statement = try db.updateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)") + dispatch_semaphore_signal(s1) + } + } catch { + XCTFail("error: \(error)") + } + } else { + XCTFail("expect non nil dbPool") + } + } + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertTrue(statement != nil) + XCTAssertTrue(dbPool == nil) + } + return (block1, block2) + }() + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + let blocks = [block1, block2] + dispatch_apply(blocks.count, queue) { index in + blocks[index]() + } + } + } +} diff --git a/Tests/Private/DatabasePoolSchemaCacheTests.swift b/Tests/Private/DatabasePoolSchemaCacheTests.swift new file mode 100644 index 000000000..a518a1c4f --- /dev/null +++ b/Tests/Private/DatabasePoolSchemaCacheTests.swift @@ -0,0 +1,68 @@ +import XCTest +@testable import GRDB + +class DatabasePoolSchemaCacheTests : GRDBTestCase { + + func testCache() { + assertNoError { + try dbPool.write { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + } + + dbPool.write { db in + // Assert that the writer cache is empty + XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + } + + dbPool.read { db in + // Assert that a reader cache is empty + XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + } + + try dbPool.read { db in + // Warm cache in a reader + let primaryKey = try db.primaryKey("items") + switch primaryKey { + case .RowID(let columnName): + XCTAssertEqual(columnName, "id") + default: + XCTFail() + } + + // Assert that reader cache is warmed + XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") != nil) + } + + dbPool.write { db in + // Assert that writer cache is warmed + XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") != nil) + } + + try dbPool.write { db in + // Empty cache after schema change + try db.execute("DROP TABLE items") + + // Assert that the writer cache is empty + XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + } + + dbPool.read { db in + // Assert that a reader cache is empty + XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + } + + try dbPool.read { db in + do { + // Assert that cache is used: we expect an error now that + // the cache is empty. + _ = try db.primaryKey("items") + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.code, 1) // SQLITE_ERROR + XCTAssertEqual(error.message!, "no such table: items") + XCTAssertEqual(error.description, "SQLite error 1: no such table: items") + } + } + } + } +} diff --git a/Tests/Private/DatabaseQueueReleaseMemoryTests.swift b/Tests/Private/DatabaseQueueReleaseMemoryTests.swift new file mode 100644 index 000000000..f0fe45fd8 --- /dev/null +++ b/Tests/Private/DatabaseQueueReleaseMemoryTests.swift @@ -0,0 +1,234 @@ +import XCTest +@testable import GRDB + +class DatabaseQueueuReleaseMemoryTests: GRDBTestCase { + + func testDatabaseQueueuDeinitClosesConnection() { + assertNoError { + let countQueue = dispatch_queue_create(nil, nil) + var openConnectionCount = 0 + var totalOpenConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + dispatch_sync(countQueue) { + totalOpenConnectionCount += 1 + openConnectionCount += 1 + } + } + + dbConfiguration.SQLiteConnectionDidClose = { + dispatch_sync(countQueue) { + openConnectionCount -= 1 + } + } + + // Open connection + try dbQueue.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + + // Release + dbQueue = nil + + // One reader, one writer + XCTAssertEqual(totalOpenConnectionCount, 1) + + // All connections are closed + XCTAssertEqual(openConnectionCount, 0) + } + } + + func testBlocksRetainConnection() { + assertNoError { + let countQueue = dispatch_queue_create(nil, nil) + var openConnectionCount = 0 + var totalOpenConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + dispatch_sync(countQueue) { + totalOpenConnectionCount += 1 + openConnectionCount += 1 + } + } + + dbConfiguration.SQLiteConnectionDidClose = { + dispatch_sync(countQueue) { + openConnectionCount -= 1 + } + } + + try self.dbQueue.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + + // Block 1 Block 2 + // inDatabase { + // > + let s1 = dispatch_semaphore_create(0) + // dbQueue = nil + // > + let s2 = dispatch_semaphore_create(0) + // use database + // } + + let (block1, block2) = { () -> (() -> (), () -> ()) in + let block1 = { () in + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + self.dbQueue = nil + dispatch_semaphore_signal(s2) + } + let dbQueue = self.dbQueue + let block2 = { [weak dbQueue] () in + if let dbQueue = dbQueue { + dbQueue.write { db in + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items"), 0) + } + } else { + XCTFail("expect non nil dbQueue") + } + } + return (block1, block2) + }() + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + let blocks = [block1, block2] + dispatch_apply(blocks.count, queue) { index in + blocks[index]() + } + + // one writer + XCTAssertEqual(totalOpenConnectionCount, 1) + + // All connections are closed + XCTAssertEqual(openConnectionCount, 0) + } + } + + func testDatabaseGeneratorRetainConnection() { + assertNoError { + let countQueue = dispatch_queue_create(nil, nil) + var openConnectionCount = 0 + var totalOpenConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + dispatch_sync(countQueue) { + totalOpenConnectionCount += 1 + openConnectionCount += 1 + } + } + + dbConfiguration.SQLiteConnectionDidClose = { + dispatch_sync(countQueue) { + openConnectionCount -= 1 + } + } + + try self.dbQueue.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try self.dbQueue.execute("INSERT INTO items (id) VALUES (NULL)") + try self.dbQueue.execute("INSERT INTO items (id) VALUES (NULL)") + + // Block 1 Block 2 + // write { + // SELECT + // step + // > + let s1 = dispatch_semaphore_create(0) + // dbQueue = nil + // > + let s2 = dispatch_semaphore_create(0) + // step + // end + // } + + let (block1, block2) = { () -> (() -> (), () -> ()) in + let block1 = { () in + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + self.dbQueue = nil + dispatch_semaphore_signal(s2) + } + let dbQueue = self.dbQueue + let block2 = { [weak dbQueue] () in + weak var connection: Database? = nil + var generator: DatabaseGenerator? = nil + do { + if let dbQueue = dbQueue { + dbQueue.write { db in + connection = db + generator = Int.fetch(db, "SELECT id FROM items").generate() + XCTAssertTrue(generator!.next() != nil) + dispatch_semaphore_signal(s1) + } + } else { + XCTFail("expect non nil dbQueue") + } + } + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + do { + XCTAssertTrue(dbQueue == nil) + XCTAssertTrue(generator!.next() != nil) + XCTAssertTrue(generator!.next() == nil) + generator = nil + XCTAssertTrue(connection == nil) + } + } + return (block1, block2) + }() + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + let blocks = [block1, block2] + dispatch_apply(blocks.count, queue) { index in + blocks[index]() + } + + // one writer + XCTAssertEqual(totalOpenConnectionCount, 1) + + // All connections are closed + XCTAssertEqual(openConnectionCount, 0) + } + } + + func testStatementDoNotRetainDatabaseConnection() { + assertNoError { + // Block 1 Block 2 + // create statement INSERT + // > + let s1 = dispatch_semaphore_create(0) + // dbQueue = nil + // > + let s2 = dispatch_semaphore_create(0) + // dbQueue is nil + + let (block1, block2) = { () -> (() -> (), () -> ()) in + let block1 = { () in + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + self.dbQueue = nil + dispatch_semaphore_signal(s2) + } + let dbQueue = self.dbQueue + let block2 = { [weak dbQueue] () in + var statement: UpdateStatement? = nil + do { + if let dbQueue = dbQueue { + do { + try dbQueue.write { db in + statement = try db.updateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)") + dispatch_semaphore_signal(s1) + } + } catch { + XCTFail("error: \(error)") + } + } else { + XCTFail("expect non nil dbQueue") + } + } + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertTrue(statement != nil) + XCTAssertTrue(dbQueue == nil) + } + return (block1, block2) + }() + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + let blocks = [block1, block2] + dispatch_apply(blocks.count, queue) { index in + blocks[index]() + } + } + } +} diff --git a/Tests/Private/DatabaseQueueSchemaCacheTests.swift b/Tests/Private/DatabaseQueueSchemaCacheTests.swift new file mode 100644 index 000000000..c6dacccff --- /dev/null +++ b/Tests/Private/DatabaseQueueSchemaCacheTests.swift @@ -0,0 +1,53 @@ +import XCTest +@testable import GRDB + +class DatabaseQueueSchemaCacheTests : GRDBTestCase { + + func testCache() { + assertNoError { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + } + + dbQueue.inDatabase { db in + // Assert that cache is empty + XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + } + + try dbQueue.inDatabase { db in + // Warm cache + let primaryKey = try db.primaryKey("items") + switch primaryKey { + case .RowID(let columnName): + XCTAssertEqual(columnName, "id") + default: + XCTFail() + } + + // Assert that cache is warmed + XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") != nil) + } + + try dbQueue.inDatabase { db in + // Empty cache after schema change + try db.execute("DROP TABLE items") + + // Assert that cache is empty + XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil) + } + + try dbQueue.inDatabase { db in + do { + // Assert that cache is used: we expect an error now that + // the cache is empty. + _ = try db.primaryKey("items") + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.code, 1) // SQLITE_ERROR + XCTAssertEqual(error.message!, "no such table: items") + XCTAssertEqual(error.description, "SQLite error 1: no such table: items") + } + } + } + } +} diff --git a/Tests/Private/SelectStatementSourceTablesTests.swift b/Tests/Private/SelectStatementSourceTablesTests.swift deleted file mode 100644 index 0b917ea40..000000000 --- a/Tests/Private/SelectStatementSourceTablesTests.swift +++ /dev/null @@ -1,18 +0,0 @@ -import XCTest -@testable import GRDB - -class SelectStatementSourceTablesTests : GRDBTestCase { - - func testSourceTables() { - assertNoError { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE foo (id INTEGER)") - try db.execute("CREATE TABLE bar (id INTEGER, fooId INTEGER)") - let statement = try db.selectStatement("SELECT * FROM Foo JOIN Bar ON fooId = foo.id") - XCTAssertTrue(statement.sourceTables.count == 2) - XCTAssertTrue(statement.sourceTables.contains("foo")) - XCTAssertTrue(statement.sourceTables.contains("bar")) - } - } - } -} diff --git a/Tests/Private/StatementInformationTests.swift b/Tests/Private/StatementInformationTests.swift new file mode 100644 index 000000000..8bb405268 --- /dev/null +++ b/Tests/Private/StatementInformationTests.swift @@ -0,0 +1,38 @@ +import XCTest +@testable import GRDB + +class StatementInformationTests : GRDBTestCase { + + func testSelectStatementSourceTables() { + assertNoError { + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE foo (id INTEGER)") + try db.execute("CREATE TABLE bar (id INTEGER, fooId INTEGER)") + let statement = try db.selectStatement("SELECT * FROM FOO JOIN BAR ON fooId = foo.id") + XCTAssertTrue(statement.sourceTables.count == 2) + XCTAssertTrue(statement.sourceTables.contains("foo")) + XCTAssertTrue(statement.sourceTables.contains("bar")) + } + } + } + + func testUpdateStatementInvalidatesDatabaseSchemaCache() { + assertNoError { + try dbQueue.inDatabase { db in + do { + let statement = try db.updateStatement("CREATE TABLE foo (id INTEGER)") + XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) + try statement.execute() + } + do { + let statement = try db.updateStatement("ALTER TABLE foo ADD COLUMN name TEXT") + XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) + } + do { + let statement = try db.updateStatement("DROP TABLE foo") + XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) + } + } + } + } +} diff --git a/Tests/Public/Core/Collation/CollationTests.swift b/Tests/Public/Core/Collation/CollationTests.swift index 4b8ab74c5..f32c46f9b 100644 --- a/Tests/Public/Core/Collation/CollationTests.swift +++ b/Tests/Public/Core/Collation/CollationTests.swift @@ -5,19 +5,20 @@ class CollationTests: GRDBTestCase { func testCollation() { assertNoError { - try dbQueue.inDatabase { db in - let collation = DatabaseCollation("localized_standard") { (string1, string2) in - let length1 = string1.utf8.count - let length2 = string2.utf8.count - if length1 == length2 { - return (string1 as NSString).compare(string2) - } else if length1 < length2 { - return .OrderedAscending - } else { - return .OrderedDescending - } + let collation = DatabaseCollation("localized_standard") { (string1, string2) in + let length1 = string1.utf8.count + let length2 = string2.utf8.count + if length1 == length2 { + return (string1 as NSString).compare(string2) + } else if length1 < length2 { + return .OrderedAscending + } else { + return .OrderedDescending } - db.addCollation(collation) + } + dbQueue.addCollation(collation) + + try dbQueue.inDatabase { db in try db.execute("CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT COLLATE LOCALIZED_STANDARD)") try db.execute("INSERT INTO strings VALUES (1, 'a')") try db.execute("INSERT INTO strings VALUES (2, 'aa')") diff --git a/Tests/Public/Core/DatabasePool/DatabasePoolCollationTests.swift b/Tests/Public/Core/DatabasePool/DatabasePoolCollationTests.swift new file mode 100644 index 000000000..660e06707 --- /dev/null +++ b/Tests/Public/Core/DatabasePool/DatabasePoolCollationTests.swift @@ -0,0 +1,34 @@ +import XCTest +import GRDB + +class DatabasePoolCollationTests: GRDBTestCase { + + func testCollationIsSharedBetweenWriterAndReaders() { + assertNoError { + let collation1 = DatabaseCollation("collation1") { (string1, string2) in + return (string1 == string2) ? .OrderedSame : ((string1 < string2) ? .OrderedAscending : .OrderedDescending) + } + dbPool.addCollation(collation1) + + try dbPool.write { db in + try db.execute("CREATE TABLE items (text TEXT COLLATE collation1)") + try db.execute("INSERT INTO items (text) VALUES ('a')") + try db.execute("INSERT INTO items (text) VALUES ('b')") + try db.execute("INSERT INTO items (text) VALUES ('c')") + } + dbPool.read { db in + XCTAssertEqual(String.fetchAll(db, "SELECT text FROM items ORDER BY text"), ["a", "b", "c"]) + XCTAssertEqual(String.fetchAll(db, "SELECT text FROM items ORDER BY text COLLATE collation1"), ["a", "b", "c"]) + } + + let collation2 = DatabaseCollation("collation2") { (string1, string2) in + return (string1 == string2) ? .OrderedSame : ((string1 < string2) ? .OrderedDescending : .OrderedAscending) + } + dbPool.addCollation(collation2) + + dbPool.read { db in + XCTAssertEqual(String.fetchAll(db, "SELECT text FROM items ORDER BY text COLLATE collation2"), ["c", "b", "a"]) + } + } + } +} diff --git a/Tests/Public/Core/DatabasePool/DatabasePoolConcurrencyTests.swift b/Tests/Public/Core/DatabasePool/DatabasePoolConcurrencyTests.swift new file mode 100644 index 000000000..c55588759 --- /dev/null +++ b/Tests/Public/Core/DatabasePool/DatabasePoolConcurrencyTests.swift @@ -0,0 +1,361 @@ +import XCTest +import GRDB + +class DatabasePoolConcurrencyTests: GRDBTestCase { + + func testUnwrappedReadWrite() { + assertNoError { + try dbPool.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try dbPool.execute("INSERT INTO items (id) VALUES (NULL)") + let id = Int.fetchOne(dbPool, "SELECT id FROM items")! + XCTAssertEqual(id, 1) + } + } + + func testWrappedReadWrite() { + assertNoError { + try dbPool.write { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + let id = dbPool.read { db in + Int.fetchOne(db, "SELECT id FROM items")! + } + XCTAssertEqual(id, 1) + } + } + + func testConcurrentRead() { + assertNoError { + try dbPool.write { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for _ in 0..<3 { + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + } + + // Block 1 Block 2 + // SELECT * FROM items SELECT * FROM items + // step step + // > + let s1 = dispatch_semaphore_create(0) + // step + // < + let s2 = dispatch_semaphore_create(0) + // step step + // step end + // end + + let block1 = { () in + self.dbPool.read { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() == nil) + } + } + let block2 = { () in + self.dbPool.read { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s2) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() == nil) + } + } + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + dispatch_apply(2, queue) { index in + [block1, block2][index]() + } + } + } + + func testReadMethodIsolationOfStatement() { + assertNoError { + try dbPool.write { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for _ in 0..<2 { + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + } + + // Block 1 Block 2 + // SELECT * FROM items + // step + // > + let s1 = dispatch_semaphore_create(0) + // DELETE * FROM items + // < + let s2 = dispatch_semaphore_create(0) + // step + // end + + let block1 = { () in + self.dbPool.read { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() == nil) + } + } + let block2 = { () in + do { + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + defer { dispatch_semaphore_signal(s2) } + try self.dbPool.write { db in + try db.execute("DELETE FROM items") + } + } catch { + XCTFail("error: \(error)") + } + } + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + dispatch_apply(2, queue) { index in + [block1, block2][index]() + } + } + } + + func testReadMethodIsolationOfStatementWithCheckpoint() { + assertNoError { + try dbPool.write { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for _ in 0..<2 { + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + } + + // Block 1 Block 2 + // SELECT * FROM items + // step + // > + let s1 = dispatch_semaphore_create(0) + // DELETE * FROM items + // Checkpoint + // < + let s2 = dispatch_semaphore_create(0) + // step + // end + + let block1 = { () in + self.dbPool.read { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() == nil) + } + } + let block2 = { () in + do { + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + defer { dispatch_semaphore_signal(s2) } + try self.dbPool.write { db in + try db.execute("DELETE FROM items") + } + try self.dbPool.checkpoint() + } catch { + XCTFail("error: \(error)") + } + } + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + dispatch_apply(2, queue) { index in + [block1, block2][index]() + } + } + } + + func testReadMethodIsolationOfBlock() { + assertNoError { + try dbPool.write { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + } + + // Block 1 Block 2 + // SELECT COUNT(*) FROM items + // > + let s1 = dispatch_semaphore_create(0) + // INSERT INTO items (id) VALUES (NULL) + // Checkpoint + // < + let s2 = dispatch_semaphore_create(0) + // SELECT COUNT(*) FROM items + + let block1 = { () in + self.dbPool.read { db in + XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) + } + } + let block2 = { () in + do { + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + defer { dispatch_semaphore_signal(s2) } + try self.dbPool.write { db in + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + try self.dbPool.checkpoint() + } catch { + XCTFail("error: \(error)") + } + } + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + dispatch_apply(2, queue) { index in + [block1, block2][index]() + } + } + } + + func testNonIsolatedReadMethodIsolationOfStatement() { + assertNoError { + try dbPool.write { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for _ in 0..<2 { + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + } + + // Block 1 Block 2 + // SELECT * FROM items + // step + // > + let s1 = dispatch_semaphore_create(0) + // DELETE * FROM items + // < + let s2 = dispatch_semaphore_create(0) + // step + // end + // SELECT COUNT(*) FROM items -> 0 + + let block1 = { () in + self.dbPool.nonIsolatedRead { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() == nil) + XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) + } + } + let block2 = { () in + do { + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + defer { dispatch_semaphore_signal(s2) } + try self.dbPool.write { db in + try db.execute("DELETE FROM items") + } + } catch { + XCTFail("error: \(error)") + } + } + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + dispatch_apply(2, queue) { index in + [block1, block2][index]() + } + } + } + + func testNonIsolatedReadMethodIsolationOfStatementWithCheckpoint() { + assertNoError { + try dbPool.write { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for _ in 0..<2 { + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + } + + // Block 1 Block 2 + // SELECT * FROM items + // step + // > + let s1 = dispatch_semaphore_create(0) + // DELETE * FROM items + // Checkpoint + // < + let s2 = dispatch_semaphore_create(0) + // step + // end + + let block1 = { () in + self.dbPool.nonIsolatedRead { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() == nil) + } + } + let block2 = { () in + do { + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + defer { dispatch_semaphore_signal(s2) } + try self.dbPool.write { db in + try db.execute("DELETE FROM items") + } + try self.dbPool.checkpoint() + } catch { + XCTFail("error: \(error)") + } + } + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + dispatch_apply(2, queue) { index in + [block1, block2][index]() + } + } + } + + func testNonIsolatedReadMethodIsolationOfBlock() { + assertNoError { + try dbPool.write { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + } + + // Block 1 Block 2 + // SELECT COUNT(*) FROM items + // > + let s1 = dispatch_semaphore_create(0) + // INSERT INTO items (id) VALUES (NULL) + // Checkpoint + // < + let s2 = dispatch_semaphore_create(0) + // SELECT COUNT(*) FROM items + + let block1 = { () in + self.dbPool.nonIsolatedRead { db in + XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) + } + } + let block2 = { () in + do { + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + defer { dispatch_semaphore_signal(s2) } + try self.dbPool.write { db in + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + try self.dbPool.checkpoint() + } catch { + XCTFail("error: \(error)") + } + } + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + dispatch_apply(2, queue) { index in + [block1, block2][index]() + } + } + } +} diff --git a/Tests/Public/Core/DatabasePool/DatabasePoolFileAttributesTests.swift b/Tests/Public/Core/DatabasePool/DatabasePoolFileAttributesTests.swift new file mode 100644 index 000000000..193d9f903 --- /dev/null +++ b/Tests/Public/Core/DatabasePool/DatabasePoolFileAttributesTests.swift @@ -0,0 +1,61 @@ +import XCTest +import GRDB + +class DatabasePoolFileAttributesTests: GRDBTestCase { + + func testDefaultFileAttributes() { + assertNoError { + let fm = NSFileManager.defaultManager() + + try dbPool.execute("CREATE TABLE foo (bar INTEGER)") + var attributes = try fm.attributesOfItemAtPath(dbPoolPath) + XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + attributes = try fm.attributesOfItemAtPath(dbPoolPath + "-wal") + XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + attributes = try fm.attributesOfItemAtPath(dbPoolPath + "-shm") + XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + } + } + + func testExplicitFileAttributesOnExistingFile() { + assertNoError { + let fm = NSFileManager.defaultManager() + + try dbPool.execute("CREATE TABLE foo (bar INTEGER)") + dbPool = nil + var attributes = try fm.attributesOfItemAtPath(dbPoolPath) + XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + attributes = try fm.attributesOfItemAtPath(dbPoolPath + "-wal") + XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + attributes = try fm.attributesOfItemAtPath(dbPoolPath + "-shm") + XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + + dbConfiguration.fileAttributes = [NSFileExtensionHidden: true] + _ = dbPool + attributes = try fm.attributesOfItemAtPath(dbPoolPath) + XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + attributes = try fm.attributesOfItemAtPath(dbPoolPath + "-wal") + XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + attributes = try fm.attributesOfItemAtPath(dbPoolPath + "-shm") + XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + } + } + + func testExplicitFileAttributesOnNewFile() { + assertNoError { + let fm = NSFileManager.defaultManager() + + dbConfiguration.fileAttributes = [NSFileExtensionHidden: true] + try dbPool.execute("CREATE TABLE foo (bar INTEGER)") + // TODO: this test is fragile: we have to wait until the database + // store has been notified of file creation. + NSThread.sleepForTimeInterval(0.1) + var attributes = try fm.attributesOfItemAtPath(dbPoolPath) + XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + attributes = try fm.attributesOfItemAtPath(dbPoolPath + "-wal") + XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + attributes = try fm.attributesOfItemAtPath(dbPoolPath + "-shm") + XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + } + } +} diff --git a/Tests/Public/Core/DatabasePool/DatabasePoolFunctionTests.swift b/Tests/Public/Core/DatabasePool/DatabasePoolFunctionTests.swift new file mode 100644 index 000000000..3149d01d1 --- /dev/null +++ b/Tests/Public/Core/DatabasePool/DatabasePoolFunctionTests.swift @@ -0,0 +1,32 @@ +import XCTest +import GRDB + +class DatabasePoolFunctionTests: GRDBTestCase { + + func testFunctionIsSharedBetweenWriterAndReaders() { + assertNoError { + let function1 = DatabaseFunction("function1", argumentCount: 1, pure: true) { (databaseValues: [DatabaseValue]) in + return databaseValues[0] + } + + dbPool.addFunction(function1) + + try dbPool.write { db in + try db.execute("CREATE TABLE items (text TEXT)") + try db.execute("INSERT INTO items (text) VALUES (function1('a'))") + } + dbPool.read { db in + XCTAssertEqual(String.fetchOne(db, "SELECT function1(text) FROM items")!, "a") + } + + let function2 = DatabaseFunction("function2", argumentCount: 1, pure: true) { (databaseValues: [DatabaseValue]) in + return "foo" + } + dbPool.addFunction(function2) + + dbPool.read { db in + XCTAssertTrue(String.fetchOne(db, "SELECT function2(text) FROM items") == "foo") + } + } + } +} diff --git a/Tests/Public/Core/DatabasePool/DatabasePoolReadOnlyTests.swift b/Tests/Public/Core/DatabasePool/DatabasePoolReadOnlyTests.swift new file mode 100644 index 000000000..273addd3c --- /dev/null +++ b/Tests/Public/Core/DatabasePool/DatabasePoolReadOnlyTests.swift @@ -0,0 +1,74 @@ +// +// DatabasePoolReadOnlyTests.swift +// GRDB +// +// Created by Gwendal Roué on 11/03/2016. +// Copyright © 2016 Gwendal Roué. All rights reserved. +// + +import XCTest +import GRDB + +class DatabasePoolReadOnlyTests: GRDBTestCase { + + func testConcurrentRead() { + assertNoError { + // Create a non-WAL database: + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for _ in 0..<3 { + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + } + dbQueue = nil + + // Open a read-only pool on that database: + var configuration = Configuration() + configuration.readonly = true + dbPool = try! DatabasePool(path: dbQueuePath, configuration: configuration) + + // Make sure the database is not in WAL mode + let mode = String.fetchOne(dbPool, "PRAGMA journal_mode")! + XCTAssertNotEqual(mode.lowercaseString, "wal") + + // Block 1 Block 2 + // SELECT * FROM items SELECT * FROM items + // step step + // > + let s1 = dispatch_semaphore_create(0) + // step + // < + let s2 = dispatch_semaphore_create(0) + // step step + // step end + // end + + let block1 = { () in + self.dbPool.read { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s1) + dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() == nil) + } + } + let block2 = { () in + self.dbPool.read { db in + let generator = Row.fetch(db, "SELECT * FROM items").generate() + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) + XCTAssertTrue(generator.next() != nil) + dispatch_semaphore_signal(s2) + XCTAssertTrue(generator.next() != nil) + XCTAssertTrue(generator.next() == nil) + } + } + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + dispatch_apply(2, queue) { index in + [block1, block2][index]() + } + } + } +} diff --git a/Tests/Public/Core/Concurrency/ConcurrencyTests.swift b/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift similarity index 94% rename from Tests/Public/Core/Concurrency/ConcurrencyTests.swift rename to Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift index bcce15195..08d3beddb 100644 --- a/Tests/Public/Core/Concurrency/ConcurrencyTests.swift +++ b/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift @@ -53,6 +53,32 @@ class ConcurrencyTests: XCTestCase { dbQueue2 = nil try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } + + func testUnwrappedReadWrite() { + do { + try dbQueue1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try dbQueue1.execute("INSERT INTO items (id) VALUES (NULL)") + let id = Int.fetchOne(dbQueue1, "SELECT id FROM items")! + XCTAssertEqual(id, 1) + } catch { + XCTFail("error: \(error)") + } + } + + func testWrappedReadWrite() { + do { + try dbQueue1.inDatabase { db in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + let id = dbQueue1.inDatabase { db in + Int.fetchOne(db, "SELECT id FROM items")! + } + XCTAssertEqual(id, 1) + } catch { + XCTFail("error: \(error)") + } + } func testDeferredTransactionConcurrency() { // Queue 1 Queue 2 @@ -391,7 +417,7 @@ class ConcurrencyTests: XCTestCase { do { dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER) try self.dbQueue2.inTransaction(.Deferred) { db in - let _ = Row.fetchAll(db, "SELECT * FROM stuffs") + _ = Row.fetchAll(db, "SELECT * FROM stuffs") dispatch_semaphore_signal(s2) usleep(100_000) // 0.1s return .Commit diff --git a/Tests/Public/Core/DatabaseQueue/DatabaseQueueFileAttributesTests.swift b/Tests/Public/Core/DatabaseQueue/DatabaseQueueFileAttributesTests.swift new file mode 100644 index 000000000..da2ce9150 --- /dev/null +++ b/Tests/Public/Core/DatabaseQueue/DatabaseQueueFileAttributesTests.swift @@ -0,0 +1,45 @@ +import XCTest +import GRDB + +class DatabaseQueueFileAttributesTests: GRDBTestCase { + + func testDefaultFileAttributes() { + assertNoError { + let fm = NSFileManager.defaultManager() + + _ = dbQueue + var attributes = try fm.attributesOfItemAtPath(dbQueuePath) + XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + } + } + + func testExplicitFileAttributesOnExistingFile() { + assertNoError { + let fm = NSFileManager.defaultManager() + + _ = dbQueue + dbQueue = nil + var attributes = try fm.attributesOfItemAtPath(dbQueuePath) + XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + + dbConfiguration.fileAttributes = [NSFileExtensionHidden: true] + _ = dbQueue + attributes = try fm.attributesOfItemAtPath(dbQueuePath) + XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + } + } + + func testExplicitFileAttributesOnNewFile() { + assertNoError { + let fm = NSFileManager.defaultManager() + + dbConfiguration.fileAttributes = [NSFileExtensionHidden: true] + _ = dbQueue + // TODO: this test is fragile: we have to wait until the database + // store has been notified of file creation. + NSThread.sleepForTimeInterval(0.1) + var attributes = try fm.attributesOfItemAtPath(dbQueuePath) + XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue) + } + } +} diff --git a/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift b/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift new file mode 100644 index 000000000..a4823125b --- /dev/null +++ b/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift @@ -0,0 +1,151 @@ +import XCTest +import GRDB + +// A type that adopts DatabaseValueConvertible but does not adopt StatementColumnConvertible +private struct WrappedInt: DatabaseValueConvertible { + let int: Int + init(int: Int) { + self.int = int + } + var databaseValue: DatabaseValue { + return int.databaseValue + } + static func fromDatabaseValue(databaseValue: DatabaseValue) -> WrappedInt? { + guard let int = Int.fromDatabaseValue(databaseValue) else { + return nil + } + return WrappedInt(int: int) + } +} + +// A type that adopts DatabaseValueConvertible and StatementColumnConvertible +private struct FastWrappedInt: DatabaseValueConvertible, StatementColumnConvertible { + let int: Int + let fast: Bool + + init(int: Int, fast: Bool) { + self.int = int + self.fast = fast + } + + init(sqliteStatement: SQLiteStatement, index: Int32) { + self.init(int: Int(sqlite3_column_int64(sqliteStatement, index)), fast: true) + } + + var databaseValue: DatabaseValue { + return int.databaseValue + } + + static func fromDatabaseValue(databaseValue: DatabaseValue) -> FastWrappedInt? { + guard let int = Int.fromDatabaseValue(databaseValue) else { + return nil + } + return FastWrappedInt(int: int, fast: false) + } +} + +private struct Item: RowConvertible, TableMapping { + let id: Int64 + + static func databaseTableName() -> String { + return "items" + } + + init(_ row: Row) { + self.id = row.value(named: "id") + } +} + +class DatabaseReaderTests : GRDBTestCase { + + func testDatabaseValueConvertibleFetch() { + XCTAssertEqual(WrappedInt.fetchOne(dbQueue, "SELECT 123")!.int, 123) + XCTAssertEqual(WrappedInt.fetchAll(dbQueue, "SELECT 123 UNION SELECT 321").map { $0.int }, [123, 321]) + + XCTAssertEqual(WrappedInt.fetchOne(dbPool, "SELECT 123")!.int, 123) + XCTAssertEqual(WrappedInt.fetchAll(dbPool, "SELECT 123 UNION SELECT 321").map { $0.int }, [123, 321]) + + dbQueue.inDatabase { db in + XCTAssertEqual(WrappedInt.fetchOne(db, "SELECT 123")!.int, 123) + XCTAssertEqual(WrappedInt.fetchAll(db, "SELECT 123 UNION SELECT 321").map { $0.int }, [123, 321]) + } + } + + func testStatementColumnConvertibleFetch() { + XCTAssertEqual(FastWrappedInt.fetchOne(dbQueue, "SELECT 123")!.int, 123) + XCTAssertEqual(FastWrappedInt.fetchAll(dbQueue, "SELECT 123 UNION SELECT 321").map { $0.int }, [123, 321]) + + XCTAssertEqual(FastWrappedInt.fetchOne(dbPool, "SELECT 123")!.int, 123) + XCTAssertEqual(FastWrappedInt.fetchAll(dbPool, "SELECT 123 UNION SELECT 321").map { $0.int }, [123, 321]) + + dbQueue.inDatabase { db in + XCTAssertEqual(FastWrappedInt.fetchOne(db, "SELECT 123")!.int, 123) + XCTAssertEqual(FastWrappedInt.fetchAll(db, "SELECT 123 UNION SELECT 321").map { $0.int }, [123, 321]) + } + } + + func testRowConvertibleFetch() { + XCTAssertEqual(Item.fetchOne(dbQueue, "SELECT 123 AS id")!.id, 123) + XCTAssertEqual(Item.fetchAll(dbQueue, "SELECT 123 AS id UNION SELECT 321").map { $0.id }, [123, 321]) + + XCTAssertEqual(Item.fetchOne(dbPool, "SELECT 123 AS id")!.id, 123) + XCTAssertEqual(Item.fetchAll(dbPool, "SELECT 123 AS id UNION SELECT 321").map { $0.id }, [123, 321]) + + dbQueue.inDatabase { db in + XCTAssertEqual(Item.fetchOne(db, "SELECT 123 AS id")!.id, 123) + XCTAssertEqual(Item.fetchAll(db, "SELECT 123 AS id UNION SELECT 321").map { $0.id }, [123, 321]) + } + } + + func testTableMappingFetch() { + let populateDatabase = { (db: Database) -> () in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db.execute("INSERT INTO items (id) VALUES (NULL)") + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + assertNoError { + try dbQueue.inDatabase { db in try populateDatabase(db) } + try dbPool.write { db in try populateDatabase(db) } + } + + XCTAssertEqual(Item.fetchOne(dbQueue, key: 1)!.id, 1) + XCTAssertEqual(Item.fetchAll(dbQueue, keys: [1, 2]).map { $0.id }, [1, 2]) + + XCTAssertEqual(Item.fetchOne(dbPool, key: 1)!.id, 1) + XCTAssertEqual(Item.fetchAll(dbPool, keys: [1, 2]).map { $0.id }, [1, 2]) + + dbQueue.inDatabase { db in + XCTAssertEqual(Item.fetchOne(db, key: 1)!.id, 1) + XCTAssertEqual(Item.fetchAll(db, keys: [1, 2]).map { $0.id }, [1, 2]) + } + } + + func testFetchRequestFetch() { + let populateDatabase = { (db: Database) -> () in + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db.execute("INSERT INTO items (id) VALUES (NULL)") + try db.execute("INSERT INTO items (id) VALUES (NULL)") + } + assertNoError { + try dbQueue.inDatabase { db in try populateDatabase(db) } + try dbPool.write { db in try populateDatabase(db) } + } + + let idCol = SQLColumn("id") + + XCTAssertEqual(Item.filter(idCol == 1).fetchOne(dbQueue)!.id, 1) + XCTAssertEqual(Item.all().fetchAll(dbQueue).map { $0.id }, [1, 2]) + XCTAssertEqual(Item.filter(idCol == 1).fetchCount(dbQueue), 1) + + XCTAssertEqual(Item.filter(idCol == 1).fetchOne(dbPool)!.id, 1) + XCTAssertEqual(Item.all().fetchAll(dbPool).map { $0.id }, [1, 2]) + XCTAssertEqual(Item.filter(idCol == 1).fetchCount(dbPool), 1) + + dbQueue.inDatabase { db in + XCTAssertEqual(Item.filter(idCol == 1).fetchOne(db)!.id, 1) + XCTAssertEqual(Item.all().fetchAll(db).map { $0.id }, [1, 2]) + XCTAssertEqual(Item.filter(idCol == 1).fetchCount(db), 1) + } + } + +} diff --git a/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleFetchTests.swift b/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleFetchTests.swift index 383fbf852..db93150be 100644 --- a/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleFetchTests.swift +++ b/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleFetchTests.swift @@ -2,7 +2,7 @@ import XCTest import GRDB // A type that adopts DatabaseValueConvertible but does not adopt StatementColumnConvertible -struct WrappedInt: DatabaseValueConvertible { +private struct WrappedInt: DatabaseValueConvertible { let int: Int init(int: Int) { self.int = int diff --git a/Tests/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift b/Tests/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift index b2519a9d9..53ff25538 100644 --- a/Tests/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift +++ b/Tests/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift @@ -25,10 +25,10 @@ enum Grape : String { case Riesling } -extension Color32 : DatabaseInt32Representable { } -extension Color64 : DatabaseInt64Representable { } -extension Color : DatabaseIntRepresentable { } -extension Grape : DatabaseStringRepresentable { } +extension Color32 : DatabaseValueConvertible { } +extension Color64 : DatabaseValueConvertible { } +extension Color : DatabaseValueConvertible { } +extension Grape : DatabaseValueConvertible { } class RawRepresentableTests: GRDBTestCase { diff --git a/Tests/Public/Core/Function/FunctionTests.swift b/Tests/Public/Core/Function/FunctionTests.swift index fb02d1e0a..7962a7fd5 100644 --- a/Tests/Public/Core/Function/FunctionTests.swift +++ b/Tests/Public/Core/Function/FunctionTests.swift @@ -19,11 +19,11 @@ class FunctionTests: GRDBTestCase { func testFunctionReturningNull() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in + return nil + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in - return nil - } - db.addFunction(fn) XCTAssertTrue(DatabaseValue.fetchOne(db, "SELECT f()") == nil) } } @@ -31,11 +31,11 @@ class FunctionTests: GRDBTestCase { func testFunctionReturningInt64() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in + return Int64(1) + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in - return Int64(1) - } - db.addFunction(fn) XCTAssertEqual(Int64.fetchOne(db, "SELECT f()")!, Int64(1)) } } @@ -43,11 +43,11 @@ class FunctionTests: GRDBTestCase { func testFunctionReturningDouble() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in + return 1e100 + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in - return 1e100 - } - db.addFunction(fn) XCTAssertEqual(Double.fetchOne(db, "SELECT f()")!, 1e100) } } @@ -55,11 +55,11 @@ class FunctionTests: GRDBTestCase { func testFunctionReturningString() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in + return "foo" + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in - return "foo" - } - db.addFunction(fn) XCTAssertEqual(String.fetchOne(db, "SELECT f()")!, "foo") } } @@ -67,11 +67,11 @@ class FunctionTests: GRDBTestCase { func testFunctionReturningData() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in + return "foo".dataUsingEncoding(NSUTF8StringEncoding) + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in - return "foo".dataUsingEncoding(NSUTF8StringEncoding) - } - db.addFunction(fn) XCTAssertEqual(NSData.fetchOne(db, "SELECT f()")!, "foo".dataUsingEncoding(NSUTF8StringEncoding)) } } @@ -79,11 +79,11 @@ class FunctionTests: GRDBTestCase { func testFunctionReturningCustomValueType() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in + return CustomValueType() + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in - return CustomValueType() - } - db.addFunction(fn) XCTAssertTrue(CustomValueType.fetchOne(db, "SELECT f()") != nil) } } @@ -93,11 +93,11 @@ class FunctionTests: GRDBTestCase { func testFunctionArgumentNil() { assertNoError { + let fn = DatabaseFunction("isNil", argumentCount: 1) { (databaseValues: [DatabaseValue]) in + return databaseValues[0].isNull + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("isNil", argumentCount: 1) { (databaseValues: [DatabaseValue]) in - return databaseValues[0].isNull - } - db.addFunction(fn) XCTAssertTrue(Bool.fetchOne(db, "SELECT isNil(NULL)")!) XCTAssertFalse(Bool.fetchOne(db, "SELECT isNil(1)")!) XCTAssertFalse(Bool.fetchOne(db, "SELECT isNil(1.1)")!) @@ -109,11 +109,11 @@ class FunctionTests: GRDBTestCase { func testFunctionArgumentInt64() { assertNoError { + let fn = DatabaseFunction("asInt64", argumentCount: 1) { (databaseValues: [DatabaseValue]) in + return databaseValues[0].value() as Int64? + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("asInt64", argumentCount: 1) { (databaseValues: [DatabaseValue]) in - return databaseValues[0].value() as Int64? - } - db.addFunction(fn) XCTAssertTrue(Int64.fetchOne(db, "SELECT asInt64(NULL)") == nil) XCTAssertEqual(Int64.fetchOne(db, "SELECT asInt64(1)")!, 1) XCTAssertEqual(Int64.fetchOne(db, "SELECT asInt64(1.1)")!, 1) @@ -125,11 +125,11 @@ class FunctionTests: GRDBTestCase { func testFunctionArgumentDouble() { assertNoError { + let fn = DatabaseFunction("asDouble", argumentCount: 1) { (databaseValues: [DatabaseValue]) in + return databaseValues[0].value() as Double? + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("asDouble", argumentCount: 1) { (databaseValues: [DatabaseValue]) in - return databaseValues[0].value() as Double? - } - db.addFunction(fn) XCTAssertTrue(Double.fetchOne(db, "SELECT asDouble(NULL)") == nil) XCTAssertEqual(Double.fetchOne(db, "SELECT asDouble(1)")!, 1.0) XCTAssertEqual(Double.fetchOne(db, "SELECT asDouble(1.1)")!, 1.1) @@ -141,11 +141,11 @@ class FunctionTests: GRDBTestCase { func testFunctionArgumentString() { assertNoError { + let fn = DatabaseFunction("asString", argumentCount: 1) { (databaseValues: [DatabaseValue]) in + return databaseValues[0].value() as String? + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("asString", argumentCount: 1) { (databaseValues: [DatabaseValue]) in - return databaseValues[0].value() as String? - } - db.addFunction(fn) XCTAssertTrue(String.fetchOne(db, "SELECT asString(NULL)") == nil) XCTAssertTrue(String.fetchOne(db, "SELECT asString(1)") == nil) XCTAssertTrue(String.fetchOne(db, "SELECT asString(1.1)") == nil) @@ -157,11 +157,11 @@ class FunctionTests: GRDBTestCase { func testFunctionArgumentBlob() { assertNoError { + let fn = DatabaseFunction("asData", argumentCount: 1) { (databaseValues: [DatabaseValue]) in + return databaseValues[0].value() as NSData? + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("asData", argumentCount: 1) { (databaseValues: [DatabaseValue]) in - return databaseValues[0].value() as NSData? - } - db.addFunction(fn) XCTAssertTrue(NSData.fetchOne(db, "SELECT asData(NULL)") == nil) XCTAssertTrue(NSData.fetchOne(db, "SELECT asData(1)") == nil) XCTAssertTrue(NSData.fetchOne(db, "SELECT asData(1.1)") == nil) @@ -173,11 +173,11 @@ class FunctionTests: GRDBTestCase { func testFunctionArgumentCustomValueType() { assertNoError { + let fn = DatabaseFunction("asCustomValueType", argumentCount: 1) { (databaseValues: [DatabaseValue]) in + return databaseValues[0].value() as CustomValueType? + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("asCustomValueType", argumentCount: 1) { (databaseValues: [DatabaseValue]) in - return databaseValues[0].value() as CustomValueType? - } - db.addFunction(fn) XCTAssertTrue(CustomValueType.fetchOne(db, "SELECT asCustomValueType(NULL)") == nil) XCTAssertTrue(CustomValueType.fetchOne(db, "SELECT asCustomValueType(1)") == nil) XCTAssertTrue(CustomValueType.fetchOne(db, "SELECT asCustomValueType(1.1)") == nil) @@ -192,11 +192,11 @@ class FunctionTests: GRDBTestCase { func testFunctionWithoutArgument() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in + return "foo" + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in - return "foo" - } - db.addFunction(fn) XCTAssertEqual(String.fetchOne(db, "SELECT f()")!, "foo") } } @@ -204,15 +204,15 @@ class FunctionTests: GRDBTestCase { func testFunctionOfOneArgument() { assertNoError { - dbQueue.inDatabase { db in - let fn = DatabaseFunction("unicodeUpper", argumentCount: 1) { (databaseValues: [DatabaseValue]) in - let dbv = databaseValues[0] - guard let string: String = dbv.value() else { - return nil - } - return string.uppercaseString + let fn = DatabaseFunction("unicodeUpper", argumentCount: 1) { (databaseValues: [DatabaseValue]) in + let dbv = databaseValues[0] + guard let string: String = dbv.value() else { + return nil } - db.addFunction(fn) + return string.uppercaseString + } + dbQueue.addFunction(fn) + dbQueue.inDatabase { db in XCTAssertEqual(String.fetchOne(db, "SELECT upper(?)", arguments: ["Roué"])!, "ROUé") XCTAssertEqual(String.fetchOne(db, "SELECT unicodeUpper(?)", arguments: ["Roué"])!, "ROUÉ") XCTAssertTrue(String.fetchOne(db, "SELECT unicodeUpper(NULL)") == nil) @@ -222,12 +222,12 @@ class FunctionTests: GRDBTestCase { func testFunctionOfTwoArguments() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 2) { databaseValues in + let ints: [Int] = databaseValues.flatMap { $0.value() } + return ints.reduce(0, combine: +) + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 2) { databaseValues in - let ints: [Int] = databaseValues.flatMap { $0.value() } - return ints.reduce(0, combine: +) - } - db.addFunction(fn) XCTAssertEqual(Int.fetchOne(db, "SELECT f(1, 2)")!, 3) } } @@ -235,11 +235,11 @@ class FunctionTests: GRDBTestCase { func testVariadicFunction() { assertNoError { + let fn = DatabaseFunction("f") { databaseValues in + return databaseValues.count + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let fn = DatabaseFunction("f") { databaseValues in - return databaseValues.count - } - db.addFunction(fn) XCTAssertEqual(Int.fetchOne(db, "SELECT f()")!, 0) XCTAssertEqual(Int.fetchOne(db, "SELECT f(1)")!, 1) XCTAssertEqual(Int.fetchOne(db, "SELECT f(1, 1)")!, 2) @@ -251,11 +251,11 @@ class FunctionTests: GRDBTestCase { func testFunctionThrowingDatabaseErrorWithMessage() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 1) { databaseValues in + throw DatabaseError(message: "custom error message") + } + dbQueue.addFunction(fn) try dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 1) { databaseValues in - throw DatabaseError(message: "custom error message") - } - db.addFunction(fn) do { try db.execute("CREATE TABLE items (value INT)") try db.execute("INSERT INTO items VALUES (f(1))") @@ -270,11 +270,11 @@ class FunctionTests: GRDBTestCase { func testFunctionThrowingDatabaseErrorWithCode() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 1) { databaseValues in + throw DatabaseError(code: 123) + } + dbQueue.addFunction(fn) try dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 1) { databaseValues in - throw DatabaseError(code: 123) - } - db.addFunction(fn) do { try db.execute("CREATE TABLE items (value INT)") try db.execute("INSERT INTO items VALUES (f(1))") @@ -289,11 +289,11 @@ class FunctionTests: GRDBTestCase { func testFunctionThrowingDatabaseErrorWithMessageAndCode() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 1) { databaseValues in + throw DatabaseError(code: 123, message: "custom error message") + } + dbQueue.addFunction(fn) try dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 1) { databaseValues in - throw DatabaseError(code: 123, message: "custom error message") - } - db.addFunction(fn) do { try db.execute("CREATE TABLE items (value INT)") try db.execute("INSERT INTO items VALUES (f(1))") @@ -308,11 +308,11 @@ class FunctionTests: GRDBTestCase { func testFunctionThrowingCustomError() { assertNoError { + let fn = DatabaseFunction("f", argumentCount: 1) { databaseValues in + throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSLocalizedDescriptionKey: "custom error message"]) + } + dbQueue.addFunction(fn) try dbQueue.inDatabase { db in - let fn = DatabaseFunction("f", argumentCount: 1) { databaseValues in - throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSLocalizedDescriptionKey: "custom error message"]) - } - db.addFunction(fn) do { try db.execute("CREATE TABLE items (value INT)") try db.execute("INSERT INTO items VALUES (f(1))") @@ -331,13 +331,14 @@ class FunctionTests: GRDBTestCase { func testFunctionsAreClosures() { assertNoError { + var x = 123 + let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in + return x + } + dbQueue.addFunction(fn) dbQueue.inDatabase { db in - let x = 123 - let fn = DatabaseFunction("f", argumentCount: 0) { databaseValues in - return x - } - db.addFunction(fn) - XCTAssertEqual(Int.fetchOne(db, "SELECT f()")!, 123) + x = 321 + XCTAssertEqual(Int.fetchOne(db, "SELECT f()")!, 321) } } } diff --git a/Tests/Public/Core/Persistable/MutablePersistableTests.swift b/Tests/Public/Core/Persistable/DatabaseMutablePersistableTests.swift similarity index 97% rename from Tests/Public/Core/Persistable/MutablePersistableTests.swift rename to Tests/Public/Core/Persistable/DatabaseMutablePersistableTests.swift index 9a3c829ef..aa099cf18 100644 --- a/Tests/Public/Core/Persistable/MutablePersistableTests.swift +++ b/Tests/Public/Core/Persistable/DatabaseMutablePersistableTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -struct MutablePersistablePerson : MutablePersistable { +private struct MutablePersistablePerson : MutablePersistable { var id: Int64? var name: String? @@ -18,7 +18,7 @@ struct MutablePersistablePerson : MutablePersistable { } } -struct MutablePersistableCountry : MutablePersistable { +private struct MutablePersistableCountry : MutablePersistable { var rowID: Int64? var isoCode: String var name: String @@ -36,7 +36,7 @@ struct MutablePersistableCountry : MutablePersistable { } } -struct MutablePersistableCustomizedCountry : MutablePersistable { +private struct MutablePersistableCustomizedCountry : MutablePersistable { var rowID: Int64? var isoCode: String var name: String @@ -58,33 +58,33 @@ struct MutablePersistableCustomizedCountry : MutablePersistable { self.rowID = rowID } - mutating func insert(db: Database) throws { + mutating func insert(db: DatabaseWriter) throws { willInsert() try performInsert(db) } - func update(db: Database) throws { + func update(db: DatabaseWriter) throws { willUpdate() try performUpdate(db) } - mutating func save(db: Database) throws { + mutating func save(db: DatabaseWriter) throws { willSave() try performSave(db) } - func delete(db: Database) throws { + func delete(db: DatabaseWriter) throws { willDelete() try performDelete(db) } - func exists(db: Database) -> Bool { + func exists(db: DatabaseReader) -> Bool { willExists() return performExists(db) } } -class MutablePersistableTests: GRDBTestCase { +class DatabaseMutablePersistableTests: GRDBTestCase { override func setUp() { super.setUp() diff --git a/Tests/Public/Core/Persistable/PersistableTests.swift b/Tests/Public/Core/Persistable/DatabasePersistableTests.swift similarity index 97% rename from Tests/Public/Core/Persistable/PersistableTests.swift rename to Tests/Public/Core/Persistable/DatabasePersistableTests.swift index 340988e27..037231940 100644 --- a/Tests/Public/Core/Persistable/PersistableTests.swift +++ b/Tests/Public/Core/Persistable/DatabasePersistableTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -struct PersistablePerson : Persistable { +private struct PersistablePerson : Persistable { var name: String? var age: Int? @@ -14,7 +14,7 @@ struct PersistablePerson : Persistable { } } -class PersistablePersonClass : Persistable { +private class PersistablePersonClass : Persistable { var id: Int64? var name: String? var age: Int? @@ -38,7 +38,7 @@ class PersistablePersonClass : Persistable { } } -struct PersistableCountry : Persistable { +private struct PersistableCountry : Persistable { var isoCode: String var name: String @@ -51,7 +51,7 @@ struct PersistableCountry : Persistable { } } -struct PersistableCustomizedCountry : Persistable { +private struct PersistableCustomizedCountry : Persistable { var isoCode: String var name: String let willInsert: Void -> Void @@ -68,33 +68,33 @@ struct PersistableCustomizedCountry : Persistable { return ["isoCode": isoCode, "name": name] } - func insert(db: Database) throws { + func insert(db: DatabaseWriter) throws { willInsert() try performInsert(db) } - func update(db: Database) throws { + func update(db: DatabaseWriter) throws { willUpdate() try performUpdate(db) } - func save(db: Database) throws { + func save(db: DatabaseWriter) throws { willSave() try performSave(db) } - func delete(db: Database) throws { + func delete(db: DatabaseWriter) throws { willDelete() try performDelete(db) } - func exists(db: Database) -> Bool { + func exists(db: DatabaseReader) -> Bool { willExists() return performExists(db) } } -class PersistableTests: GRDBTestCase { +class DatabasePersistableTests: GRDBTestCase { override func setUp() { super.setUp() diff --git a/Tests/Public/Core/Persistable/DatabasePoolMutablePersistableTests.swift b/Tests/Public/Core/Persistable/DatabasePoolMutablePersistableTests.swift new file mode 100644 index 000000000..53692e842 --- /dev/null +++ b/Tests/Public/Core/Persistable/DatabasePoolMutablePersistableTests.swift @@ -0,0 +1,537 @@ +import XCTest +import GRDB + +private struct MutablePersistablePerson : MutablePersistable { + var id: Int64? + var name: String? + + static func databaseTableName() -> String { + return "persons" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.id = rowID + } +} + +private struct MutablePersistableCountry : MutablePersistable { + var rowID: Int64? + var isoCode: String + var name: String + + static func databaseTableName() -> String { + return "countries" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.rowID = rowID + } +} + +private struct MutablePersistableCustomizedCountry : MutablePersistable { + var rowID: Int64? + var isoCode: String + var name: String + let willInsert: Void -> Void + let willUpdate: Void -> Void + let willSave: Void -> Void + let willDelete: Void -> Void + let willExists: Void -> Void + + static func databaseTableName() -> String { + return "countries" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.rowID = rowID + } + + mutating func insert(db: DatabaseWriter) throws { + willInsert() + try performInsert(db) + } + + func update(db: DatabaseWriter) throws { + willUpdate() + try performUpdate(db) + } + + mutating func save(db: DatabaseWriter) throws { + willSave() + try performSave(db) + } + + func delete(db: DatabaseWriter) throws { + willDelete() + try performDelete(db) + } + + func exists(db: DatabaseReader) -> Bool { + willExists() + return performExists(db) + } +} + +class DatabasePoolMutablePersistableTests: GRDBTestCase { + + override func setUp() { + super.setUp() + + var migrator = DatabaseMigrator() + migrator.registerMigration("setUp") { db in + try db.execute( + "CREATE TABLE persons (" + + "id INTEGER PRIMARY KEY, " + + "name NOT NULL " + + ")") + try db.execute( + "CREATE TABLE countries (" + + "isoCode TEXT NOT NULL PRIMARY KEY, " + + "name TEXT NOT NULL " + + ")") + } + + assertNoError { + try migrator.migrate(dbPool) + } + } + + + // MARK: - MutablePersistablePerson + + func testInsertMutablePersistablePerson() { + assertNoError { + var person = MutablePersistablePerson(id: nil, name: "Arthur") + try person.insert(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + + func testUpdateMutablePersistablePerson() { + assertNoError { + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.insert(dbPool) + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.insert(dbPool) + + person1.name = "Craig" + try person1.update(dbPool) + + let rows = Row.fetchAll(dbPool, "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 { + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.save(dbPool) + + var rows = Row.fetchAll(dbPool, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.save(dbPool) + + person1.name = "Craig" + try person1.save(dbPool) + + rows = Row.fetchAll(dbPool, "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") + + try person1.delete(dbPool) + try person1.save(dbPool) + + rows = Row.fetchAll(dbPool, "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 testDeleteMutablePersistablePerson() { + assertNoError { + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.insert(dbPool) + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.insert(dbPool) + + try person1.delete(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") + } + } + + func testExistsMutablePersistablePerson() { + assertNoError { + var person = MutablePersistablePerson(id: nil, name: "Arthur") + try person.insert(dbPool) + XCTAssertTrue(person.exists(dbPool)) + + try person.delete(dbPool) + + XCTAssertFalse(person.exists(dbPool)) + } + } + + + // MARK: - MutablePersistableCountry + + func testInsertMutablePersistableCountry() { + assertNoError { + var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country.insert(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + + func testUpdateMutablePersistableCountry() { + assertNoError { + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country1.insert(dbPool) + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + try country2.insert(dbPool) + + country1.name = "France Métropolitaine" + try country1.update(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + + func testSaveMutablePersistableCountry() { + assertNoError { + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country1.save(dbPool) + + var rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + try country2.save(dbPool) + + country1.name = "France Métropolitaine" + try country1.save(dbPool) + + rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(dbPool) + try country1.save(dbPool) + + rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "France Métropolitaine") + } + } + + func testDeleteMutablePersistableCountry() { + assertNoError { + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country1.insert(dbPool) + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + try country2.insert(dbPool) + + try country1.delete(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + + func testExistsMutablePersistableCountry() { + assertNoError { + var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country.insert(dbPool) + XCTAssertTrue(country.exists(dbPool)) + + try country.delete(dbPool) + + XCTAssertFalse(country.exists(dbPool)) + } + } + + + // MARK: - MutablePersistableCustomizedCountry + + func testInsertMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + + func testUpdateMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(dbPool) + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(dbPool) + + country1.name = "France Métropolitaine" + try country1.update(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + + func testSaveMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.save(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 1) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + var rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.save(dbPool) + + country1.name = "France Métropolitaine" + try country1.save(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 2) + XCTAssertEqual(saveCount, 2) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(dbPool) + try country1.save(dbPool) + + XCTAssertEqual(insertCount, 2) + XCTAssertEqual(updateCount, 3) + XCTAssertEqual(saveCount, 3) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "France Métropolitaine") + } + } + + func testDeleteMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(dbPool) + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(dbPool) + + try country1.delete(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbPool, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + + func testExistsMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(dbPool) + + XCTAssertTrue(country.exists(dbPool)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 1) + + try country.delete(dbPool) + + XCTAssertFalse(country.exists(dbPool)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 2) + } + } +} diff --git a/Tests/Public/Core/Persistable/DatabasePoolPersistableTests.swift b/Tests/Public/Core/Persistable/DatabasePoolPersistableTests.swift new file mode 100644 index 000000000..201f1882d --- /dev/null +++ b/Tests/Public/Core/Persistable/DatabasePoolPersistableTests.swift @@ -0,0 +1,565 @@ +import XCTest +import GRDB + +private struct PersistablePerson : Persistable { + var name: String? + var age: Int? + + static func databaseTableName() -> String { + return "persons" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["name": name, "age": age] + } +} + +private class PersistablePersonClass : Persistable { + var id: Int64? + var name: String? + var age: Int? + + init(id: Int64?, name: String?, age: Int?) { + self.id = id + self.name = name + self.age = age + } + + static func databaseTableName() -> String { + return "persons" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name, "age": age] + } + + func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.id = rowID + } +} + +private struct PersistableCountry : Persistable { + var isoCode: String + var name: String + + static func databaseTableName() -> String { + return "countries" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } +} + +private struct PersistableCustomizedCountry : Persistable { + var isoCode: String + var name: String + let willInsert: Void -> Void + let willUpdate: Void -> Void + let willSave: Void -> Void + let willDelete: Void -> Void + let willExists: Void -> Void + + static func databaseTableName() -> String { + return "countries" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + func insert(db: DatabaseWriter) throws { + willInsert() + try performInsert(db) + } + + func update(db: DatabaseWriter) throws { + willUpdate() + try performUpdate(db) + } + + func save(db: DatabaseWriter) throws { + willSave() + try performSave(db) + } + + func delete(db: DatabaseWriter) throws { + willDelete() + try performDelete(db) + } + + func exists(db: DatabaseReader) -> Bool { + willExists() + return performExists(db) + } +} + +class DatabasePoolPersistableTests: GRDBTestCase { + + override func setUp() { + super.setUp() + + var migrator = DatabaseMigrator() + migrator.registerMigration("setUp") { db in + try db.execute( + "CREATE TABLE persons (" + + "id INTEGER PRIMARY KEY, " + + "name TEXT NOT NULL, " + + "age INT NOT NULL " + + ")") + try db.execute( + "CREATE TABLE countries (" + + "isoCode TEXT NOT NULL PRIMARY KEY, " + + "name TEXT NOT NULL " + + ")") + } + + assertNoError { + try migrator.migrate(dbPool) + } + } + + + // MARK: - PersistablePerson + + func testInsertPersistablePerson() { + assertNoError { + let person = PersistablePerson(name: "Arthur", age: 42) + try person.insert(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + + func testSavePersistablePerson() { + assertNoError { + let person = PersistablePerson(name: "Arthur", age: 42) + try person.save(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + + + // MARK: - PersistablePersonClass + + func testInsertPersistablePersonClass() { + assertNoError { + let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person.insert(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + + func testUpdatePersistablePersonClass() { + assertNoError { + let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person1.insert(dbPool) + let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + try person2.insert(dbPool) + + person1.name = "Craig" + try person1.update(dbPool) + + let rows = Row.fetchAll(dbPool, "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 person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person1.save(dbPool) + + var rows = Row.fetchAll(dbPool, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + + let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + try person2.save(dbPool) + + person1.name = "Craig" + try person1.save(dbPool) + + rows = Row.fetchAll(dbPool, "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") + + try person1.delete(dbPool) + try person1.save(dbPool) + + rows = Row.fetchAll(dbPool, "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 testDeletePersistablePersonClass() { + assertNoError { + let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person1.insert(dbPool) + let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + try person2.insert(dbPool) + + try person1.delete(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") + } + } + + func testExistsPersistablePersonClass() { + assertNoError { + let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person.insert(dbPool) + XCTAssertTrue(person.exists(dbPool)) + + try person.delete(dbPool) + + XCTAssertFalse(person.exists(dbPool)) + } + } + + + // MARK: - PersistableCountry + + func testInsertPersistableCountry() { + assertNoError { + let country = PersistableCountry(isoCode: "FR", name: "France") + try country.insert(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + + func testUpdatePersistableCountry() { + assertNoError { + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.insert(dbPool) + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.insert(dbPool) + + country1.name = "France Métropolitaine" + try country1.update(dbPool) + + let rows = Row.fetchAll(dbPool, "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 { + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.save(dbPool) + + var rows = Row.fetchAll(dbPool, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.save(dbPool) + + country1.name = "France Métropolitaine" + try country1.save(dbPool) + + rows = Row.fetchAll(dbPool, "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") + + try country1.delete(dbPool) + try country1.save(dbPool) + + rows = Row.fetchAll(dbPool, "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 testDeletePersistableCountry() { + assertNoError { + let country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.insert(dbPool) + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.insert(dbPool) + + try country1.delete(dbPool) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + + func testExistsPersistableCountry() { + assertNoError { + let country = PersistableCountry(isoCode: "FR", name: "France") + try country.insert(dbPool) + XCTAssertTrue(country.exists(dbPool)) + + try country.delete(dbPool) + + XCTAssertFalse(country.exists(dbPool)) + } + } + + + // MARK: - PersistableCustomizedCountry + + func testInsertPersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + let country = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + + func testUpdatePersistableCustomizedCountry() { + assertNoError { + 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(dbPool) + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(dbPool) + + country1.name = "France Métropolitaine" + try country1.update(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbPool, "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 { + 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.save(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 1) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + var rows = Row.fetchAll(dbPool, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.save(dbPool) + + country1.name = "France Métropolitaine" + try country1.save(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 2) + XCTAssertEqual(saveCount, 2) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(dbPool, "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") + + try country1.delete(dbPool) + try country1.save(dbPool) + + XCTAssertEqual(insertCount, 2) + XCTAssertEqual(updateCount, 3) + XCTAssertEqual(saveCount, 3) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(dbPool, "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 testDeletePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + let country1 = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(dbPool) + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(dbPool) + + try country1.delete(dbPool) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbPool, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + + func testExistsPersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + let country = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(dbPool) + + XCTAssertTrue(country.exists(dbPool)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 1) + + try country.delete(dbPool) + + XCTAssertFalse(country.exists(dbPool)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 2) + } + } +} diff --git a/Tests/Public/Core/Persistable/DatabaseQueueMutablePersistableTests.swift b/Tests/Public/Core/Persistable/DatabaseQueueMutablePersistableTests.swift new file mode 100644 index 000000000..3388b3b4d --- /dev/null +++ b/Tests/Public/Core/Persistable/DatabaseQueueMutablePersistableTests.swift @@ -0,0 +1,537 @@ +import XCTest +import GRDB + +private struct MutablePersistablePerson : MutablePersistable { + var id: Int64? + var name: String? + + static func databaseTableName() -> String { + return "persons" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.id = rowID + } +} + +private struct MutablePersistableCountry : MutablePersistable { + var rowID: Int64? + var isoCode: String + var name: String + + static func databaseTableName() -> String { + return "countries" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.rowID = rowID + } +} + +private struct MutablePersistableCustomizedCountry : MutablePersistable { + var rowID: Int64? + var isoCode: String + var name: String + let willInsert: Void -> Void + let willUpdate: Void -> Void + let willSave: Void -> Void + let willDelete: Void -> Void + let willExists: Void -> Void + + static func databaseTableName() -> String { + return "countries" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.rowID = rowID + } + + mutating func insert(db: DatabaseWriter) throws { + willInsert() + try performInsert(db) + } + + func update(db: DatabaseWriter) throws { + willUpdate() + try performUpdate(db) + } + + mutating func save(db: DatabaseWriter) throws { + willSave() + try performSave(db) + } + + func delete(db: DatabaseWriter) throws { + willDelete() + try performDelete(db) + } + + func exists(db: DatabaseReader) -> Bool { + willExists() + return performExists(db) + } +} + +class DatabaseQueueMutablePersistableTests: GRDBTestCase { + + override func setUp() { + super.setUp() + + var migrator = DatabaseMigrator() + migrator.registerMigration("setUp") { db in + try db.execute( + "CREATE TABLE persons (" + + "id INTEGER PRIMARY KEY, " + + "name NOT NULL " + + ")") + try db.execute( + "CREATE TABLE countries (" + + "isoCode TEXT NOT NULL PRIMARY KEY, " + + "name TEXT NOT NULL " + + ")") + } + + assertNoError { + try migrator.migrate(dbQueue) + } + } + + + // MARK: - MutablePersistablePerson + + func testInsertMutablePersistablePerson() { + assertNoError { + var person = MutablePersistablePerson(id: nil, name: "Arthur") + try person.insert(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + + func testUpdateMutablePersistablePerson() { + assertNoError { + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.insert(dbQueue) + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.insert(dbQueue) + + person1.name = "Craig" + try person1.update(dbQueue) + + let rows = Row.fetchAll(dbQueue, "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 { + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.save(dbQueue) + + var rows = Row.fetchAll(dbQueue, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.save(dbQueue) + + person1.name = "Craig" + try person1.save(dbQueue) + + rows = Row.fetchAll(dbQueue, "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") + + try person1.delete(dbQueue) + try person1.save(dbQueue) + + rows = Row.fetchAll(dbQueue, "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 testDeleteMutablePersistablePerson() { + assertNoError { + var person1 = MutablePersistablePerson(id: nil, name: "Arthur") + try person1.insert(dbQueue) + var person2 = MutablePersistablePerson(id: nil, name: "Barbara") + try person2.insert(dbQueue) + + try person1.delete(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") + } + } + + func testExistsMutablePersistablePerson() { + assertNoError { + var person = MutablePersistablePerson(id: nil, name: "Arthur") + try person.insert(dbQueue) + XCTAssertTrue(person.exists(dbQueue)) + + try person.delete(dbQueue) + + XCTAssertFalse(person.exists(dbQueue)) + } + } + + + // MARK: - MutablePersistableCountry + + func testInsertMutablePersistableCountry() { + assertNoError { + var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country.insert(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + + func testUpdateMutablePersistableCountry() { + assertNoError { + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country1.insert(dbQueue) + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + try country2.insert(dbQueue) + + country1.name = "France Métropolitaine" + try country1.update(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + + func testSaveMutablePersistableCountry() { + assertNoError { + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country1.save(dbQueue) + + var rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + try country2.save(dbQueue) + + country1.name = "France Métropolitaine" + try country1.save(dbQueue) + + rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(dbQueue) + try country1.save(dbQueue) + + rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "France Métropolitaine") + } + } + + func testDeleteMutablePersistableCountry() { + assertNoError { + var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country1.insert(dbQueue) + var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + try country2.insert(dbQueue) + + try country1.delete(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + + func testExistsMutablePersistableCountry() { + assertNoError { + var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + try country.insert(dbQueue) + XCTAssertTrue(country.exists(dbQueue)) + + try country.delete(dbQueue) + + XCTAssertFalse(country.exists(dbQueue)) + } + } + + + // MARK: - MutablePersistableCustomizedCountry + + func testInsertMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + + func testUpdateMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(dbQueue) + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(dbQueue) + + country1.name = "France Métropolitaine" + try country1.update(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + } + } + + func testSaveMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.save(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 1) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + var rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.save(dbQueue) + + country1.name = "France Métropolitaine" + try country1.save(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 2) + XCTAssertEqual(saveCount, 2) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "France Métropolitaine") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "United States") + + try country1.delete(dbQueue) + try country1.save(dbQueue) + + XCTAssertEqual(insertCount, 2) + XCTAssertEqual(updateCount, 3) + XCTAssertEqual(saveCount, 3) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + XCTAssertEqual(rows[1].value(named: "rowID") as Int64, country1.rowID!) + XCTAssertEqual(rows[1].value(named: "name") as String, "France Métropolitaine") + } + } + + func testDeleteMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country1 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(dbQueue) + var country2 = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(dbQueue) + + try country1.delete(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbQueue, "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "rowID") as Int64, country2.rowID!) + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + + func testExistsMutablePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + var country = MutablePersistableCustomizedCountry( + rowID: nil, + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(dbQueue) + + XCTAssertTrue(country.exists(dbQueue)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 1) + + try country.delete(dbQueue) + + XCTAssertFalse(country.exists(dbQueue)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 2) + } + } +} diff --git a/Tests/Public/Core/Persistable/DatabaseQueuePersistableTests.swift b/Tests/Public/Core/Persistable/DatabaseQueuePersistableTests.swift new file mode 100644 index 000000000..b8e94141f --- /dev/null +++ b/Tests/Public/Core/Persistable/DatabaseQueuePersistableTests.swift @@ -0,0 +1,565 @@ +import XCTest +import GRDB + +private struct PersistablePerson : Persistable { + var name: String? + var age: Int? + + static func databaseTableName() -> String { + return "persons" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["name": name, "age": age] + } +} + +private class PersistablePersonClass : Persistable { + var id: Int64? + var name: String? + var age: Int? + + init(id: Int64?, name: String?, age: Int?) { + self.id = id + self.name = name + self.age = age + } + + static func databaseTableName() -> String { + return "persons" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["id": id, "name": name, "age": age] + } + + func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + self.id = rowID + } +} + +private struct PersistableCountry : Persistable { + var isoCode: String + var name: String + + static func databaseTableName() -> String { + return "countries" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } +} + +private struct PersistableCustomizedCountry : Persistable { + var isoCode: String + var name: String + let willInsert: Void -> Void + let willUpdate: Void -> Void + let willSave: Void -> Void + let willDelete: Void -> Void + let willExists: Void -> Void + + static func databaseTableName() -> String { + return "countries" + } + + var persistentDictionary: [String: DatabaseValueConvertible?] { + return ["isoCode": isoCode, "name": name] + } + + func insert(db: DatabaseWriter) throws { + willInsert() + try performInsert(db) + } + + func update(db: DatabaseWriter) throws { + willUpdate() + try performUpdate(db) + } + + func save(db: DatabaseWriter) throws { + willSave() + try performSave(db) + } + + func delete(db: DatabaseWriter) throws { + willDelete() + try performDelete(db) + } + + func exists(db: DatabaseReader) -> Bool { + willExists() + return performExists(db) + } +} + +class DatabaseQueuePersistableTests: GRDBTestCase { + + override func setUp() { + super.setUp() + + var migrator = DatabaseMigrator() + migrator.registerMigration("setUp") { db in + try db.execute( + "CREATE TABLE persons (" + + "id INTEGER PRIMARY KEY, " + + "name TEXT NOT NULL, " + + "age INT NOT NULL " + + ")") + try db.execute( + "CREATE TABLE countries (" + + "isoCode TEXT NOT NULL PRIMARY KEY, " + + "name TEXT NOT NULL " + + ")") + } + + assertNoError { + try migrator.migrate(dbQueue) + } + } + + + // MARK: - PersistablePerson + + func testInsertPersistablePerson() { + assertNoError { + let person = PersistablePerson(name: "Arthur", age: 42) + try person.insert(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + + func testSavePersistablePerson() { + assertNoError { + let person = PersistablePerson(name: "Arthur", age: 42) + try person.save(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + + + // MARK: - PersistablePersonClass + + func testInsertPersistablePersonClass() { + assertNoError { + let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person.insert(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + } + } + + func testUpdatePersistablePersonClass() { + assertNoError { + let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person1.insert(dbQueue) + let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + try person2.insert(dbQueue) + + person1.name = "Craig" + try person1.update(dbQueue) + + let rows = Row.fetchAll(dbQueue, "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 person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person1.save(dbQueue) + + var rows = Row.fetchAll(dbQueue, "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") + + let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + try person2.save(dbQueue) + + person1.name = "Craig" + try person1.save(dbQueue) + + rows = Row.fetchAll(dbQueue, "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") + + try person1.delete(dbQueue) + try person1.save(dbQueue) + + rows = Row.fetchAll(dbQueue, "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 testDeletePersistablePersonClass() { + assertNoError { + let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person1.insert(dbQueue) + let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + try person2.insert(dbQueue) + + try person1.delete(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "id") as Int64, person2.id!) + XCTAssertEqual(rows[0].value(named: "name") as String, "Barbara") + } + } + + func testExistsPersistablePersonClass() { + assertNoError { + let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + try person.insert(dbQueue) + XCTAssertTrue(person.exists(dbQueue)) + + try person.delete(dbQueue) + + XCTAssertFalse(person.exists(dbQueue)) + } + } + + + // MARK: - PersistableCountry + + func testInsertPersistableCountry() { + assertNoError { + let country = PersistableCountry(isoCode: "FR", name: "France") + try country.insert(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + + func testUpdatePersistableCountry() { + assertNoError { + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.insert(dbQueue) + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.insert(dbQueue) + + country1.name = "France Métropolitaine" + try country1.update(dbQueue) + + let rows = Row.fetchAll(dbQueue, "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 { + var country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.save(dbQueue) + + var rows = Row.fetchAll(dbQueue, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.save(dbQueue) + + country1.name = "France Métropolitaine" + try country1.save(dbQueue) + + rows = Row.fetchAll(dbQueue, "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") + + try country1.delete(dbQueue) + try country1.save(dbQueue) + + rows = Row.fetchAll(dbQueue, "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 testDeletePersistableCountry() { + assertNoError { + let country1 = PersistableCountry(isoCode: "FR", name: "France") + try country1.insert(dbQueue) + let country2 = PersistableCountry(isoCode: "US", name: "United States") + try country2.insert(dbQueue) + + try country1.delete(dbQueue) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + + func testExistsPersistableCountry() { + assertNoError { + let country = PersistableCountry(isoCode: "FR", name: "France") + try country.insert(dbQueue) + XCTAssertTrue(country.exists(dbQueue)) + + try country.delete(dbQueue) + + XCTAssertFalse(country.exists(dbQueue)) + } + } + + + // MARK: - PersistableCustomizedCountry + + func testInsertPersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + let country = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + } + } + + func testUpdatePersistableCustomizedCountry() { + assertNoError { + 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(dbQueue) + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(dbQueue) + + country1.name = "France Métropolitaine" + try country1.update(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbQueue, "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 { + 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.save(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 1) + XCTAssertEqual(saveCount, 1) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + var rows = Row.fetchAll(dbQueue, "SELECT * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "FR") + XCTAssertEqual(rows[0].value(named: "name") as String, "France") + + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.save(dbQueue) + + country1.name = "France Métropolitaine" + try country1.save(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 2) + XCTAssertEqual(saveCount, 2) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(dbQueue, "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") + + try country1.delete(dbQueue) + try country1.save(dbQueue) + + XCTAssertEqual(insertCount, 2) + XCTAssertEqual(updateCount, 3) + XCTAssertEqual(saveCount, 3) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + rows = Row.fetchAll(dbQueue, "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 testDeletePersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + let country1 = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country1.insert(dbQueue) + let country2 = PersistableCustomizedCountry( + isoCode: "US", + name: "United States", + willInsert: { }, + willUpdate: { }, + willSave: { }, + willDelete: { }, + willExists: { }) + try country2.insert(dbQueue) + + try country1.delete(dbQueue) + + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 0) + + let rows = Row.fetchAll(dbQueue, "SELECT * FROM countries ORDER BY isoCode") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].value(named: "isoCode") as String, "US") + XCTAssertEqual(rows[0].value(named: "name") as String, "United States") + } + } + + func testExistsPersistableCustomizedCountry() { + assertNoError { + var insertCount: Int = 0 + var updateCount: Int = 0 + var saveCount: Int = 0 + var deleteCount: Int = 0 + var existsCount: Int = 0 + let country = PersistableCustomizedCountry( + isoCode: "FR", + name: "France", + willInsert: { insertCount += 1 }, + willUpdate: { updateCount += 1 }, + willSave: { saveCount += 1 }, + willDelete: { deleteCount += 1 }, + willExists: { existsCount += 1 }) + try country.insert(dbQueue) + + XCTAssertTrue(country.exists(dbQueue)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 0) + XCTAssertEqual(existsCount, 1) + + try country.delete(dbQueue) + + XCTAssertFalse(country.exists(dbQueue)) + XCTAssertEqual(insertCount, 1) + XCTAssertEqual(updateCount, 0) + XCTAssertEqual(saveCount, 0) + XCTAssertEqual(deleteCount, 1) + XCTAssertEqual(existsCount, 2) + } + } +} diff --git a/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift b/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift index eaf2c2156..2b1feaf2a 100644 --- a/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift +++ b/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift @@ -2,7 +2,7 @@ import XCTest import GRDB // A type that adopts DatabaseValueConvertible and StatementColumnConvertible -struct FastWrappedInt: DatabaseValueConvertible, StatementColumnConvertible { +private struct FastWrappedInt: DatabaseValueConvertible, StatementColumnConvertible { let int: Int let fast: Bool diff --git a/Tests/Public/Core/Statement/SelectStatementTests.swift b/Tests/Public/Core/Statement/SelectStatementTests.swift index 5fe043fa7..62dce7242 100644 --- a/Tests/Public/Core/Statement/SelectStatementTests.swift +++ b/Tests/Public/Core/Statement/SelectStatementTests.swift @@ -156,7 +156,7 @@ class SelectStatementTests : GRDBTestCase { func testDatabaseErrorThrownBySelectStatementContainSQL() { dbQueue.inDatabase { db in do { - let _ = try db.selectStatement("SELECT * FROM blah") + _ = try db.selectStatement("SELECT * FROM blah") XCTFail() } catch let error as DatabaseError { XCTAssertEqual(error.code, 1) diff --git a/Tests/Public/Core/Statement/UpdateStatementTests.swift b/Tests/Public/Core/Statement/UpdateStatementTests.swift index f8046e5eb..637b174a6 100644 --- a/Tests/Public/Core/Statement/UpdateStatementTests.swift +++ b/Tests/Public/Core/Statement/UpdateStatementTests.swift @@ -258,7 +258,7 @@ class UpdateStatementTests : GRDBTestCase { func testDatabaseErrorThrownByUpdateStatementContainSQL() { dbQueue.inDatabase { db in do { - let _ = try db.updateStatement("UPDATE blah SET id = 12") + _ = try db.updateStatement("UPDATE blah SET id = 12") XCTFail() } catch let error as DatabaseError { XCTAssertEqual(error.code, 1) @@ -275,7 +275,7 @@ class UpdateStatementTests : GRDBTestCase { assertNoError { try dbQueue.inDatabase { db in do { - let _ = try db.updateStatement("UPDATE persons SET age = 1; UPDATE persons SET age = 2;") + _ = try db.updateStatement("UPDATE persons SET age = 1; UPDATE persons SET age = 2;") XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.code, 21) // SQLITE_MISUSE @@ -291,7 +291,7 @@ class UpdateStatementTests : GRDBTestCase { assertNoError { try dbQueue.inDatabase { db in do { - let _ = try db.updateStatement("UPDATE persons SET age = 1;x") + _ = try db.updateStatement("UPDATE persons SET age = 1;x") XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.code, 21) // SQLITE_MISUSE @@ -302,4 +302,26 @@ class UpdateStatementTests : GRDBTestCase { } } } + + func testReadOnlyDatabaseCanNotBeModified() { + assertNoError { + var configuration = Configuration() + configuration.readonly = true + dbQueue = try DatabaseQueue(path: dbQueuePath, configuration: configuration) + let statement = try dbQueue.inDatabase { db in + try db.updateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)") + } + do { + try dbQueue.inDatabase { db in + try statement.execute() + } + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.code, 8) // SQLITE_READONLY + XCTAssertEqual(error.message!, "attempt to write a readonly database") + XCTAssertEqual(error.sql!, "CREATE TABLE items (id INTEGER PRIMARY KEY)") + XCTAssertEqual(error.description, "SQLite error 8 with statement `CREATE TABLE items (id INTEGER PRIMARY KEY)`: attempt to write a readonly database") + } + } + } } diff --git a/Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift b/Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift index 02b3b184a..9db74f1e5 100644 --- a/Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift +++ b/Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift @@ -145,8 +145,8 @@ class TransactionObserverTests: GRDBTestCase { observer = TransactionObserver() assertNoError { + dbQueue.addTransactionObserver(self.observer) try dbQueue.inDatabase { db in - db.addTransactionObserver(self.observer) try Artist.setupInDatabase(db) try Artwork.setupInDatabase(db) } @@ -631,13 +631,13 @@ class TransactionObserverTests: GRDBTestCase { func testInsertEventIsNotifiedToAllObservers() { assertNoError { + let observer1 = TransactionObserver() + let observer2 = TransactionObserver() + + dbQueue.addTransactionObserver(observer1) + dbQueue.addTransactionObserver(observer2) + try dbQueue.inDatabase { db in - let observer1 = TransactionObserver() - let observer2 = TransactionObserver() - - db.addTransactionObserver(observer1) - db.addTransactionObserver(observer2) - let artist = Artist(name: "Gerhard Richter") // @@ -667,12 +667,13 @@ class TransactionObserverTests: GRDBTestCase { let observer2 = TransactionObserver() let observer3 = TransactionObserver() observer2.commitError = NSError(domain: "foo", code: 0, userInfo: nil) + + dbQueue.addTransactionObserver(observer1) + dbQueue.addTransactionObserver(observer2) + dbQueue.addTransactionObserver(observer3) + do { try dbQueue.inTransaction { db in - db.addTransactionObserver(observer1) - db.addTransactionObserver(observer2) - db.addTransactionObserver(observer3) - do { try Artist(name: "Gerhard Richter").save(db) } catch { @@ -709,9 +710,7 @@ class TransactionObserverTests: GRDBTestCase { do { let observer = TransactionObserver(deinitBlock: { observerReleased = true }) withExtendedLifetime(observer) { - dbQueue.inDatabase { db in - db.addTransactionObserver(observer) - } + dbQueue.addTransactionObserver(observer) XCTAssertFalse(observerReleased) } } diff --git a/Tests/Public/CrashTests.swift b/Tests/Public/CrashTests.swift deleted file mode 100644 index b3eb4d42d..000000000 --- a/Tests/Public/CrashTests.swift +++ /dev/null @@ -1,713 +0,0 @@ -// All tests in this file must crash. -// -// To run those tests, run the GRDBOSXCrashTests target, and verify that each -// test crashes with the expected error message. - -import XCTest -import GRDB - - -// MARK: - Support - -class RecordWithoutDatabaseTableName: Record { } - -class RecordWithInexistingDatabaseTable: Record { - override static func databaseTableName() -> String { - return "foo" - } -} - -class RecordWithEmptyPersistentDictionary : Record { - override static func databaseTableName() -> String { - return "records" - } -} - -class RecordWithNilPrimaryKey : Record { - override static func databaseTableName() -> String { - return "records" - } - - override var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["id": nil] - } -} - -class RecordForTableWithoutPrimaryKey : Record { - override static func databaseTableName() -> String { - return "records" - } - - override var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["name": "foo"] - } -} - -class RecordForTableWithMultipleColumnsPrimaryKey : Record { - override static func databaseTableName() -> String { - return "records" - } - - override var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["name": "foo"] - } -} - -class RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary : Record { - override static func databaseTableName() -> String { - return "records" - } - - override var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["name": "foo"] - } -} - -// A type that adopts DatabaseValueConvertible but does not adopt StatementColumnConvertible -struct IntConvertible: DatabaseValueConvertible { - let int: Int - init(int: Int) { - self.int = int - } - var databaseValue: DatabaseValue { - return int.databaseValue - } - static func fromDatabaseValue(databaseValue: DatabaseValue) -> IntConvertible? { - guard let int = Int.fromDatabaseValue(databaseValue) else { - return nil - } - return IntConvertible(int: int) - } -} - -// MARK: - CrashTests - -class CrashTests: GRDBTestCase { - - // This method does not actually catch any crash. - // But it expresses an intent :-) - func assertCrash(message: String, @noescape block: () throws -> ()) { - do { - try block() - XCTFail("Crash expected: \(message)") - } catch { - XCTFail("Unexpected error: \(error)") - } - } - - - // ========================================================================= - // MARK: - Migrations - - func testMigrationNamesMustBeUnique() { - assertCrash("already registered migration: \"foo\"") { - var migrator = DatabaseMigrator() - migrator.registerMigration("foo") { db in } - migrator.registerMigration("foo") { db in } - } - } - - - // ========================================================================= - // MARK: - Queue - - func testInDatabaseIsNotReentrant() { - assertCrash("DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.") { - dbQueue.inDatabase { db in - self.dbQueue.inDatabase { db in - } - } - } - } - - func testInTransactionInsideInDatabaseIsNotReentrant() { - assertCrash("DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.") { - try dbQueue.inDatabase { db in - try self.dbQueue.inTransaction { db in - return .Commit - } - } - } - } - - func testInTransactionIsNotReentrant() { - assertCrash("DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.") { - try dbQueue.inTransaction { db in - try self.dbQueue.inTransaction { db in - return .Commit - } - return .Commit - } - } - } - - func testRowSequenceCanNotBeGeneratedOutsideOfDatabaseQueue() { - assertCrash("Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") { - var rows: DatabaseSequence? - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE persons (name TEXT)") - rows = Row.fetch(db, "SELECT * FROM persons") - } - let _ = rows!.generate() - } - } - - func testRowSequenceCanNotBeIteratedOutsideOfDatabaseQueue() { - assertCrash("Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") { - var generator: DatabaseGenerator? - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE persons (name TEXT)") - generator = Row.fetch(db, "SELECT * FROM persons").generate() - } - generator!.next() - } - } - - - // ========================================================================= - // MARK: - Statements - - func testInvalidStatementArguments() { - assertCrash("SQLite error 1 with statement `INSERT INTO persons (name, age) VALUES (:name, :age)`: missing statement argument(s): age") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE persons (name TEXT, age INT)") - try! db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur"]) - } - } - - assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', ?);`: wrong number of statement arguments: 0") { - try dbQueue.inTransaction { db in - do { - try db.execute("CREATE TABLE persons (name TEXT, age INT)") - try db.execute( - "INSERT INTO persons (name, age) VALUES ('Arthur', ?);" + - "INSERT INTO persons (name, age) VALUES ('Arthur', ?);") - XCTFail("Expected Error") - } catch { - XCTAssertTrue(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age").isEmpty) - } - - return .Rollback - } - } - - assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', ?);`: wrong number of statement arguments: 0") { - try dbQueue.inTransaction { db in - do { - try db.execute("CREATE TABLE persons (name TEXT, age INT)") - try db.execute( - "INSERT INTO persons (name, age) VALUES ('Arthur', ?);" + - "INSERT INTO persons (name, age) VALUES ('Arthur', ?);", - arguments: [41]) - XCTFail("Expected Error") - } catch { - // Partial fail - XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [41]) - } - - return .Rollback - } - } - - assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', :age1);`: missing statement argument(s): age1") { - try dbQueue.inTransaction { db in - do { - try db.execute("CREATE TABLE persons (name TEXT, age INT)") - try db.execute( - "INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" + - "INSERT INTO persons (name, age) VALUES ('Arthur', :age2);") - XCTFail("Expected Error") - } catch { - XCTAssertTrue(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age").isEmpty) - } - return .Rollback - } - } - - assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', :age2);`: missing statement argument(s): age2") { - try dbQueue.inTransaction { db in - do { - try db.execute("CREATE TABLE persons (name TEXT, age INT)") - try db.execute( - "INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" + - "INSERT INTO persons (name, age) VALUES ('Arthur', :age2);", - arguments: ["age1": 41]) - XCTFail("Expected Error") - } catch { - // Partial fail - XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [41]) - } - return .Rollback - } - } - - assertCrash("wrong number of statement arguments: 3") { - try dbQueue.inTransaction { db in - do { - try db.execute("CREATE TABLE persons (name TEXT, age INT)") - try db.execute( - "INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" + - "INSERT INTO persons (name, age) VALUES ('Arthur', :age2);", - arguments: [41, 32, 17]) - XCTFail("Expected Error") - } catch { - // Partial fail - XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41]) - } - return .Rollback - } - } - - assertCrash("wrong number of statement arguments: 3") { - try dbQueue.inTransaction { db in - do { - try db.execute("CREATE TABLE persons (name TEXT, age INT)") - try db.execute( - "INSERT INTO persons (name, age) VALUES ('Arthur', ?);" + - "INSERT INTO persons (name, age) VALUES ('Arthur', ?);", - arguments: [41, 32, 17]) - XCTFail("Expected Error") - } catch { - // Partial fail - XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41]) - } - return .Rollback - } - } - } - - - // ========================================================================= - // MARK: - RecordWithoutDatabaseTableName - - func testRecordWithoutDatabaseTableNameCanNotBeFetchedByID() { - assertCrash("subclass must override") { - dbQueue.inDatabase { db in - RecordWithoutDatabaseTableName.fetchOne(db, key: 1) - } - } - } - - func testRecordWithoutDatabaseTableNameCanNotBeFetchedByKey() { - assertCrash("subclass must override") { - dbQueue.inDatabase { db in - RecordWithoutDatabaseTableName.fetchOne(db, key: ["foo": "bar"]) - } - } - } - - func testRecordWithoutDatabaseTableNameCanNotBeInserted() { - assertCrash("subclass must override") { - try dbQueue.inDatabase { db in - try RecordWithoutDatabaseTableName().insert(db) - } - } - } - - func testRecordWithoutDatabaseTableNameCanNotBeUpdated() { - assertCrash("subclass must override") { - try dbQueue.inDatabase { db in - try RecordWithoutDatabaseTableName().update(db) - } - } - } - - func testRecordWithoutDatabaseTableNameCanNotBeSaved() { - assertCrash("subclass must override") { - try dbQueue.inDatabase { db in - try RecordWithoutDatabaseTableName().save(db) - } - } - } - - func testRecordWithoutDatabaseTableNameCanNotBeDeleted() { - assertCrash("subclass must override") { - try dbQueue.inDatabase { db in - try RecordWithoutDatabaseTableName().delete(db) - } - } - } - - func testRecordWithoutDatabaseTableNameCanNotBeTestedForExistence() { - assertCrash("subclass must override") { - dbQueue.inDatabase { db in - RecordWithoutDatabaseTableName().exists(db) - } - } - } - - - // ========================================================================= - // MARK: - RecordWithInexistingDatabaseTable - - func testRecordWithInexistingDatabaseTableCanNotBeFetchedByID() { - assertCrash("no such table: foo") { - dbQueue.inDatabase { db in - RecordWithInexistingDatabaseTable.fetchOne(db, key: 1) - } - } - } - - func testRecordWithInexistingDatabaseTableCanNotBeFetchedByKey() { - assertCrash("SQLite error 1 with statement `SELECT * FROM \"foo\" WHERE (\"id\" = ?)`: no such table: foo") { - dbQueue.inDatabase { db in - RecordWithInexistingDatabaseTable.fetchOne(db, key: ["id": 1]) - } - } - } - - func testRecordWithInexistingDatabaseTableCanNotBeInserted() { - assertCrash("no such table: foo") { - try dbQueue.inDatabase { db in - try RecordWithInexistingDatabaseTable().insert(db) - } - } - } - - func testRecordWithInexistingDatabaseTableCanNotBeUpdated() { - assertCrash("no such table: foo") { - try dbQueue.inDatabase { db in - try RecordWithInexistingDatabaseTable().update(db) - } - } - } - - func testRecordWithInexistingDatabaseTableCanNotBeSaved() { - assertCrash("no such table: foo") { - try dbQueue.inDatabase { db in - try RecordWithInexistingDatabaseTable().save(db) - } - } - } - - func testRecordWithInexistingDatabaseTableCanNotBeDeleted() { - assertCrash("no such table: foo") { - try dbQueue.inDatabase { db in - try RecordWithInexistingDatabaseTable().delete(db) - } - } - } - - func testRecordWithInexistingDatabaseTableCanNotBeTestedForExistence() { - assertCrash("no such table: foo") { - dbQueue.inDatabase { db in - RecordWithInexistingDatabaseTable().exists(db) - } - } - } - - - // ========================================================================= - // MARK: - RecordWithEmptyPersistentDictionary - - func testRecordWithEmptyPersistentDictionaryCanNotBeInserted() { - assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") - try RecordWithEmptyPersistentDictionary().insert(db) - } - } - } - - func testRecordWithEmptyPersistentDictionaryCanNotBeUpdated() { - assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") - try RecordWithEmptyPersistentDictionary().update(db) - } - } - } - - func testRecordWithEmptyPersistentDictionaryCanNotBeSaved() { - assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") - try RecordWithEmptyPersistentDictionary().save(db) - } - } - } - - func testRecordWithEmptyPersistentDictionaryCanNotBeDeleted() { - assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") - try RecordWithEmptyPersistentDictionary().delete(db) - } - } - } - - func testRecordWithEmptyPersistentDictionaryCanNotBeTestedForExistence() { - assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") - RecordWithEmptyPersistentDictionary().exists(db) - } - } - } - - - // ========================================================================= - // MARK: - RecordWithNilPrimaryKey - - func testRecordWithNilPrimaryKeyCanNotBeUpdated() { - assertCrash("invalid primary key in ") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") - try RecordWithNilPrimaryKey().update(db) - } - } - } - - func testRecordWithNilPrimaryKeyCanNotBeDeleted() { - assertCrash("invalid primary key in ") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") - try RecordWithNilPrimaryKey().delete(db) - } - } - } - - func testRecordWithNilPrimaryKeyCanNotBeTestedForExistence() { - assertCrash("invalid primary key in ") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)") - RecordWithNilPrimaryKey().exists(db) - } - } - } - - - // ========================================================================= - // MARK: - RecordForTableWithoutPrimaryKey - - func testRecordForTableWithoutPrimaryKeyCanNotBeFetchedByID() { - assertCrash("expected single column primary key in table: records") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (name TEXT)") - RecordForTableWithoutPrimaryKey.fetchOne(db, key: 1) - } - } - } - - func testRecordForTableWithoutPrimaryKeyCanNotBeUpdated() { - assertCrash("invalid primary key in ") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (name TEXT)") - try RecordForTableWithoutPrimaryKey().update(db) - } - } - } - - func testRecordForTableWithoutPrimaryKeyCanNotBeDeleted() { - assertCrash("invalid primary key in ") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (name TEXT)") - try RecordForTableWithoutPrimaryKey().delete(db) - } - } - } - - func testRecordForTableWithoutPrimaryKeyCanNotBeTestedForExistence() { - assertCrash("invalid primary key in ") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (name TEXT)") - RecordForTableWithoutPrimaryKey().exists(db) - } - } - } - - - // ========================================================================= - // MARK: - RecordForTableWithMultipleColumnsPrimaryKey - - func testRecordForTableWithMultipleColumnsPrimaryKeyCanNotBeFetchedByID() { - assertCrash("expected single column primary key in table: records") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (a TEXT, b TEXT, PRIMARY KEY(a,b))") - RecordForTableWithMultipleColumnsPrimaryKey.fetchOne(db, key: 1) - } - } - } - - - // ========================================================================= - // MARK: - RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary - - func testRecordWithRowIDPrimaryKeyNotExposedInPersistentDictionaryCanNotBeInserted() { - assertCrash("invalid primary key in ") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY, name TEXT)") - try RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary().update(db) - } - } - } - - - // ========================================================================= - // MARK: - Concurrency - - func testReaderCrashDuringExclusiveTransaction() { - assertCrash("SQLite error 5 with statement `SELECT * FROM stuffs`: database is locked") { - databasePath = "/tmp/GRDBTestReaderDuringExclusiveTransaction.sqlite" - do { try NSFileManager.defaultManager().removeItemAtPath(databasePath) } catch { } - let dbQueue1 = try! DatabaseQueue(path: databasePath) - let dbQueue2 = try! DatabaseQueue(path: databasePath) - - try! dbQueue1.inDatabase { db in - try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)") - } - - let queue = NSOperationQueue() - queue.maxConcurrentOperationCount = 2 - queue.addOperation(NSBlockOperation { - do { - try dbQueue1.inTransaction(.Exclusive) { db in - sleep(2) // let other queue try to read. - return .Commit - } - } - catch is DatabaseError { - } - catch { - XCTFail("\(error)") - } - }) - - queue.addOperation(NSBlockOperation { - dbQueue2.inDatabase { db in - sleep(1) // let other queue open transaction - Row.fetch(db, "SELECT * FROM stuffs") // Crash expected - } - }) - - queue.waitUntilAllOperationsAreFinished() - } - } - - - // ========================================================================= - // MARK: - DatabaseValueConvertible - - func testCrashFetchDatabaseValueConvertibleFromStatement() { - assertCrash("could not convert NULL to IntConvertible.") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE ints (int Int)") - try db.execute("INSERT INTO ints (int) VALUES (1)") - try db.execute("INSERT INTO ints (int) VALUES (NULL)") - - let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int") - let sequence = IntConvertible.fetch(statement) - for _ in sequence { } - } - } - } - - func testCrashFetchAllDatabaseValueConvertibleFromStatement() { - assertCrash("could not convert NULL to IntConvertible.") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE ints (int Int)") - try db.execute("INSERT INTO ints (int) VALUES (1)") - try db.execute("INSERT INTO ints (int) VALUES (NULL)") - - let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int") - let _ = IntConvertible.fetchAll(statement) - } - } - } - - func testCrashFetchDatabaseValueConvertibleFromDatabase() { - assertCrash("could not convert NULL to IntConvertible.") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE ints (int Int)") - try db.execute("INSERT INTO ints (int) VALUES (1)") - try db.execute("INSERT INTO ints (int) VALUES (NULL)") - - let sequence = IntConvertible.fetch(db, "SELECT int FROM ints ORDER BY int") - for _ in sequence { } - } - } - } - - func testCrashFetchAllDatabaseValueConvertibleFromDatabase() { - assertCrash("could not convert NULL to IntConvertible.") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE ints (int Int)") - try db.execute("INSERT INTO ints (int) VALUES (1)") - try db.execute("INSERT INTO ints (int) VALUES (NULL)") - - let _ = IntConvertible.fetchAll(db, "SELECT int FROM ints ORDER BY int") - } - } - } - - func testCrashDatabaseValueConvertibleInvalidConversionFromNULL() { - assertCrash("could not convert NULL to IntConvertible.") { - let row = Row(["int": nil]) - let _ = row.value(named: "int") as IntConvertible - } - } - - func testCrashDatabaseValueConvertibleInvalidConversionFromInvalidType() { - assertCrash("could not convert \"foo\" to IntConvertible") { - let row = Row(["int": "foo"]) - let _ = row.value(named: "int") as IntConvertible - } - } - - - // ========================================================================= - // MARK: - StatementColumnConvertible - - func testCrashFetchStatementColumnConvertibleFromStatement() { - assertCrash("could not convert NULL to Int.") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE ints (int Int)") - try db.execute("INSERT INTO ints (int) VALUES (1)") - try db.execute("INSERT INTO ints (int) VALUES (NULL)") - - let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int") - let sequence = Int.fetch(statement) - for _ in sequence { } - } - } - } - - func testCrashFetchAllStatementColumnConvertibleFromStatement() { - assertCrash("could not convert NULL to Int.") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE ints (int Int)") - try db.execute("INSERT INTO ints (int) VALUES (1)") - try db.execute("INSERT INTO ints (int) VALUES (NULL)") - - let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int") - let _ = Int.fetchAll(statement) - } - } - } - - func testCrashFetchStatementColumnConvertibleFromDatabase() { - assertCrash("could not convert NULL to Int.") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE ints (int Int)") - try db.execute("INSERT INTO ints (int) VALUES (1)") - try db.execute("INSERT INTO ints (int) VALUES (NULL)") - - let sequence = Int.fetch(db, "SELECT int FROM ints ORDER BY int") - for _ in sequence { } - } - } - } - - func testCrashFetchAllStatementColumnConvertibleFromDatabase() { - assertCrash("could not convert NULL to Int.") { - try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE ints (int Int)") - try db.execute("INSERT INTO ints (int) VALUES (1)") - try db.execute("INSERT INTO ints (int) VALUES (NULL)") - - let _ = Int.fetchAll(db, "SELECT int FROM ints ORDER BY int") - } - } - } - -} diff --git a/Tests/Public/FetchRequest/FetchRequestTests.swift b/Tests/Public/FetchRequest/FetchRequestTests.swift index da716481b..75fe787d2 100644 --- a/Tests/Public/FetchRequest/FetchRequestTests.swift +++ b/Tests/Public/FetchRequest/FetchRequestTests.swift @@ -20,9 +20,7 @@ class FetchRequestTests: GRDBTestCase { collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in return (lhs as NSString).localizedCaseInsensitiveCompare(rhs) } - dbQueue.inDatabase { db in - db.addCollation(self.collation) - } + dbQueue.addCollation(collation) var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in @@ -81,27 +79,45 @@ class FetchRequestTests: GRDBTestCase { // MARK: - Count func testFetchCount() { - assertNoError { - try dbQueue.inDatabase { db in - XCTAssertEqual(tableRequest.fetchCount(db), 0) - XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - - let readers: [(String, Int?)] = [ - ("Arthur", 42), - ("Barbara", 36), - ("Craig", 42), - ("Craig", 42), - ("Daniel", nil)] - for (name, age) in readers { - try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: [name, age]) - } - - XCTAssertEqual(tableRequest.fetchCount(db), 5) - XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - - XCTAssertEqual(tableRequest.filter(Col.age == 42).fetchCount(db), 3) - XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE (\"age\" = 42)") - } + dbQueue.inDatabase { db in + XCTAssertEqual(tableRequest.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(tableRequest.reverse().fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(tableRequest.order(Col.name).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(tableRequest.limit(10).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM \"readers\" LIMIT 10)") + + XCTAssertEqual(tableRequest.filter(Col.age == 42).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE (\"age\" = 42)") + + XCTAssertEqual(tableRequest.distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT * FROM \"readers\")") + + XCTAssertEqual(tableRequest.select(Col.name).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(tableRequest.select(Col.name).distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT \"name\") FROM \"readers\"") + + XCTAssertEqual(tableRequest.select(Col.age * 2).distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT (\"age\" * 2)) FROM \"readers\"") + + XCTAssertEqual(tableRequest.select((Col.age * 2).aliased("ignored")).distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT (\"age\" * 2)) FROM \"readers\"") + + XCTAssertEqual(tableRequest.select(Col.name, Col.age).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(tableRequest.select(Col.name, Col.age).distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"name\", \"age\" FROM \"readers\")") + + XCTAssertEqual(tableRequest.select(max(Col.age)).group(Col.name).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT MAX(\"age\") FROM \"readers\" GROUP BY \"name\")") } } diff --git a/Tests/Public/FetchRequest/SQLSupportTests.swift b/Tests/Public/FetchRequest/SQLSupportTests.swift index 61b27f515..cc4ec02b5 100644 --- a/Tests/Public/FetchRequest/SQLSupportTests.swift +++ b/Tests/Public/FetchRequest/SQLSupportTests.swift @@ -21,17 +21,13 @@ class SQLSupportTests: GRDBTestCase { collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in return (lhs as NSString).localizedCaseInsensitiveCompare(rhs) } - dbQueue.inDatabase { db in - db.addCollation(self.collation) - } + dbQueue.addCollation(collation) customFunction = DatabaseFunction("avgOf", pure: true) { databaseValues in let sum = databaseValues.flatMap { $0.value() as Int? }.reduce(0, combine: +) return Double(sum) / Double(databaseValues.count) } - dbQueue.inDatabase { db in - db.addFunction(self.customFunction) - } + dbQueue.addFunction(self.customFunction) var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in @@ -149,8 +145,6 @@ class SQLSupportTests: GRDBTestCase { } func testGreaterThan() { - // TODO: test compound expressions such as `average(Col.age) + 10 > 20` - XCTAssertEqual( sql(tableRequest.filter(Col.age > 10)), "SELECT * FROM \"readers\" WHERE (\"age\" > 10)") @@ -176,6 +170,10 @@ class SQLSupportTests: GRDBTestCase { XCTAssertEqual( sql(tableRequest.filter(Col.name > Col.name)), "SELECT * FROM \"readers\" WHERE (\"name\" > \"name\")") + + XCTAssertEqual( + sql(tableRequest.group(Col.name).having(average(Col.age) + 10 > 20)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((AVG(\"age\") + 10) > 20)") } func testGreaterThanWithCollation() { @@ -188,8 +186,6 @@ class SQLSupportTests: GRDBTestCase { } func testGreaterThanOrEqual() { - // TODO: test compound expressions such as `average(Col.age) + 10 > 20` - XCTAssertEqual( sql(tableRequest.filter(Col.age >= 10)), "SELECT * FROM \"readers\" WHERE (\"age\" >= 10)") @@ -215,6 +211,10 @@ class SQLSupportTests: GRDBTestCase { XCTAssertEqual( sql(tableRequest.filter(Col.name >= Col.name)), "SELECT * FROM \"readers\" WHERE (\"name\" >= \"name\")") + + XCTAssertEqual( + sql(tableRequest.group(Col.name).having(average(Col.age) + 10 >= 20)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((AVG(\"age\") + 10) >= 20)") } func testGreaterThanOrEqualWithCollation() { @@ -227,8 +227,6 @@ class SQLSupportTests: GRDBTestCase { } func testLessThan() { - // TODO: test compound expressions such as `average(Col.age) + 10 > 20` - XCTAssertEqual( sql(tableRequest.filter(Col.age < 10)), "SELECT * FROM \"readers\" WHERE (\"age\" < 10)") @@ -254,6 +252,10 @@ class SQLSupportTests: GRDBTestCase { XCTAssertEqual( sql(tableRequest.filter(Col.name < Col.name)), "SELECT * FROM \"readers\" WHERE (\"name\" < \"name\")") + + XCTAssertEqual( + sql(tableRequest.group(Col.name).having(average(Col.age) + 10 < 20)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((AVG(\"age\") + 10) < 20)") } func testLessThanWithCollation() { @@ -266,8 +268,6 @@ class SQLSupportTests: GRDBTestCase { } func testLessThanOrEqual() { - // TODO: test compound expressions such as `average(Col.age) + 10 > 20` - XCTAssertEqual( sql(tableRequest.filter(Col.age <= 10)), "SELECT * FROM \"readers\" WHERE (\"age\" <= 10)") @@ -293,6 +293,10 @@ class SQLSupportTests: GRDBTestCase { XCTAssertEqual( sql(tableRequest.filter(Col.name <= Col.name)), "SELECT * FROM \"readers\" WHERE (\"name\" <= \"name\")") + + XCTAssertEqual( + sql(tableRequest.group(Col.name).having(average(Col.age) + 10 <= 20)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((AVG(\"age\") + 10) <= 20)") } func testLessThanOrEqualWithCollation() { diff --git a/Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift b/Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift index 0a075f0a3..a0b2b1a13 100644 --- a/Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift +++ b/Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift @@ -36,27 +36,45 @@ class TableMappingFetchRequestTests: GRDBTestCase { // MARK: - Count func testFetchCount() { - assertNoError { - try dbQueue.inDatabase { db in - XCTAssertEqual(Reader.fetchCount(db), 0) - XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - - let readers: [(String, Int?)] = [ - ("Arthur", 42), - ("Barbara", 36), - ("Craig", 42), - ("Craig", 42), - ("Daniel", nil)] - for (name, age) in readers { - try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: [name, age]) - } - - XCTAssertEqual(Reader.fetchCount(db), 5) - XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - - XCTAssertEqual(Reader.filter(Col.age == 42).fetchCount(db), 3) - XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE (\"age\" = 42)") - } + dbQueue.inDatabase { db in + XCTAssertEqual(Reader.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(Reader.all().reverse().fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(Reader.order(Col.name).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(Reader.limit(10).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM \"readers\" LIMIT 10)") + + XCTAssertEqual(Reader.filter(Col.age == 42).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE (\"age\" = 42)") + + XCTAssertEqual(Reader.all().distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT * FROM \"readers\")") + + XCTAssertEqual(Reader.select(Col.name).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(Reader.select(Col.name).distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT \"name\") FROM \"readers\"") + + XCTAssertEqual(Reader.select(Col.age * 2).distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT (\"age\" * 2)) FROM \"readers\"") + + XCTAssertEqual(Reader.select((Col.age * 2).aliased("ignored")).distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT (\"age\" * 2)) FROM \"readers\"") + + XCTAssertEqual(Reader.select(Col.name, Col.age).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(Reader.select(Col.name, Col.age).distinct.fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"name\", \"age\" FROM \"readers\")") + + XCTAssertEqual(Reader.select(max(Col.age)).group(Col.name).fetchCount(db), 0) + XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT MAX(\"age\") FROM \"readers\" GROUP BY \"name\")") } } @@ -160,15 +178,6 @@ class TableMappingFetchRequestTests: GRDBTestCase { } - // MARK: - Reverse - - func testReverse() { - XCTAssertEqual( - sql(Reader.reverse()), - "SELECT * FROM \"readers\" ORDER BY \"id\" DESC") - } - - // MARK: - Limit func testLimit() { diff --git a/Tests/Public/Migrations/DatabaseMigratorTests.swift b/Tests/Public/Migrations/DatabaseMigratorTests.swift index 33c4138db..5fa776016 100644 --- a/Tests/Public/Migrations/DatabaseMigratorTests.swift +++ b/Tests/Public/Migrations/DatabaseMigratorTests.swift @@ -41,6 +41,12 @@ class DatabaseMigratorTests : GRDBTestCase { XCTAssertTrue(db.tableExists("persons")) XCTAssertFalse(db.tableExists("pets")) } + + try migrator.migrate(dbPool) + dbPool.read { db in + XCTAssertTrue(db.tableExists("persons")) + XCTAssertFalse(db.tableExists("pets")) + } } } diff --git a/Tests/Public/Record/PrimaryKeyNoneTests.swift b/Tests/Public/Record/PrimaryKeyNoneTests.swift index 488eb0ab0..ef138e77f 100644 --- a/Tests/Public/Record/PrimaryKeyNoneTests.swift +++ b/Tests/Public/Record/PrimaryKeyNoneTests.swift @@ -2,7 +2,7 @@ import XCTest import GRDB // Item has no primary key. -class Item : Record { +private class Item : Record { var name: String? init(name: String? = nil) { diff --git a/Tests/Public/Record/PrimaryKeyRowIDTests.swift b/Tests/Public/Record/PrimaryKeyRowIDTests.swift index bc127974f..dbddc2804 100644 --- a/Tests/Public/Record/PrimaryKeyRowIDTests.swift +++ b/Tests/Public/Record/PrimaryKeyRowIDTests.swift @@ -49,7 +49,7 @@ class Person : Record { ] } - override func insert(db: Database) throws { + override func insert(db: DatabaseWriter) throws { // This is implicitely tested with the NOT NULL constraint on creationDate if creationDate == nil { creationDate = NSDate() diff --git a/Tests/Public/Record/RecordEditedTests.swift b/Tests/Public/Record/RecordEditedTests.swift index dc12d92dd..c41992df7 100644 --- a/Tests/Public/Record/RecordEditedTests.swift +++ b/Tests/Public/Record/RecordEditedTests.swift @@ -58,7 +58,7 @@ class PersonWithModifiedCaseColumns: Record { ] } - override func insert(db: Database) throws { + override func insert(db: DatabaseWriter) throws { // This is implicitely tested with the NOT NULL constraint on creationDate if creationDate == nil { creationDate = NSDate() diff --git a/Tests/Public/Record/RecordSubClassTests.swift b/Tests/Public/Record/RecordSubClassTests.swift index 0be7a332b..b38ac2154 100644 --- a/Tests/Public/Record/RecordSubClassTests.swift +++ b/Tests/Public/Record/RecordSubClassTests.swift @@ -32,12 +32,12 @@ class PersonWithOverrides : Person { super.init(row) } - override func insert(db: Database) throws { + override func insert(db: DatabaseWriter) throws { lastSavingMethod = .Insert try super.insert(db) } - override func update(db: Database) throws { + override func update(db: DatabaseWriter) throws { lastSavingMethod = .Update try super.update(db) }