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

This commit is contained in:
Gwendal Roué committed 2016-03-17 08:02:06 +01:00
commit a308ffebeb
147 files changed
+14365 -2644

No files matched your search

+163
View File
@@ -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
@@ -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
@@ -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
@@ -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 = "<group>"; };
560A37B41C91391800949E71 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
560A37B51C91391800949E71 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = "<group>"; };
560A37B61C91391800949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = "<group>"; };
560A37B71C91391800949E71 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = "<group>"; };
560A37B81C91391800949E71 /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = "<group>"; };
560A37B91C91391800949E71 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = "<group>"; };
560A37BA1C91391800949E71 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
560A37BB1C91391800949E71 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = "<group>"; };
560A37BC1C91391800949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = "<group>"; };
560A37BD1C91391800949E71 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = "<group>"; };
560A37BE1C91391800949E71 /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = "<group>"; };
560A37C11C91391800949E71 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = "<group>"; };
560A37C31C91391800949E71 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = "<group>"; };
560A37C41C91391800949E71 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = "<group>"; };
560A37C51C91391800949E71 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = "<group>"; };
560A37C61C91391800949E71 /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
560A37C71C91391800949E71 /* NSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDate.swift; sourceTree = "<group>"; };
560A37C81C91391800949E71 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = "<group>"; };
560A37C91C91391800949E71 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = "<group>"; };
560A37CA1C91391800949E71 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
560A37CB1C91391800949E71 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = "<group>"; };
560A37CC1C91391800949E71 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = "<group>"; };
560A37CD1C91391800949E71 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = "<group>"; };
560A37CF1C91391800949E71 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = "<group>"; };
560A37D01C91391800949E71 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
560A37D11C91391800949E71 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
560A37D31C91391800949E71 /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = "<group>"; };
560A37D41C91391800949E71 /* SQLCollation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollation.swift; sourceTree = "<group>"; };
560A37D51C91391800949E71 /* SQLFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunction.swift; sourceTree = "<group>"; };
560A37D61C91391800949E71 /* SQLOperator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperator.swift; sourceTree = "<group>"; };
560A37D71C91391800949E71 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = "<group>"; };
560A37D91C91391800949E71 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
560A37DA1C91391800949E71 /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
560A37DC1C91391800949E71 /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = "<group>"; };
560A37DD1C91391800949E71 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
560A37DE1C91391800949E71 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
560A37DF1C91391800949E71 /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = "<group>"; };
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 = "<group>"; };
562FF9961BCE8FA400759400 /* PersonsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersonsViewController.swift; sourceTree = "<group>"; };
@@ -65,42 +109,10 @@
562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
562FF9F11BCE914E00759400 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
562FF9F41BCE930C00759400 /* GRDBDemoiOS7-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBDemoiOS7-Bridging-Header.h"; sourceTree = "<group>"; };
563363C71C942CAE000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = "<group>"; };
563363C91C942CB4000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = "<group>"; };
563363EF1C95A41B000BE133 /* DatabaseStore.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseStore.swift; sourceTree = "<group>"; };
566A20F21C58A4B300C5A218 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
566A20F61C58A54F00C5A218 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = "<group>"; };
566A20F71C58A54F00C5A218 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
566A20F81C58A54F00C5A218 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = "<group>"; };
566A20F91C58A54F00C5A218 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = "<group>"; };
566A20FA1C58A54F00C5A218 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = "<group>"; };
566A20FC1C58A54F00C5A218 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
566A20FD1C58A54F00C5A218 /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = "<group>"; };
566A20FE1C58A54F00C5A218 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
566A20FF1C58A54F00C5A218 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = "<group>"; };
566A21001C58A54F00C5A218 /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = "<group>"; };
566A21011C58A54F00C5A218 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = "<group>"; };
566A21021C58A54F00C5A218 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = "<group>"; };
566A21031C58A54F00C5A218 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
566A21051C58A54F00C5A218 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = "<group>"; };
566A21071C58A54F00C5A218 /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = "<group>"; };
566A21091C58A54F00C5A218 /* Collation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Collation.swift; sourceTree = "<group>"; };
566A210A1C58A54F00C5A218 /* Function.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Function.swift; sourceTree = "<group>"; };
566A210B1C58A54F00C5A218 /* Operator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Operator.swift; sourceTree = "<group>"; };
566A210C1C58A54F00C5A218 /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
566A210E1C58A54F00C5A218 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = "<group>"; };
566A210F1C58A54F00C5A218 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = "<group>"; };
566A21101C58A54F00C5A218 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = "<group>"; };
566A21111C58A54F00C5A218 /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
566A21121C58A54F00C5A218 /* NSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDate.swift; sourceTree = "<group>"; };
566A21131C58A54F00C5A218 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = "<group>"; };
566A21141C58A54F00C5A218 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = "<group>"; };
566A21151C58A54F00C5A218 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
566A21161C58A54F00C5A218 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = "<group>"; };
566A21171C58A54F00C5A218 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = "<group>"; };
566A21181C58A54F00C5A218 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = "<group>"; };
566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
566A211F1C58A54F00C5A218 /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
566A21231C58A54F00C5A218 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
566A21251C58A54F00C5A218 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = "<group>"; };
566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibraryTypes.swift; sourceTree = "<group>"; };
/* 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 = "<group>";
};
560A37BF1C91391800949E71 /* Support */ = {
isa = PBXGroup;
children = (
560A37C01C91391800949E71 /* CoreGraphics */,
560A37C21C91391800949E71 /* Foundation */,
560A37CE1C91391800949E71 /* StandardLibrary */,
);
path = Support;
sourceTree = "<group>";
};
560A37C01C91391800949E71 /* CoreGraphics */ = {
isa = PBXGroup;
children = (
560A37C11C91391800949E71 /* CGFloat.swift */,
);
path = CoreGraphics;
sourceTree = "<group>";
};
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 = "<group>";
};
560A37CE1C91391800949E71 /* StandardLibrary */ = {
isa = PBXGroup;
children = (
560A37CF1C91391800949E71 /* RawRepresentable.swift */,
560A37D01C91391800949E71 /* StandardLibrary.swift */,
);
path = StandardLibrary;
sourceTree = "<group>";
};
560A37D21C91391800949E71 /* FetchRequest */ = {
isa = PBXGroup;
children = (
560A37D31C91391800949E71 /* FetchRequest.swift */,
560A37D41C91391800949E71 /* SQLCollation.swift */,
560A37D51C91391800949E71 /* SQLFunction.swift */,
560A37D61C91391800949E71 /* SQLOperator.swift */,
560A37D71C91391800949E71 /* SQLSelectQuery.swift */,
);
path = FetchRequest;
sourceTree = "<group>";
};
560A37D81C91391800949E71 /* Migrations */ = {
isa = PBXGroup;
children = (
560A37D91C91391800949E71 /* DatabaseMigrator.swift */,
560A37DA1C91391800949E71 /* Migration.swift */,
);
path = Migrations;
sourceTree = "<group>";
};
560A37DB1C91391800949E71 /* Record */ = {
isa = PBXGroup;
children = (
560A37DC1C91391800949E71 /* Persistable.swift */,
560A37DD1C91391800949E71 /* Record.swift */,
560A37DE1C91391800949E71 /* RowConvertible.swift */,
560A37DF1C91391800949E71 /* TableMapping.swift */,
);
path = Record;
sourceTree = "<group>";
};
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 = "<group>";
};
562FF9ED1BCE904D00759400 /* Libraries */ = {
562FF9ED1BCE904D00759400 /* GRDB */ = {
isa = PBXGroup;
children = (
562FF9EB1BCE903D00759400 /* libsqlite3.tbd */,
566A20F41C58A54F00C5A218 /* GRDB */,
);
name = Libraries;
name = GRDB;
sourceTree = "<group>";
};
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 = "<group>";
};
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 = "<group>";
};
566A20FB1C58A54F00C5A218 /* Protocols */ = {
isa = PBXGroup;
children = (
566A20FC1C58A54F00C5A218 /* DatabaseValueConvertible.swift */,
566A20FD1C58A54F00C5A218 /* Persistable.swift */,
566A20FE1C58A54F00C5A218 /* RowConvertible.swift */,
566A20FF1C58A54F00C5A218 /* SQLiteStatementConvertible.swift */,
566A21001C58A54F00C5A218 /* TableMapping.swift */,
);
path = Protocols;
sourceTree = "<group>";
};
566A21041C58A54F00C5A218 /* CoreGraphics */ = {
isa = PBXGroup;
children = (
566A21051C58A54F00C5A218 /* CGFloat.swift */,
);
path = CoreGraphics;
sourceTree = "<group>";
};
566A21061C58A54F00C5A218 /* FetchRequest */ = {
isa = PBXGroup;
children = (
566A21071C58A54F00C5A218 /* FetchRequest.swift */,
566A21081C58A54F00C5A218 /* SQLSupport */,
);
path = FetchRequest;
sourceTree = "<group>";
};
566A21081C58A54F00C5A218 /* SQLSupport */ = {
isa = PBXGroup;
children = (
566A21091C58A54F00C5A218 /* Collation.swift */,
566A210A1C58A54F00C5A218 /* Function.swift */,
566A210B1C58A54F00C5A218 /* Operator.swift */,
566A210C1C58A54F00C5A218 /* SQLQuery.swift */,
);
path = SQLSupport;
sourceTree = "<group>";
};
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 = "<group>";
};
566A211D1C58A54F00C5A218 /* Migrations */ = {
isa = PBXGroup;
children = (
566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */,
566A211F1C58A54F00C5A218 /* Migration.swift */,
);
path = Migrations;
sourceTree = "<group>";
};
566A21221C58A54F00C5A218 /* Record */ = {
isa = PBXGroup;
children = (
566A21231C58A54F00C5A218 /* Record.swift */,
);
path = Record;
sourceTree = "<group>";
};
566A21241C58A54F00C5A218 /* Swift */ = {
isa = PBXGroup;
children = (
566A21251C58A54F00C5A218 /* RawRepresentable.swift */,
566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */,
);
path = Swift;
sourceTree = "<group>";
};
/* 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;
};
+2 -2
View File
@@ -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}" }
+253 -38
View File
@@ -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 = "<group>"; };
5605F14B1C672E4000235C62 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = "<group>"; };
@@ -315,13 +383,16 @@
5605F1551C672E4000235C62 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = "<group>"; };
5605F1571C672E4000235C62 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = "<group>"; };
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* SelectStatementSourceTablesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SelectStatementSourceTablesTests.swift; sourceTree = "<group>"; };
5605F1861C69111300235C62 /* StatementInformationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementInformationTests.swift; sourceTree = "<group>"; };
5605F1891C6B1A8700235C62 /* SQLCollation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollation.swift; sourceTree = "<group>"; };
5605F18A1C6B1A8700235C62 /* SQLFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunction.swift; sourceTree = "<group>"; };
5605F18B1C6B1A8700235C62 /* SQLOperator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperator.swift; sourceTree = "<group>"; };
5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = "<group>"; };
560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = "<group>"; };
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = "<group>"; };
560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolConcurrencyTests.swift; sourceTree = "<group>"; };
560A37AE1C90A8D800949E71 /* DatabasePoolCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolCrashTests.swift; sourceTree = "<group>"; };
560C97C61BFD0B8400BF8471 /* FunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionTests.swift; sourceTree = "<group>"; };
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 = "<group>"; };
@@ -336,14 +407,42 @@
56300B6A1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+FetchRequestTests.swift"; sourceTree = "<group>"; };
56300B6F1C53F592005A543B /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = "<group>"; };
56300B841C54DC95005A543B /* Record+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+FetchRequestTests.swift"; sourceTree = "<group>"; };
563363A91C933FF8000BE133 /* DatabaseMutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMutablePersistableTests.swift; sourceTree = "<group>"; };
563363AA1C933FF8000BE133 /* DatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistableTests.swift; sourceTree = "<group>"; };
563363AB1C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolMutablePersistableTests.swift; sourceTree = "<group>"; };
563363AC1C933FF8000BE133 /* DatabasePoolPersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolPersistableTests.swift; sourceTree = "<group>"; };
563363AD1C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueMutablePersistableTests.swift; sourceTree = "<group>"; };
563363AE1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueuePersistableTests.swift; sourceTree = "<group>"; };
563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = "<group>"; };
563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = "<group>"; };
563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = "<group>"; };
563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReleaseMemoryTests.swift; sourceTree = "<group>"; };
563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = "<group>"; };
563363D71C95787F000BE133 /* DatabaseStore.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseStore.swift; sourceTree = "<group>"; };
563363DB1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueFileAttributesTests.swift; sourceTree = "<group>"; };
563363DE1C959295000BE133 /* DatabasePoolFileAttributesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolFileAttributesTests.swift; sourceTree = "<group>"; };
563363F11C95F654000BE133 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = Realm/RealmSwift.framework; sourceTree = "<group>"; };
563363F31C95F6EB000BE133 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = Realm/Realm.framework; sourceTree = "<group>"; };
563363F81C960711000BE133 /* PerformanceRealmTests.realm */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceRealmTests.realm; sourceTree = "<group>"; };
563445041C4A7FD7003D3DC6 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollationTests.swift; sourceTree = "<group>"; };
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 = "<group>"; };
565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = "<group>"; };
565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = "<group>"; };
565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = "<group>"; };
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 = "<group>"; };
569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleCrashTests.swift; sourceTree = "<group>"; };
569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBCrashTestCase.swift; sourceTree = "<group>"; };
569530FE1C9067CC00CF1A2B /* MigrationCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MigrationCrashTests.swift; sourceTree = "<group>"; };
569530FF1C9067CC00CF1A2B /* RecordCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordCrashTests.swift; sourceTree = "<group>"; };
569531001C9067CC00CF1A2B /* StatementColumnConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleCrashTests.swift; sourceTree = "<group>"; };
569531011C9067CC00CF1A2B /* StatementCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementCrashTests.swift; sourceTree = "<group>"; };
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = "<group>"; };
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueSchemaCacheTests.swift; sourceTree = "<group>"; };
569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolSchemaCacheTests.swift; sourceTree = "<group>"; };
569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolCollationTests.swift; sourceTree = "<group>"; };
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolFunctionTests.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
56A238141B9C74A90082EB20 /* InMemoryDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InMemoryDatabaseTests.swift; sourceTree = "<group>"; };
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = "<group>"; };
@@ -381,7 +480,6 @@
56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTimestampTests.swift; sourceTree = "<group>"; };
56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordWithColumnNameManglingTests.swift; sourceTree = "<group>"; };
56AC8CCD1BA3F2AD009E4319 /* ConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConcurrencyTests.swift; sourceTree = "<group>"; };
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4361BE4C11200E39BBF /* DatabaseCoderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoderTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
@@ -406,7 +504,6 @@
56CA21B91BB3FCF7009A04C5 /* NSDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDataTests.swift; sourceTree = "<group>"; };
56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = SQLite.xcodeproj; path = SQLite.swift/SQLite.xcodeproj; sourceTree = "<group>"; };
56CA22211BB41565009A04C5 /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceTests.swift; sourceTree = "<group>"; };
56CB92EC1BA453E500DFD5FC /* CrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CrashTests.swift; sourceTree = "<group>"; };
56DBEC341C19A0020093A2EE /* CHANGELOG.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = CHANGELOG.md; sourceTree = "<group>"; };
56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = "<group>"; };
56DE7B231C412F7E00861EB8 /* InsertPositionalValuesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertPositionalValuesTests.swift; sourceTree = "<group>"; };
@@ -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 = "<group>"; };
56E8CE0F1BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertibleFetchTests.swift; sourceTree = "<group>"; };
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = "<group>"; };
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
56EB0AB11BCD787300A3DC55 /* NSDataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDataMemoryTests.swift; sourceTree = "<group>"; };
56EE573C1BB317B7007A6A95 /* SQLiteStatementConversionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConversionTests.swift; sourceTree = "<group>"; };
56F0B98D1B6001C600A2F135 /* NSDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDateComponentsTests.swift; sourceTree = "<group>"; };
@@ -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 = "<group>";
};
560A37A91C90084600949E71 /* DatabasePool */ = {
isa = PBXGroup;
children = (
569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */,
560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */,
563363DE1C959295000BE133 /* DatabasePoolFileAttributesTests.swift */,
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */,
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */,
);
path = DatabasePool;
sourceTree = "<group>";
};
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 = "<group>";
@@ -601,6 +718,15 @@
path = FetchRequest;
sourceTree = "<group>";
};
563363BB1C93FD32000BE133 /* DatabaseQueue */ = {
isa = PBXGroup;
children = (
563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */,
563363DB1C95891E000BE133 /* DatabaseQueueFileAttributesTests.swift */,
);
path = DatabaseQueue;
sourceTree = "<group>";
};
564A50BF1BFF4B6E00B3A3A2 /* Collation */ = {
isa = PBXGroup;
children = (
@@ -609,11 +735,30 @@
path = Collation;
sourceTree = "<group>";
};
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 = "<group>";
};
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 = "<group>";
@@ -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 = "<group>";
@@ -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 = "<group>";
@@ -786,14 +938,6 @@
path = Record;
sourceTree = "<group>";
};
56AC8CCC1BA3F267009E4319 /* Concurrency */ = {
isa = PBXGroup;
children = (
56AC8CCD1BA3F2AD009E4319 /* ConcurrencyTests.swift */,
);
path = Concurrency;
sourceTree = "<group>";
};
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 = "<group>";
};
56EA86921C91DFDA002BB4DF /* DatabaseReader */ = {
isa = PBXGroup;
children = (
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
);
path = DatabaseReader;
sourceTree = "<group>";
};
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";
+6 -3
View File
@@ -4,6 +4,12 @@
<Group
location = "group:Playgrounds"
name = "Playgrounds">
<FileRef
location = "group:/Users/groue/Documents/git/groue/GRDB.swift/Playgrounds/Tour.playground">
</FileRef>
<FileRef
location = "group:DatabaseTimestamp.playground">
</FileRef>
<FileRef
location = "group:JSONSynchronization.playground">
</FileRef>
@@ -13,9 +19,6 @@
<FileRef
location = "group:TransactionObserver.playground">
</FileRef>
<FileRef
location = "group:DatabaseTimestamp.playground">
</FileRef>
<FileRef
location = "group:UserDefaults.playground">
</FileRef>
+24 -3
View File
@@ -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() { }
+143 -88
View File
@@ -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<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
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<Void> = 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<Void>.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<Int8>(codeUnits.baseAddress)
let sqlEnd = sqlStart + sqlCodeUnits.count
var statementStart = sqlStart
while statementStart < sqlEnd - 1 {
schemaChangeObserver.invalidatesDatabaseSchemaCache = false
observer.reset()
var statementEnd: UnsafePointer<Int8> = 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<String> = []
let database: Database
init(_ database: Database) {
self.database = database
}
func start() {
let observerPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.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<String> = []
var invalidatesDatabaseSchemaCache = false
init(_ database: Database) {
self.database = database
@@ -816,15 +802,12 @@ final class SchemaChangeObserver {
let observerPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
sqlite3_set_authorizer(database.sqliteConnection, { (observerPointer, actionCode, CString1, CString2, CString3, CString4) -> Int32 in
switch actionCode {
case SQLITE_DROP_TABLE,
SQLITE_DROP_TEMP_TABLE,
SQLITE_DROP_TEMP_VIEW,
SQLITE_DROP_VIEW,
SQLITE_DETACH,
SQLITE_ALTER_TABLE,
SQLITE_DROP_VTABLE:
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<T>(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<T>(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<T>(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)
}
}
+352
View File
@@ -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<SerializedDatabase>
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private init(path: String, configuration: Configuration, maximumReaderCount: Int, databaseSchemaCache: DatabaseSchemaCacheType, writer: SerializedDatabase, store: DatabaseStore) {
self.store = store
self.writer = writer
self.readerPool = Pool<SerializedDatabase>(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<T>(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<T>(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<T>(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)
}
}
}
}
+158 -129
View File
@@ -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<T>(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<Void>.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<T>(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<Void>
// =========================================================================
// MARK: - DatabaseReader
extension DatabaseQueue : DatabaseReader {
// MARK: - Read From Database
/// Alias for inDatabase
///
/// This method is part of the DatabaseReader protocol adoption.
public func read<T>(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<T>(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<T>(block: (db: Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
}
+105
View File
@@ -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<T>(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<T>(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)
}
+74
View File
@@ -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) }
}
}
+89
View File
@@ -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()
}
}
}
}
}
+19 -16
View File
@@ -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<String>.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<Wrapped?> {
@@ -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) }
}
}
+87
View File
@@ -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<T>(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)
}
}
}
+77 -26
View File
@@ -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<SelectStatement>?
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<SelectStatement>) {
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<Row> {
// 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<DatabaseValue>
let columnNames: [String]
init(statement: SelectStatement) {
let sqliteStatement = statement.sqliteStatement
self.databaseValues = (0..<Int32(statement.columnCount)).map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) }
self.columnNames = statement.columnNames
init(sqliteStatement: SQLiteStatement, columnNames: [String]) {
assert(sqliteStatement != nil)
let sqliteStatement = sqliteStatement
self.databaseValues = ContiguousArray((0..<sqlite3_column_count(sqliteStatement)).lazy.map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) })
self.columnNames = columnNames
}
var count: Int {
@@ -720,12 +763,17 @@ private struct StatementCopyRowImpl : RowImpl {
/// See Row.init(statement:)
private struct StatementRowImpl : RowImpl {
let statement: SelectStatement
let statementRef: Unmanaged<SelectStatement>
let sqliteStatement: SQLiteStatement
let lowercaseColumnIndexes: [String: Int]
init(statement: SelectStatement) {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
init(sqliteStatement: SQLiteStatement, statementRef: Unmanaged<SelectStatement>) {
assert(sqliteStatement != nil)
self.statementRef = statementRef
self.sqliteStatement = sqliteStatement
// Optimize row.value(named: "...")
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement)).map { String.fromCString(sqlite3_column_name(sqliteStatement, Int32($0)))!.lowercaseString }
self.lowercaseColumnIndexes = Dictionary(lowercaseColumnNames.enumerate().map { ($1, $0) }.reverse())
}
var count: Int {
@@ -746,17 +794,20 @@ private struct StatementRowImpl : RowImpl {
}
func columnName(atIndex index: Int) -> 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)
}
}
+88
View File
@@ -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<Void>.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<T>(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)
}
}
}
+63 -56
View File
@@ -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<String>
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..<self.columnCount).map { String.fromCString(sqlite3_column_name(self.sqliteStatement, Int32($0)))! }
let sqliteStatement = self.sqliteStatement
return (0..<self.columnCount).map { String.fromCString(sqlite3_column_name(sqliteStatement, Int32($0)))! }
}()
/// Cache for indexOfColumn(). Keys are lowercase.
@@ -302,9 +297,9 @@ public final class SelectStatement : Statement {
return columnIndexes[name.lowercaseString]
}
/// The DatabaseSequence builder.
/// Creates a DatabaseSequence
@warn_unused_result
func fetchSequence<T>(arguments arguments: StatementArguments?, element: () -> T) -> DatabaseSequence<T> {
func fetchSequence<Element>(arguments arguments: StatementArguments?, element: () -> Element) -> DatabaseSequence<Element> {
// 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<T>: SequenceType {
private let generateImpl: () throws -> DatabaseGenerator<T>
public struct DatabaseSequence<Element>: SequenceType {
private let generateImpl: () throws -> DatabaseGenerator<Element>
// 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<T>: 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<T>) {
private init(generateImpl: () throws -> DatabaseGenerator<Element>) {
self.generateImpl = generateImpl
}
/// Return a *generator* over the elements of this *sequence*.
@warn_unused_result
public func generate() -> DatabaseGenerator<T> {
public func generate() -> DatabaseGenerator<Element> {
return try! generateImpl()
}
}
/// A generator of elements fetched from the database.
public struct DatabaseGenerator<T>: GeneratorType {
private let element: () throws -> T?
public func next() -> T? {
return try! element()
public class DatabaseGenerator<Element>: GeneratorType {
private let statementRef: Unmanaged<SelectStatement>?
private let sqliteStatement: SQLiteStatement
private let element: ((SQLiteStatement, Unmanaged<SelectStatement>) -> Element?)?
// Generator takes ownership of statementRef
init(statementRef: Unmanaged<SelectStatement>, element: (SQLiteStatement, Unmanaged<SelectStatement>) -> 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()
+6 -6
View File
@@ -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) }
}
}
@@ -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)
}
}
+158 -4
View File
@@ -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<T>(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<T>(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<T>(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<T> {
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<U>(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<Int>(maximumCount: 3, makeElement: {
/// number = number + 1
/// return number
/// })
///
/// The function get() dequeues an available element and gives this element to
/// the block argument. During the block execution, the element is not
/// available. When the block is ended, the element is available again.
///
/// // got 1
/// pool.get { n in
/// print("got \(n)")
/// }
///
/// If there is no available element, the pool builds a new element, unless the
/// maximum number of elements is reached. In this case, the get() method
/// blocks the current thread, until an element eventually turns available again.
///
/// 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<T> {
var makeElement: (() -> T)?
private var items: [PoolItem<T>] = []
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<U>(@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<T> {
var item: PoolItem<T>! = 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<T>) {
dispatch_sync(queue) {
item.available = true
}
dispatch_semaphore_signal(semaphore)
}
}
private class PoolItem<T> {
let element: T
var available: Bool
init(element: T, available: Bool) {
self.element = element
self.available = available
}
}
+100 -56
View File
@@ -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<Person>
///
/// 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<Self> {
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<String>
///
/// 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<T>(db: Database, _ request: FetchRequest<T>) -> [Self] {
return try! fetchAll(request.selectStatement(db))
public static func fetchAll<T>(db: DatabaseReader, _ request: FetchRequest<T>) -> [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<T>(db: Database, _ request: FetchRequest<T>) -> Self? {
return try! fetchOne(request.selectStatement(db))
public static func fetchOne<T>(db: DatabaseReader, _ request: FetchRequest<T>) -> 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<String>.fetch(db, request) // DatabaseSequence<String?>
///
/// 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<String>.fetchAll(db, request) // [String?]
///
/// - parameter db: A DatabaseReader (DatabaseQueue, DatabasePool, or Database).
@warn_unused_result
public static func fetchAll<T>(db: Database, _ request: FetchRequest<T>) -> [Wrapped?] {
return try! fetchAll(request.selectStatement(db))
public static func fetchAll<T>(db: DatabaseReader, _ request: FetchRequest<T>) -> [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<String>
///
/// 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<T>(db: Database, _ request: FetchRequest<T>) -> [Self] {
return try! fetchAll(request.selectStatement(db))
public static func fetchAll<T>(db: DatabaseReader, _ request: FetchRequest<T>) -> [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<T>(db: Database, _ request: FetchRequest<T>) -> Self? {
return try! fetchOne(request.selectStatement(db))
public static func fetchOne<T>(db: DatabaseReader, _ request: FetchRequest<T>) -> 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<Person>
/// let nameColumn = SQLColumn("firstName")
/// let request = Person.order(nameColumn)
/// let identities = Identity.fetch(db, request) // DatabaseSequence<Identity>
///
/// 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<T>(db: Database, _ request: FetchRequest<T>) -> [Self] {
return try! fetchAll(request.selectStatement(db))
public static func fetchAll<T>(db: DatabaseReader, _ request: FetchRequest<T>) -> [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<T>(db: Database, _ request: FetchRequest<T>) -> Self? {
return try! fetchOne(request.selectStatement(db))
public static func fetchOne<T>(db: DatabaseReader, _ request: FetchRequest<T>) -> 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<T>(db: Database, _ request: FetchRequest<T>) -> [Row] {
return try! fetchAll(request.selectStatement(db))
public static func fetchAll<T>(db: DatabaseReader, _ request: FetchRequest<T>) -> [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<T>(db: Database, _ request: FetchRequest<T>) -> Row? {
return try! fetchOne(request.selectStatement(db))
public static func fetchOne<T>(db: DatabaseReader, _ request: FetchRequest<T>) -> Row? {
return db.nonIsolatedRead { db in try! fetchOne(request.selectStatement(db)) }
}
}
+123 -17
View File
@@ -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)
}
}
}
+4 -3
View File
@@ -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)
}
+145 -68
View File
@@ -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<String, DatabaseValue>(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)
}
}
}
+69 -42
View File
@@ -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)
}
}
+9 -6
View File
@@ -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) }
}
}
+22 -16
View File
@@ -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<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(db: Database, keys: Sequence) -> [Self] {
guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else {
return []
public static func fetchAll<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(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<PrimaryKeyType: DatabaseValueConvertible>(db: Database, key: PrimaryKeyType?) -> Self? {
public static func fetchOne<PrimaryKeyType: DatabaseValueConvertible>(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 = ?) ...
+9 -14
View File
@@ -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)
+123
View File
@@ -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)
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='osx' display-mode='raw'>
<timeline fileName='timeline.xctimeline'/>
</playground>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>
@@ -53,9 +53,8 @@ class TableChangeObserver : NSObject, TransactionObserverType {
// Register observer
dbQueue.inDatabase { db in
db.addTransactionObserver(TableChangeObserver())
}
let observer = TableChangeObserver()
dbQueue.addTransactionObserver(observer)
//
@@ -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
}
+903 -602
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>0.45.0</string>
<string>0.51.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+2 -5
View File
@@ -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<StatementColumnConvertible>.fetch... methods when http://openradar.appspot.com/22852669 is fixed.
+21
View File
@@ -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")
}
}
}
}
+107
View File
@@ -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<Row>?
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<Row>?
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()
}
}
}
@@ -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
}
}
}
+15
View File
@@ -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)")
}
}
}
+13
View File
@@ -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 }
}
}
}
+324
View File
@@ -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 <RecordWithNilPrimaryKey id:nil>") {
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 <RecordWithNilPrimaryKey id:nil>") {
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 <RecordWithNilPrimaryKey id:nil>") {
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 <RecordForTableWithoutPrimaryKey name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
try RecordForTableWithoutPrimaryKey().update(db)
}
}
}
func testRecordForTableWithoutPrimaryKeyCanNotBeDeleted() {
assertCrash("invalid primary key in <RecordForTableWithoutPrimaryKey name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
try RecordForTableWithoutPrimaryKey().delete(db)
}
}
}
func testRecordForTableWithoutPrimaryKeyCanNotBeTestedForExistence() {
assertCrash("invalid primary key in <RecordForTableWithoutPrimaryKey name:\"foo\">") {
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 <RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY, name TEXT)")
try RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary().update(db)
}
}
}
}
@@ -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")
}
}
}
}
+73
View File
@@ -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])
}
}
}
}
@@ -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
+58 -17
View File
@@ -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<T>(request: FetchRequest<T>) -> String {
return dbQueue.inDatabase { db in
let _ = Row.fetchOne(db, request)
_ = Row.fetchOne(db, request)
return self.lastSQLQuery
}
}
+30 -30
View File
@@ -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
}
@@ -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
}
+26 -3
View File
@@ -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)
}
}
}
@@ -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
@@ -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
+19 -2
View File
@@ -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..<insertedRowCount {
realm.add(RealmItem(i0: i, i1: i, i2: i, i3: i, i4: i, i5: i, i6: i, i7: i, i8: i, i9: i))
}
}
}
}
}
Binary file not shown.
+32
View File
@@ -1,5 +1,7 @@
import GRDB
import SQLite
import RealmSwift
// MARK:- SQLite
@@ -87,3 +89,33 @@ extension Item {
}
}
// MARK: - Realm
class RealmItem : RealmSwift.Object {
dynamic var i0: Int = 0
dynamic var i1: Int = 0
dynamic var i2: Int = 0
dynamic var i3: Int = 0
dynamic var i4: Int = 0
dynamic var i5: Int = 0
dynamic var i6: Int = 0
dynamic var i7: Int = 0
dynamic var i8: Int = 0
dynamic var i9: Int = 0
convenience init(i0: Int, i1: Int, i2: Int, i3: Int, i4: Int, i5: Int, i6: Int, i7: Int, i8: Int, i9: Int) {
self.init()
self.i0 = i0
self.i1 = i1
self.i2 = i2
self.i3 = i3
self.i4 = i4
self.i5 = i5
self.i6 = i6
self.i7 = i7
self.i8 = i8
self.i9 = i9
}
}
+1
View File
@@ -0,0 +1 @@
Versions/Current/Headers
+1
View File
@@ -0,0 +1 @@
Versions/Current/Modules
+1
View File
@@ -0,0 +1 @@
Versions/Current/PrivateHeaders
+1
View File
@@ -0,0 +1 @@
Versions/Current/Realm
+1
View File
@@ -0,0 +1 @@
Versions/Current/Resources
@@ -0,0 +1,364 @@
////////////////////////////////////////////////////////////////////////////
//
// 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 <Foundation/Foundation.h>
#import <Realm/RLMCollection.h>
#import <Realm/RLMDefines.h>
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<ObjectType *><ObjectType> *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<RLMCollection, NSFastEnumeration>
#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<NSFastEnumeration>)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
@@ -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 <Realm/RLMDefines.h>
RLM_ASSUME_NONNULL_BEGIN
@class RLMRealm, RLMResults, RLMObject, RLMSortDescriptor, RLMNotificationToken;
/**
A homogenous collection of `RLMObject`s like `RLMArray` or `RLMResults`.
*/
@protocol RLMCollection <NSFastEnumeration>
@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<RLMCollection> collection))block RLM_WARN_UNUSED_RESULT;
@end
RLM_ASSUME_NONNULL_END
@@ -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 <Foundation/Foundation.h>
#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 <realm/data_type.hpp>
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;
@@ -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 <Foundation/Foundation.h>
@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 <RLMObjectType: RLMObject *>
#define RLM_GENERIC_RETURN <RLMObjectType>
#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
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMDefines.h>
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
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMObjectBase.h>
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<X>`, 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<X>`, 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<ObjectType *><ObjectType> *arrayOfObjectTypes;
*/
#define RLM_ARRAY_TYPE(RLM_OBJECT_SUBCLASS)\
@protocol RLM_OBJECT_SUBCLASS <NSObject> \
@end
RLM_ASSUME_NONNULL_END
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMDefines.h>
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
@@ -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 <Realm/RLMObject.h>
@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);
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMDefines.h>
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<NSCopying>
#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 <NSCopying>)propertyName;
/**
Returns YES if equal to objectSchema
*/
- (BOOL)isEqualToObjectSchema:(RLMObjectSchema *)objectSchema;
@end
RLM_ASSUME_NONNULL_END
@@ -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
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMConstants.h>
#import <Realm/RLMDefines.h>
RLM_ASSUME_NONNULL_BEGIN
/// :nodoc:
@protocol RLMInt
@end
/// :nodoc:
@protocol RLMBool
@end
/// :nodoc:
@protocol RLMDouble
@end
/// :nodoc:
@protocol RLMFloat
@end
/// :nodoc:
@interface NSNumber ()<RLMInt, RLMBool, RLMDouble, RLMFloat>
@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
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMDefines.h>
@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<NSFastEnumeration>)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
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMRealm.h>
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<NSCopying>
#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
@@ -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 <Realm/RLMRealm.h>
#import <Realm/RLMObjectSchema.h>
#import <Realm/RLMProperty.h>
@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
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMCollection.h>
#import <Realm/RLMDefines.h>
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<RLMCollection, NSFastEnumeration>
#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
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMDefines.h>
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<NSCopying>
#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 <NSCopying>)className;
/**
Returns YES if equal to schema
*/
- (BOOL)isEqualToSchema:(RLMSchema *)schema;
@end
RLM_ASSUME_NONNULL_END
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMArray.h>
#import <Realm/RLMMigration.h>
#import <Realm/RLMObject.h>
#import <Realm/RLMObjectSchema.h>
#import <Realm/RLMPlatform.h>
#import <Realm/RLMProperty.h>
#import <Realm/RLMRealm.h>
#import <Realm/RLMRealmConfiguration.h>
#import <Realm/RLMResults.h>
#import <Realm/RLMSchema.h>
@@ -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"
}
}
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMDefines.h>
@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
@@ -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 <Realm/RLMArray.h>
@interface RLMArray ()
- (instancetype)initWithObjectClassName:(NSString *)objectClassName;
- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth;
@end
@@ -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 <Foundation/Foundation.h>
@class RLMArray;
// A base class for Swift generic Lists to make it possible to interact with
// them from obj-c
@interface RLMListBase : NSObject <NSFastEnumeration>
@property (nonatomic, strong) RLMArray *_rlmArray;
- (instancetype)initWithArray:(RLMArray *)array;
@end
@@ -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 <Realm/RLMMigration.h>
#import <Realm/RLMObjectBase.h>
#import <Realm/RLMRealm.h>
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
@@ -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 <Realm/RLMDefines.h>
#import <Realm/RLMObjectSchema.h>
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
@@ -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 <Foundation/Foundation.h>
#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<typename T> class BasicRowExpr;
using RowExpr = BasicRowExpr<Table>;
}
// 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
@@ -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 <Realm/RLMObject.h>
// 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
@@ -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 <Foundation/Foundation.h>
#import <Realm/RLMConstants.h>
@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
@@ -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 <Realm/RLMProperty.h>
#import <objc/runtime.h>
@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
@@ -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 <Realm/RLMRealmConfiguration.h>
@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);
@@ -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 <Foundation/Foundation.h>
#import <memory>
#import <string>
@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<realm::BindingContext> RLMCreateBindingContext(RLMRealm *realm);
@@ -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 <Realm/RLMRealm.h>
@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
@@ -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 <Realm/RLMResults.h>
@class RLMObjectSchema;
@interface RLMResults ()
@property (nonatomic, unsafe_unretained) RLMObjectSchema *objectSchema;
@end
@@ -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 <Realm/RLMSchema.h>
#import <Realm/RLMDefines.h>
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
Binary file not shown.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>14F27</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>Realm</string>
<key>CFBundleIdentifier</key>
<string>io.Realm.Realm</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Realm</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>0.98.4</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>0.98.4</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>7C1002</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>15C43</string>
<key>DTSDKName</key>
<string>macosx10.11</string>
<key>DTXcode</key>
<string>0721</string>
<key>DTXcodeBuild</key>
<string>7C1002</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2014 Realm. All rights reserved.</string>
<key>UIDeviceFamily</key>
<array>
<integer>3</integer>
<integer>2</integer>
<integer>1</integer>
<integer>4</integer>
</array>
</dict>
</plist>
@@ -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.
@@ -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
+1
View File
@@ -0,0 +1 @@
A
+1
View File
@@ -0,0 +1 @@
Versions/Current/Headers
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more