This commit is contained in:
Pascal Edmond committed 2016-01-12 14:15:59 +01:00
commit fe2be594be
61 files changed
+2884 -1734

No files matched your search

+86 -1
View File
@@ -1,6 +1,91 @@
Release Notes
=============
## 0.39.0
Released January 11, 2016
**Breaking Changes**
- Removed partial update introduced in 0.38.0.
## 0.38.2
Released January 10, 2016
**Fixed**
- Preconditions on invalid statements arguments are restored.
## 0.38.1
Released January 10, 2016
**New**
- Various [performance improvements](https://github.com/groue/GRDB.swift/wiki/Performance)
## 0.38.0
Released January 8, 2016
**New**
- `Record.update()` and `DatabasePersistable.update()` can execute partial updates:
```swift
try person.update(db) // Full update
try person.update(db, columns: ["age"]) // Only updates the age column
```
**Breaking Changes**
- `Statement.arguments` is no longer optional.
- Your Record subclasses and DatabasePersistable types that provide custom implementation of `update` must use the signature below:
```swift
func update(db: Database, columns: [String]? = nil) throws
```
## 0.37.1
Released January 7, 2016
**Fixed**
- Remove method `fromRow()` from NSData, NSDate, NSNull, NSNumber, NSString and NSURL, which should have been removed in v0.36.0.
## 0.37.0
Released January 7, 2016
**Fixed**
- A named argument such as `:name` can now be used several times in a statement.
- Validation of statement arguments is much more solid (and tested).
**New**
- `Database.execute()` can now execute several statements separated by a semicolon.
- `Statement.validateArguments(_)` throws an error if the arguments parameter doesn't match the prepared statement:
```swift
let statement = try db.selectStatement("SELECT * FROM persons WHERE id = ?")
// OK
try statement.validateArguments([1])
// Error: wrong number of statement arguments: 2
try statement.validateArguments([1, 2])
```
**Breaking Changes**
- `Database.executeMultiStatement(sql)` has been removed. To execute several SQL statements separated by a semicolon, use `Database.execute()` instead.
## 0.36.0
Released December 28, 2015
@@ -485,7 +570,7 @@ Released August 18, 2015
- `RowModel.exists(db)` returns whether a row model has a matching row in the database.
- `Statement.arguments` property gains a public setter.
- `Database.executeMultiple(sql)` can execute several SQL statements separated by a semi-colon ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
- `Database.executeMultiStatement(sql)` can execute several SQL statements separated by a semi-colon ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
**Breaking changes**
@@ -17,7 +17,6 @@
562FF9F21BCE914E00759400 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9F11BCE914E00759400 /* Person.swift */; };
56FCB3691C21210B00305D10 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3421C21210B00305D10 /* Configuration.swift */; };
56FCB36A1C21210B00305D10 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3431C21210B00305D10 /* Database.swift */; };
56FCB36B1C21210B00305D10 /* DatabaseChanges.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3441C21210B00305D10 /* DatabaseChanges.swift */; };
56FCB36C1C21210B00305D10 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3451C21210B00305D10 /* DatabaseError.swift */; };
56FCB36D1C21210B00305D10 /* DatabaseQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3461C21210B00305D10 /* DatabaseQueue.swift */; };
56FCB36E1C21210B00305D10 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3471C21210B00305D10 /* DatabaseValue.swift */; };
@@ -27,10 +26,7 @@
56FCB3721C21210B00305D10 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB34C1C21210B00305D10 /* RowConvertible.swift */; };
56FCB3731C21210B00305D10 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB34D1C21210B00305D10 /* SQLiteStatementConvertible.swift */; };
56FCB3741C21210B00305D10 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB34E1C21210B00305D10 /* Row.swift */; };
56FCB3751C21210B00305D10 /* SelectStatement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB34F1C21210B00305D10 /* SelectStatement.swift */; };
56FCB3761C21210B00305D10 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3501C21210B00305D10 /* Statement.swift */; };
56FCB3771C21210B00305D10 /* StatementArguments.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3511C21210B00305D10 /* StatementArguments.swift */; };
56FCB3781C21210B00305D10 /* UpdateStatement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3521C21210B00305D10 /* UpdateStatement.swift */; };
56FCB3791C21210B00305D10 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3541C21210B00305D10 /* CGFloat.swift */; };
56FCB37A1C21210B00305D10 /* DatabaseCoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3561C21210B00305D10 /* DatabaseCoder.swift */; };
56FCB37B1C21210B00305D10 /* DatabaseDateComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3571C21210B00305D10 /* DatabaseDateComponents.swift */; };
@@ -64,7 +60,6 @@
562FF9F41BCE930C00759400 /* GRDBDemoiOS7-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBDemoiOS7-Bridging-Header.h"; sourceTree = "<group>"; };
56FCB3421C21210B00305D10 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = "<group>"; };
56FCB3431C21210B00305D10 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
56FCB3441C21210B00305D10 /* DatabaseChanges.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseChanges.swift; sourceTree = "<group>"; };
56FCB3451C21210B00305D10 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = "<group>"; };
56FCB3461C21210B00305D10 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = "<group>"; };
56FCB3471C21210B00305D10 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = "<group>"; };
@@ -74,10 +69,7 @@
56FCB34C1C21210B00305D10 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
56FCB34D1C21210B00305D10 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = "<group>"; };
56FCB34E1C21210B00305D10 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = "<group>"; };
56FCB34F1C21210B00305D10 /* SelectStatement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SelectStatement.swift; sourceTree = "<group>"; };
56FCB3501C21210B00305D10 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = "<group>"; };
56FCB3511C21210B00305D10 /* StatementArguments.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArguments.swift; sourceTree = "<group>"; };
56FCB3521C21210B00305D10 /* UpdateStatement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpdateStatement.swift; sourceTree = "<group>"; };
56FCB3541C21210B00305D10 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = "<group>"; };
56FCB3561C21210B00305D10 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = "<group>"; };
56FCB3571C21210B00305D10 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = "<group>"; };
@@ -202,16 +194,12 @@
children = (
56FCB3421C21210B00305D10 /* Configuration.swift */,
56FCB3431C21210B00305D10 /* Database.swift */,
56FCB3441C21210B00305D10 /* DatabaseChanges.swift */,
56FCB3451C21210B00305D10 /* DatabaseError.swift */,
56FCB3461C21210B00305D10 /* DatabaseQueue.swift */,
56FCB3471C21210B00305D10 /* DatabaseValue.swift */,
56FCB3481C21210B00305D10 /* Protocols */,
56FCB34E1C21210B00305D10 /* Row.swift */,
56FCB34F1C21210B00305D10 /* SelectStatement.swift */,
56FCB3501C21210B00305D10 /* Statement.swift */,
56FCB3511C21210B00305D10 /* StatementArguments.swift */,
56FCB3521C21210B00305D10 /* UpdateStatement.swift */,
);
path = Core;
sourceTree = "<group>";
@@ -351,8 +339,6 @@
buildActionMask = 2147483647;
files = (
56FCB3821C21210B00305D10 /* NSURL.swift in Sources */,
56FCB3781C21210B00305D10 /* UpdateStatement.swift in Sources */,
56FCB3771C21210B00305D10 /* StatementArguments.swift in Sources */,
56FCB3881C21210B00305D10 /* RawRepresentable.swift in Sources */,
56FCB3841C21210B00305D10 /* StatementArguments+Foundation.swift in Sources */,
56FCB37A1C21210B00305D10 /* DatabaseCoder.swift in Sources */,
@@ -377,7 +363,6 @@
56FCB3861C21210B00305D10 /* Migration.swift in Sources */,
56FCB3761C21210B00305D10 /* Statement.swift in Sources */,
56FCB36C1C21210B00305D10 /* DatabaseError.swift in Sources */,
56FCB3751C21210B00305D10 /* SelectStatement.swift in Sources */,
56FCB3811C21210B00305D10 /* NSString.swift in Sources */,
56FCB36F1C21210B00305D10 /* DatabasePersistable.swift in Sources */,
562FF9951BCE8FA400759400 /* AppDelegate.swift in Sources */,
@@ -386,7 +371,6 @@
56FCB37B1C21210B00305D10 /* DatabaseDateComponents.swift in Sources */,
56FCB3871C21210B00305D10 /* Record.swift in Sources */,
56FCB3721C21210B00305D10 /* RowConvertible.swift in Sources */,
56FCB36B1C21210B00305D10 /* DatabaseChanges.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -9,20 +9,26 @@
import Cocoa
import GRDB
let expectedRowCount = 100_000
let insertedRowCount = 20_000
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var dbQueue: DatabaseQueue!
func applicationDidFinishLaunching(aNotification: NSNotification) {
let databasePath = NSBundle.mainBundle().pathForResource("ProfilingDatabase", ofType: "sqlite")!
dbQueue = try! DatabaseQueue(path: databasePath)
testValueAtIndexPerformance()
testValueNamedPerformance()
testRecordPerformance()
testKeyValueCodingPerformance()
fetchPositionalValues()
fetchNamedValues()
fetchRecords()
insertPositionalValues()
insertNamedValues()
insertRecords()
}
func testValueAtIndexPerformance() {
func fetchPositionalValues() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("ProfilingDatabase", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
var count = 0
dbQueue.inDatabase { db in
for row in Row.fetch(db, "SELECT * FROM items") {
let _: Int = row.value(atIndex: 0)
@@ -35,11 +41,20 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let _: Int = row.value(atIndex: 7)
let _: Int = row.value(atIndex: 8)
let _: Int = row.value(atIndex: 9)
count += 1
}
}
assert(count == expectedRowCount)
}
func testValueNamedPerformance() {
func fetchNamedValues() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("ProfilingDatabase", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
var count = 0
dbQueue.inDatabase { db in
for row in Row.fetch(db, "SELECT * FROM items") {
let _: Int = row.value(named: "i0")
@@ -52,35 +67,117 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let _: Int = row.value(named: "i7")
let _: Int = row.value(named: "i8")
let _: Int = row.value(named: "i9")
count += 1
}
}
assert(count == expectedRowCount)
}
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")
}
assert(items.count == expectedRowCount)
assert(items[0].i0 == 0)
assert(items[1].i1 == 1)
assert(items[expectedRowCount-1].i9 == expectedRowCount-1)
}
func insertPositionalValues() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
assert(Int.fetchOne(db, "SELECT COUNT(*) FROM items")! == insertedRowCount)
assert(Int.fetchOne(db, "SELECT MIN(i0) FROM items")! == 0)
assert(Int.fetchOne(db, "SELECT MAX(i9) FROM items")! == insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
try! dbQueue.inTransaction { db in
let statement = try! db.updateStatement("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)")
for i in 0..<insertedRowCount {
try statement.execute(arguments: [i, i, i, i, i, i, i, i, i, i])
}
return .Commit
}
}
func testRecordPerformance() {
let records = dbQueue.inDatabase { db in
PerformanceRecord.fetchAll(db, "SELECT * FROM items")
func insertNamedValues() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
assert(Int.fetchOne(db, "SELECT COUNT(*) FROM items")! == insertedRowCount)
assert(Int.fetchOne(db, "SELECT MIN(i0) FROM items")! == 0)
assert(Int.fetchOne(db, "SELECT MAX(i9) FROM items")! == insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
try! dbQueue.inTransaction { db in
let statement = try! db.updateStatement("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (:i0, :i1, :i2, :i3, :i4, :i5, :i6, :i7, :i8, :i9)")
for i in 0..<insertedRowCount {
try statement.execute(arguments: ["i0": i, "i1": i, "i2": i, "i3": i, "i4": i, "i5": i, "i6": i, "i7": i, "i8": i, "i9": i])
}
return .Commit
}
assert(records[4].i2 == 1)
assert(records[4].i3 == 0)
assert(records[5].i2 == 2)
assert(records[5].i3 == 1)
}
func testKeyValueCodingPerformance() {
let records = dbQueue.inDatabase { db in
Row.fetch(db, "SELECT * FROM items").map { row in
PerformanceObjCRecord(dictionary: row.toNSDictionary())
func insertRecords() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
assert(Int.fetchOne(db, "SELECT COUNT(*) FROM items")! == insertedRowCount)
assert(Int.fetchOne(db, "SELECT MIN(i0) FROM items")! == 0)
assert(Int.fetchOne(db, "SELECT MAX(i9) FROM items")! == insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
try! dbQueue.inTransaction { db in
for i in 0..<insertedRowCount {
try Item(i0: i, i1: i, i2: i, i3: i, i4: i, i5: i, i6: i, i7: i, i8: i, i9: i).insert(db)
}
return .Commit
}
assert(records[4].i2!.intValue == 1)
assert(records[4].i3!.intValue == 0)
assert(records[5].i2!.intValue == 2)
assert(records[5].i3!.intValue == 1)
}
}
class PerformanceRecord : Record {
class Item : Record {
var i0: Int?
var i1: Int?
var i2: Int?
@@ -92,10 +189,25 @@ class PerformanceRecord : Record {
var i8: Int?
var i9: Int?
init(i0: Int?, i1: Int?, i2: Int?, i3: Int?, i4: Int?, i5: Int?, i6: Int?, i7: Int?, i8: Int?, i9: Int?) {
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
super.init()
}
// Record
override class func databaseTableName() -> String {
return "items"
}
required init(_ row: Row) {
required init(_ row: GRDB.Row) {
i0 = row.value(named: "i0")
i1 = row.value(named: "i1")
i2 = row.value(named: "i2")
@@ -108,25 +220,8 @@ class PerformanceRecord : Record {
i9 = row.value(named: "i9")
super.init(row)
}
}
class PerformanceObjCRecord : NSObject {
var i0: NSNumber?
var i1: NSNumber?
var i2: NSNumber?
var i3: NSNumber?
var i4: NSNumber?
var i5: NSNumber?
var i6: NSNumber?
var i7: NSNumber?
var i8: NSNumber?
var i9: NSNumber?
init(dictionary: NSDictionary) {
super.init()
for (key, value) in dictionary {
setValue(value, forKey: key as! String)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["i0": i0, "i1": i1, "i2": i2, "i3": i3, "i4": i4, "i5": i5, "i6": i6, "i7": i7, "i8": i8, "i9": i9]
}
}
+3 -1
View File
@@ -18,7 +18,9 @@ class GRDBTestCase: XCTestCase {
super.setUp()
sqlQueries = []
databasePath = "/tmp/GRDB.sqlite"
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)
}
@@ -1,102 +0,0 @@
import XCTest
class FMDBPerformanceTests: XCTestCase {
func testValueAtIndexPerformance() {
// Here we test the extraction of values by column index.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
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)
}
}
}
}
}
func testValueNamedPerformance() {
// Here we test the extraction of values by column name.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
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")
}
}
}
}
}
func testRecordPerformance() {
// Here we test the loading of an array of Records.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
var records = [PerformanceRecord]()
dbQueue.inDatabase { db in
if let rs = db.executeQuery("SELECT * FROM items", withArgumentsInArray: nil) {
while rs.next() {
let dictionary = rs.resultDictionary()
let record = PerformanceRecord(dictionary: dictionary)
records.append(record)
}
}
}
XCTAssertEqual(records[4].i2, 1)
XCTAssertEqual(records[4].i3, 0)
XCTAssertEqual(records[5].i2, 2)
XCTAssertEqual(records[5].i3, 1)
}
}
func testKeyValueCodingPerformance() {
// Here we test the loading of an array of KVC-based objects.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
var records = [PerformanceObjCRecord]()
dbQueue.inDatabase { db in
if let rs = db.executeQuery("SELECT * FROM items", withArgumentsInArray: nil) {
while rs.next() {
records.append(PerformanceObjCRecord(dictionary: rs.resultDictionary()))
}
}
}
XCTAssertEqual(records[4].i2!.intValue, 1)
XCTAssertEqual(records[4].i3!.intValue, 0)
XCTAssertEqual(records[5].i2!.intValue, 2)
XCTAssertEqual(records[5].i3!.intValue, 1)
}
}
}
@@ -0,0 +1,94 @@
import XCTest
import GRDB
import SQLite
private let expectedRowCount = 100_000
/// Here we test the extraction of values by column name.
class FetchNamedValuesTests: XCTestCase {
func testFMDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
var count = 0
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")
count += 1
}
}
}
XCTAssertEqual(count, expectedRowCount)
}
}
func testGRDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
measureBlock {
var count = 0
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")
count += 1
}
}
XCTAssertEqual(count, expectedRowCount)
}
}
func testSQLiteSwift() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
self.measureBlock {
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]
count += 1
}
XCTAssertEqual(count, expectedRowCount)
}
}
}
Binary file not shown.
@@ -0,0 +1,136 @@
import XCTest
import GRDB
import SQLite
private let expectedRowCount = 100_000
/// Here we test the extraction of values by column index.
class FetchPositionalValuesTests: XCTestCase {
func testSQLite() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
var connection: COpaquePointer = nil
sqlite3_open_v2(databasePath, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil)
self.measureBlock {
var count = 0
var statement: COpaquePointer = nil
sqlite3_prepare_v2(connection, "SELECT * FROM items", -1, &statement, nil)
loop: while true {
switch sqlite3_step(statement) {
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)
break
default:
XCTFail()
}
count += 1
}
sqlite3_finalize(statement)
XCTAssertEqual(count, expectedRowCount)
}
sqlite3_close(connection)
}
func testFMDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
var count = 0
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)
count += 1
}
}
}
XCTAssertEqual(count, expectedRowCount)
}
}
func testGRDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
measureBlock {
var count = 0
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)
count += 1
}
}
XCTAssertEqual(count, expectedRowCount)
}
}
func testSQLiteSwift() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
self.measureBlock {
var count = 0
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)
count += 1
}
XCTAssertEqual(count, expectedRowCount)
}
}
}
@@ -0,0 +1,159 @@
import XCTest
import GRDB
import SQLite
import CoreData
private let expectedRowCount = 100_000
/// Here we test the extraction of models from rows
class FetchRecordTests: XCTestCase {
func testSQLite() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
var connection: COpaquePointer = nil
sqlite3_open_v2(databasePath, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil)
self.measureBlock {
var statement: COpaquePointer = nil
sqlite3_prepare_v2(connection, "SELECT * FROM items", -1, &statement, nil)
let columnNames = (Int32(0)..<10).map { String.fromCString(sqlite3_column_name(statement, $0))! }
let index0 = Int32(columnNames.indexOf("i0")!)
let index1 = Int32(columnNames.indexOf("i1")!)
let index2 = Int32(columnNames.indexOf("i2")!)
let index3 = Int32(columnNames.indexOf("i3")!)
let index4 = Int32(columnNames.indexOf("i4")!)
let index5 = Int32(columnNames.indexOf("i5")!)
let index6 = Int32(columnNames.indexOf("i6")!)
let index7 = Int32(columnNames.indexOf("i7")!)
let index8 = Int32(columnNames.indexOf("i8")!)
let index9 = Int32(columnNames.indexOf("i9")!)
var items = [Item]()
loop: while true {
switch sqlite3_step(statement) {
case 101 /*SQLITE_DONE*/:
break loop
case 100 /*SQLITE_ROW*/:
let item = Item(
i0: Int(sqlite3_column_int64(statement, index0)),
i1: Int(sqlite3_column_int64(statement, index1)),
i2: Int(sqlite3_column_int64(statement, index2)),
i3: Int(sqlite3_column_int64(statement, index3)),
i4: Int(sqlite3_column_int64(statement, index4)),
i5: Int(sqlite3_column_int64(statement, index5)),
i6: Int(sqlite3_column_int64(statement, index6)),
i7: Int(sqlite3_column_int64(statement, index7)),
i8: Int(sqlite3_column_int64(statement, index8)),
i9: Int(sqlite3_column_int64(statement, index9)))
items.append(item)
break
default:
XCTFail()
}
}
sqlite3_finalize(statement)
XCTAssertEqual(items.count, expectedRowCount)
XCTAssertEqual(items[0].i0, 0)
XCTAssertEqual(items[1].i1, 1)
XCTAssertEqual(items[expectedRowCount-1].i9, expectedRowCount-1)
}
sqlite3_close(connection)
}
func testFMDB() {
// Here we test the loading of an array of Records.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
var items = [Item]()
dbQueue.inDatabase { db in
if let rs = db.executeQuery("SELECT * FROM items", withArgumentsInArray: nil) {
while rs.next() {
let item = Item(dictionary: rs.resultDictionary())
items.append(item)
}
}
}
XCTAssertEqual(items.count, expectedRowCount)
XCTAssertEqual(items[0].i0, 0)
XCTAssertEqual(items[1].i1, 1)
XCTAssertEqual(items[expectedRowCount-1].i9, expectedRowCount-1)
}
}
func testGRDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
measureBlock {
let items = dbQueue.inDatabase { db in
Item.fetchAll(db, "SELECT * FROM items")
}
XCTAssertEqual(items.count, expectedRowCount)
XCTAssertEqual(items[0].i0, 0)
XCTAssertEqual(items[1].i1, 1)
XCTAssertEqual(items[expectedRowCount-1].i9, expectedRowCount-1)
}
}
func testSQLiteSwift() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
self.measureBlock {
var items = [Item]()
for row in try! db.prepare(itemsTable) {
let item = Item(
i0: row[i0Column],
i1: row[i1Column],
i2: row[i2Column],
i3: row[i3Column],
i4: row[i4Column],
i5: row[i5Column],
i6: row[i6Column],
i7: row[i7Column],
i8: row[i8Column],
i9: row[i9Column])
items.append(item)
}
XCTAssertEqual(items.count, expectedRowCount)
XCTAssertEqual(items[0].i0, 0)
XCTAssertEqual(items[1].i1, 1)
XCTAssertEqual(items[expectedRowCount-1].i9, expectedRowCount-1)
}
}
func testCoreData() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceCoreDataTests", ofType: "sqlite")!
let modelURL = NSBundle(forClass: self.dynamicType).URLForResource("PerformanceModel", withExtension: "momd")!
let mom = NSManagedObjectModel(contentsOfURL: modelURL)!
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
try! psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: NSURL(fileURLWithPath: databasePath), options: nil)
let moc = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
moc.persistentStoreCoordinator = psc
measureBlock {
let request = NSFetchRequest(entityName: "Item")
let items = try! moc.executeFetchRequest(request)
for item in items {
item.valueForKey("i0")
item.valueForKey("i1")
item.valueForKey("i2")
item.valueForKey("i3")
item.valueForKey("i4")
item.valueForKey("i5")
item.valueForKey("i6")
item.valueForKey("i7")
item.valueForKey("i8")
item.valueForKey("i9")
}
XCTAssertEqual(items.count, expectedRowCount)
}
}
}
@@ -1,104 +0,0 @@
import XCTest
import GRDB
class GRDBPerformanceTests: XCTestCase {
// This is not a test, but a function which generates the FetchPerformanceTests.sqlite resource.
func populateDatabase() {
let databasePath = "/tmp/FetchPerformanceTests.sqlite"
do {
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inTransaction { db in
try db.execute("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
for i in 0..<100_000 {
try db.execute("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)", arguments: [i%1, i%2, i%3, i%4, i%5, i%6, i%7, i%8, i%9, i%10])
}
return .Commit
}
}
}
func testValueAtIndexPerformance() {
// Here we test the extraction of values by column index.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
self.measureBlock {
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)
}
}
}
}
func testValueNamedPerformance() {
// Here we test the extraction of values by column name.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
self.measureBlock {
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")
}
}
}
}
func testRecordPerformance() {
// Here we test the loading of an array of Records.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
self.measureBlock {
let records = dbQueue.inDatabase { db in
PerformanceRecord.fetchAll(db, "SELECT * FROM items")
}
XCTAssertEqual(records[4].i2, 1)
XCTAssertEqual(records[4].i3, 0)
XCTAssertEqual(records[5].i2, 2)
XCTAssertEqual(records[5].i3, 1)
}
}
func testKeyValueCodingPerformance() {
// Here we test the loading of an array of KVC-based objects.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
self.measureBlock {
let records = dbQueue.inDatabase { db in
Row.fetch(db, "SELECT * FROM items").map { row in
PerformanceObjCRecord(dictionary: row.toNSDictionary())
}
}
XCTAssertEqual(records[4].i2!.intValue, 1)
XCTAssertEqual(records[4].i3!.intValue, 0)
XCTAssertEqual(records[5].i2!.intValue, 2)
XCTAssertEqual(records[5].i3!.intValue, 1)
}
}
}
@@ -0,0 +1,119 @@
import XCTest
import GRDB
import SQLite
private let insertedRowCount = 20_000
// Here we insert rows, referencing statement arguments by name.
class InsertNamedValuesTests: XCTestCase {
func testFMDB() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
measureBlock {
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
db.executeStatements("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
dbQueue.inTransaction { (db, rollback) -> Void in
db.setShouldCacheStatements(true)
for i in 0..<insertedRowCount {
db.executeUpdate("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (:i0, :i1, :i2, :i3, :i4, :i5, :i6, :i7, :i8, :i9)", withParameterDictionary: ["i0": i, "i1": i, "i2": i, "i3": i, "i4": i, "i5": i, "i6": i, "i7": i, "i8": i, "i9": i])
}
}
}
}
func testGRDB() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
measureBlock {
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
try! dbQueue.inTransaction { db in
let statement = try! db.updateStatement("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (:i0, :i1, :i2, :i3, :i4, :i5, :i6, :i7, :i8, :i9)")
for i in 0..<insertedRowCount {
try statement.execute(arguments: ["i0": i, "i1": i, "i2": i, "i3": i, "i4": i, "i5": i, "i6": i, "i7": i, "i8": i, "i9": i])
}
return .Commit
}
}
}
func testSQLiteSwift() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
measureBlock {
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let db = try! Connection(databasePath)
try! db.run(itemsTable.create { t in
t.column(i0Column)
t.column(i1Column)
t.column(i2Column)
t.column(i3Column)
t.column(i4Column)
t.column(i5Column)
t.column(i6Column)
t.column(i7Column)
t.column(i8Column)
t.column(i9Column)
})
try! db.transaction {
for i in 0..<insertedRowCount {
try db.run(itemsTable.insert(
i0Column <- i,
i1Column <- i,
i2Column <- i,
i3Column <- i,
i4Column <- i,
i5Column <- i,
i6Column <- i,
i7Column <- i,
i8Column <- i,
i9Column <- i))
}
}
}
}
}
@@ -0,0 +1,153 @@
import XCTest
import GRDB
import SQLite
private let insertedRowCount = 20_000
// Here we insert rows, referencing statement arguments by index.
class InsertPositionalValuesTests: XCTestCase {
func testSQLite() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
measureBlock {
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
var connection: COpaquePointer = nil
sqlite3_open_v2(databasePath, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil)
sqlite3_exec(connection, "CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)", nil, nil, nil)
sqlite3_exec(connection, "BEGIN TRANSACTION", nil, nil, nil)
var statement: COpaquePointer = nil
sqlite3_prepare_v2(connection, "INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)", -1, &statement, nil)
for i in Int64(0)..<Int64(insertedRowCount) {
sqlite3_reset(statement)
sqlite3_bind_int64(statement, 1, i)
sqlite3_bind_int64(statement, 2, i)
sqlite3_bind_int64(statement, 3, i)
sqlite3_bind_int64(statement, 4, i)
sqlite3_bind_int64(statement, 5, i)
sqlite3_bind_int64(statement, 6, i)
sqlite3_bind_int64(statement, 7, i)
sqlite3_bind_int64(statement, 8, i)
sqlite3_bind_int64(statement, 9, i)
sqlite3_bind_int64(statement, 10, i)
sqlite3_step(statement)
}
sqlite3_finalize(statement)
sqlite3_exec(connection, "COMMIT", nil, nil, nil)
sqlite3_close(connection)
}
}
func testFMDB() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
measureBlock {
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
db.executeStatements("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
dbQueue.inTransaction { (db, rollback) -> Void in
db.setShouldCacheStatements(true)
for i in 0..<insertedRowCount {
db.executeUpdate("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)", withArgumentsInArray: [i, i, i, i, i, i, i, i, i, i])
}
}
}
}
func testGRDB() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
measureBlock {
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
try! dbQueue.inTransaction { db in
let statement = try! db.updateStatement("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)")
for i in 0..<insertedRowCount {
try statement.execute(arguments: [i, i, i, i, i, i, i, i, i, i])
}
return .Commit
}
}
}
func testSQLiteSwift() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
measureBlock {
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let db = try! Connection(databasePath)
try! db.run(itemsTable.create { t in
t.column(i0Column)
t.column(i1Column)
t.column(i2Column)
t.column(i3Column)
t.column(i4Column)
t.column(i5Column)
t.column(i6Column)
t.column(i7Column)
t.column(i8Column)
t.column(i9Column)
})
try! db.transaction {
let stmt = try! db.prepare("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)")
for i in 0..<insertedRowCount {
try stmt.run(i, i, i, i, i, i, i, i, i, i)
}
}
}
}
}
@@ -0,0 +1,71 @@
import XCTest
import GRDB
import CoreData
private let insertedRowCount = 20_000
// Here we insert records.
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)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
measureBlock {
let _ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
try! dbQueue.inTransaction { db in
for i in 0..<insertedRowCount {
try Item(i0: i, i1: i, i2: i, i3: i, i4: i, i5: i, i6: i, i7: i, i8: i, i9: i).insert(db)
}
return .Commit
}
}
}
func testCoreData() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let modelURL = NSBundle(forClass: self.dynamicType).URLForResource("PerformanceModel", withExtension: "momd")!
let mom = NSManagedObjectModel(contentsOfURL: modelURL)!
measureBlock {
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
let store = try! psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: NSURL(fileURLWithPath: databasePath), options: nil)
let moc = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
moc.persistentStoreCoordinator = psc
for i in 0..<insertedRowCount {
let item = NSEntityDescription.insertNewObjectForEntityForName("Item", inManagedObjectContext: moc)
item.setValue(NSNumber(integer: i), forKey: "i0")
item.setValue(NSNumber(integer: i), forKey: "i1")
item.setValue(NSNumber(integer: i), forKey: "i2")
item.setValue(NSNumber(integer: i), forKey: "i3")
item.setValue(NSNumber(integer: i), forKey: "i4")
item.setValue(NSNumber(integer: i), forKey: "i5")
item.setValue(NSNumber(integer: i), forKey: "i6")
item.setValue(NSNumber(integer: i), forKey: "i7")
item.setValue(NSNumber(integer: i), forKey: "i8")
item.setValue(NSNumber(integer: i), forKey: "i9")
}
try! moc.save()
try! psc.removePersistentStore(store)
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
}
}
}
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="9525" systemVersion="15B42" minimumToolsVersion="Xcode 7.0">
<entity name="Item" representedClassName="ManagedItem" syncable="YES">
<attribute name="i0" optional="YES" attributeType="Integer 64" syncable="YES"/>
<attribute name="i1" optional="YES" attributeType="Integer 64" syncable="YES"/>
<attribute name="i2" optional="YES" attributeType="Integer 64" syncable="YES"/>
<attribute name="i3" optional="YES" attributeType="Integer 64" syncable="YES"/>
<attribute name="i4" optional="YES" attributeType="Integer 64" syncable="YES"/>
<attribute name="i5" optional="YES" attributeType="Integer 64" syncable="YES"/>
<attribute name="i6" optional="YES" attributeType="Integer 64" syncable="YES"/>
<attribute name="i7" optional="YES" attributeType="Integer 64" syncable="YES"/>
<attribute name="i8" optional="YES" attributeType="Integer 64" syncable="YES"/>
<attribute name="i9" optional="YES" attributeType="Integer 64" syncable="YES"/>
</entity>
<elements>
<element name="Item" positionX="-63" positionY="-18" width="128" height="195"/>
</elements>
</model>
@@ -1,68 +0,0 @@
import GRDB
class PerformanceRecord : Record {
var i0: Int?
var i1: Int?
var i2: Int?
var i3: Int?
var i4: Int?
var i5: Int?
var i6: Int?
var i7: Int?
var i8: Int?
var i9: Int?
// Record
required init(_ row: Row) {
i0 = row.value(named: "i0")
i1 = row.value(named: "i1")
i2 = row.value(named: "i2")
i3 = row.value(named: "i3")
i4 = row.value(named: "i4")
i5 = row.value(named: "i5")
i6 = row.value(named: "i6")
i7 = row.value(named: "i7")
i8 = row.value(named: "i8")
i9 = row.value(named: "i9")
super.init(row)
}
// FMDB
init(dictionary: [NSObject: AnyObject]) {
super.init()
if let n = dictionary["i0"] as? NSNumber { i0 = n.longValue }
if let n = dictionary["i1"] as? NSNumber { i1 = n.longValue }
if let n = dictionary["i2"] as? NSNumber { i2 = n.longValue }
if let n = dictionary["i3"] as? NSNumber { i3 = n.longValue }
if let n = dictionary["i4"] as? NSNumber { i4 = n.longValue }
if let n = dictionary["i5"] as? NSNumber { i5 = n.longValue }
if let n = dictionary["i6"] as? NSNumber { i6 = n.longValue }
if let n = dictionary["i7"] as? NSNumber { i7 = n.longValue }
if let n = dictionary["i8"] as? NSNumber { i8 = n.longValue }
if let n = dictionary["i9"] as? NSNumber { i9 = n.longValue }
}
}
class PerformanceObjCRecord : NSObject {
var i0: NSNumber?
var i1: NSNumber?
var i2: NSNumber?
var i3: NSNumber?
var i4: NSNumber?
var i5: NSNumber?
var i6: NSNumber?
var i7: NSNumber?
var i8: NSNumber?
var i9: NSNumber?
init(dictionary: NSDictionary) {
super.init()
for (key, value) in dictionary {
setValue(value, forKey: key as! String)
}
}
}
Binary file not shown.
@@ -0,0 +1,89 @@
import GRDB
import SQLite
// MARK:- SQLite
let itemsTable = Table("items")
let i0Column = Expression<Int>("i0")
let i1Column = Expression<Int>("i1")
let i2Column = Expression<Int>("i2")
let i3Column = Expression<Int>("i3")
let i4Column = Expression<Int>("i4")
let i5Column = Expression<Int>("i5")
let i6Column = Expression<Int>("i6")
let i7Column = Expression<Int>("i7")
let i8Column = Expression<Int>("i8")
let i9Column = Expression<Int>("i9")
// MARK:- GRDB
class Item : Record {
var i0: Int?
var i1: Int?
var i2: Int?
var i3: Int?
var i4: Int?
var i5: Int?
var i6: Int?
var i7: Int?
var i8: Int?
var i9: Int?
init(i0: Int?, i1: Int?, i2: Int?, i3: Int?, i4: Int?, i5: Int?, i6: Int?, i7: Int?, i8: Int?, i9: Int?) {
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
super.init()
}
override class func databaseTableName() -> String {
return "items"
}
required init(_ row: GRDB.Row) {
i0 = row.value(named: "i0")
i1 = row.value(named: "i1")
i2 = row.value(named: "i2")
i3 = row.value(named: "i3")
i4 = row.value(named: "i4")
i5 = row.value(named: "i5")
i6 = row.value(named: "i6")
i7 = row.value(named: "i7")
i8 = row.value(named: "i8")
i9 = row.value(named: "i9")
super.init(row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["i0": i0, "i1": i1, "i2": i2, "i3": i3, "i4": i4, "i5": i5, "i6": i6, "i7": i7, "i8": i8, "i9": i9]
}
}
// MARK:- FMDB
extension Item {
convenience init(dictionary: [NSObject: AnyObject]) {
self.init(
i0: (dictionary["i0"] as! NSNumber).longValue,
i1: (dictionary["i1"] as! NSNumber).longValue,
i2: (dictionary["i2"] as! NSNumber).longValue,
i3: (dictionary["i3"] as! NSNumber).longValue,
i4: (dictionary["i4"] as! NSNumber).longValue,
i5: (dictionary["i5"] as! NSNumber).longValue,
i6: (dictionary["i6"] as! NSNumber).longValue,
i7: (dictionary["i7"] as! NSNumber).longValue,
i8: (dictionary["i8"] as! NSNumber).longValue,
i9: (dictionary["i9"] as! NSNumber).longValue)
}
}
@@ -1,150 +0,0 @@
import XCTest
import SQLite
class StephenCelisSQLitePerformanceTests: XCTestCase {
func testValueAtIndexPerformance() {
// Here we test the extraction of values by column index.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
self.measureBlock {
// Column access by index requires raw SQL (unlike extraction of values by column name).
for row in 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)
}
}
}
func testValueNamedPerformance() {
// Here we test the extraction of values by column name.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
// Column access by name requires query builder (unlike extraction of values by column index).
let items = Table("items")
let i0 = Expression<Int>("i0")
let i1 = Expression<Int>("i1")
let i2 = Expression<Int>("i2")
let i3 = Expression<Int>("i3")
let i4 = Expression<Int>("i4")
let i5 = Expression<Int>("i5")
let i6 = Expression<Int>("i6")
let i7 = Expression<Int>("i7")
let i8 = Expression<Int>("i8")
let i9 = Expression<Int>("i9")
self.measureBlock {
for item in db.prepare(items) {
let _ = item[i0]
let _ = item[i1]
let _ = item[i2]
let _ = item[i3]
let _ = item[i4]
let _ = item[i5]
let _ = item[i6]
let _ = item[i7]
let _ = item[i8]
let _ = item[i9]
}
}
}
func testRecordPerformance() {
// Here we test the loading of an array of Records.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
// Column access by name requires query builder.
let items = Table("items")
let i0 = Expression<Int>("i0")
let i1 = Expression<Int>("i1")
let i2 = Expression<Int>("i2")
let i3 = Expression<Int>("i3")
let i4 = Expression<Int>("i4")
let i5 = Expression<Int>("i5")
let i6 = Expression<Int>("i6")
let i7 = Expression<Int>("i7")
let i8 = Expression<Int>("i8")
let i9 = Expression<Int>("i9")
self.measureBlock {
var records = [PerformanceRecord]()
for row in db.prepare(items) {
let dictionary = [
"i0": row[i0],
"i1": row[i1],
"i2": row[i2],
"i3": row[i3],
"i4": row[i4],
"i5": row[i5],
"i6": row[i6],
"i7": row[i7],
"i8": row[i8],
"i9": row[i9]] as [NSObject: AnyObject]
let record = PerformanceRecord(dictionary: dictionary)
records.append(record)
}
XCTAssertEqual(records[4].i2, 1)
XCTAssertEqual(records[4].i3, 0)
XCTAssertEqual(records[5].i2, 2)
XCTAssertEqual(records[5].i3, 1)
}
}
func testKeyValueCodingPerformance() {
// Here we test the loading of an array of KVC-based objects.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("FetchPerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
// Column access by name requires query builder.
let items = Table("items")
let i0 = Expression<Int>("i0")
let i1 = Expression<Int>("i1")
let i2 = Expression<Int>("i2")
let i3 = Expression<Int>("i3")
let i4 = Expression<Int>("i4")
let i5 = Expression<Int>("i5")
let i6 = Expression<Int>("i6")
let i7 = Expression<Int>("i7")
let i8 = Expression<Int>("i8")
let i9 = Expression<Int>("i9")
self.measureBlock {
var records = [PerformanceObjCRecord]()
for row in db.prepare(items) {
let dictionary = [
"i0": row[i0],
"i1": row[i1],
"i2": row[i2],
"i3": row[i3],
"i4": row[i4],
"i5": row[i5],
"i6": row[i6],
"i7": row[i7],
"i8": row[i8],
"i9": row[i9]] as [NSObject: AnyObject]
let record = PerformanceObjCRecord(dictionary: dictionary)
records.append(record)
}
XCTAssertEqual(records[4].i2!.intValue, 1)
XCTAssertEqual(records[4].i3!.intValue, 0)
XCTAssertEqual(records[5].i2!.intValue, 2)
XCTAssertEqual(records[5].i3!.intValue, 1)
}
}
}
@@ -1,37 +0,0 @@
import XCTest
@testable import GRDB
class DatabaseErrorFromStatementCreationTests: GRDBTestCase {
func testDatabaseErrorThrownBySelectStatementContainSQL() {
dbQueue.inDatabase { db in
do {
let _ = try SelectStatement(database: db, sql: "SELECT * FROM blah")
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 1)
XCTAssertEqual(error.message!, "no such table: blah")
XCTAssertEqual(error.sql!, "SELECT * FROM blah")
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT * FROM blah`: no such table: blah")
} catch {
XCTFail("\(error)")
}
}
}
func testDatabaseErrorThrownByUpdateStatementContainSQL() {
dbQueue.inDatabase { db in
do {
let _ = try UpdateStatement(database: db, sql: "UPDATE blah SET id = 12")
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 1)
XCTAssertEqual(error.message!, "no such table: blah")
XCTAssertEqual(error.sql!, "UPDATE blah SET id = 12")
XCTAssertEqual(error.description, "SQLite error 1 with statement `UPDATE blah SET id = 12`: no such table: blah")
} catch {
XCTFail("\(error)")
}
}
}
}
@@ -22,7 +22,7 @@ class DatabaseTests : GRDBTestCase {
try dbQueue.inDatabase { db in
XCTAssertFalse(db.tableExists("persons"))
XCTAssertFalse(db.tableExists("pets"))
try db.executeMultiStatement(
try db.execute(
"CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);" +
"CREATE TABLE pets (id INTEGER PRIMARY KEY, name TEXT, age INT);")
XCTAssertTrue(db.tableExists("persons"))
@@ -86,7 +86,7 @@ class DatabaseErrorTests: GRDBTestCase {
func testDatabaseErrorThrownByExecuteMultiStatementContainSQL() {
dbQueue.inDatabase { db in
do {
try db.executeMultiStatement(
try db.execute(
"CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);" +
"CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT);" +
"INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
@@ -94,8 +94,8 @@ class DatabaseErrorTests: GRDBTestCase {
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 19) // SQLITE_CONSTRAINT
XCTAssertEqual(error.message!, "FOREIGN KEY constraint failed")
XCTAssertEqual(error.sql!, "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT);INSERT INTO pets (masterId, name) VALUES (1, \'Bobby\')")
XCTAssertEqual(error.description, "SQLite error 19 with statement `CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT);INSERT INTO pets (masterId, name) VALUES (1, \'Bobby\')`: FOREIGN KEY constraint failed")
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
XCTAssertEqual(error.description, "SQLite error 19 with statement `INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')`: FOREIGN KEY constraint failed")
} catch {
XCTFail("\(error)")
}
@@ -3,23 +3,26 @@ import GRDB
struct PersistablePerson : DatabasePersistable {
var name: String?
var age: Int?
static func databaseTableName() -> String {
return "persons"
}
var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["name": name]
return ["name": name, "age": age]
}
}
class PersistablePersonClass : DatabasePersistable {
var id: Int64?
var name: String?
var age: Int?
init(id: Int64?, name: String?) {
init(id: Int64?, name: String?, age: Int?) {
self.id = id
self.name = name
self.age = age
}
static func databaseTableName() -> String {
@@ -27,7 +30,7 @@ class PersistablePersonClass : DatabasePersistable {
}
var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["id": id, "name": name]
return ["id": id, "name": name, "age": age]
}
func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
@@ -101,7 +104,8 @@ class DatabasePersistableTests: GRDBTestCase {
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"name NOT NULL " +
"name TEXT NOT NULL, " +
"age INT NOT NULL " +
")")
try db.execute(
"CREATE TABLE countries (" +
@@ -121,7 +125,7 @@ class DatabasePersistableTests: GRDBTestCase {
func testInsertPersistablePerson() {
assertNoError {
try dbQueue.inDatabase { db in
let person = PersistablePerson(name: "Arthur")
let person = PersistablePerson(name: "Arthur", age: 42)
try person.insert(db)
let rows = Row.fetchAll(db, "SELECT * FROM persons")
@@ -134,7 +138,7 @@ class DatabasePersistableTests: GRDBTestCase {
func testSavePersistablePerson() {
assertNoError {
try dbQueue.inDatabase { db in
let person = PersistablePerson(name: "Arthur")
let person = PersistablePerson(name: "Arthur", age: 42)
try person.save(db)
let rows = Row.fetchAll(db, "SELECT * FROM persons")
@@ -150,7 +154,7 @@ class DatabasePersistableTests: GRDBTestCase {
func testInsertPersistablePersonClass() {
assertNoError {
try dbQueue.inDatabase { db in
let person = PersistablePersonClass(id: nil, name: "Arthur")
let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42)
try person.insert(db)
let rows = Row.fetchAll(db, "SELECT * FROM persons")
@@ -164,9 +168,9 @@ class DatabasePersistableTests: GRDBTestCase {
func testUpdatePersistablePersonClass() {
assertNoError {
try dbQueue.inDatabase { db in
let person1 = PersistablePersonClass(id: nil, name: "Arthur")
let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42)
try person1.insert(db)
let person2 = PersistablePersonClass(id: nil, name: "Barbara")
let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39)
try person2.insert(db)
person1.name = "Craig"
@@ -185,7 +189,7 @@ class DatabasePersistableTests: GRDBTestCase {
func testSavePersistablePersonClass() {
assertNoError {
try dbQueue.inDatabase { db in
let person1 = PersistablePersonClass(id: nil, name: "Arthur")
let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42)
try person1.save(db)
var rows = Row.fetchAll(db, "SELECT * FROM persons")
@@ -193,7 +197,7 @@ class DatabasePersistableTests: GRDBTestCase {
XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!)
XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur")
let person2 = PersistablePersonClass(id: nil, name: "Barbara")
let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39)
try person2.save(db)
person1.name = "Craig"
@@ -222,9 +226,9 @@ class DatabasePersistableTests: GRDBTestCase {
func testDeletePersistablePersonClass() {
assertNoError {
try dbQueue.inDatabase { db in
let person1 = PersistablePersonClass(id: nil, name: "Arthur")
let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42)
try person1.insert(db)
let person2 = PersistablePersonClass(id: nil, name: "Barbara")
let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39)
try person2.insert(db)
try person1.delete(db)
@@ -240,7 +244,7 @@ class DatabasePersistableTests: GRDBTestCase {
func testExistsPersistablePersonClass() {
assertNoError {
try dbQueue.inDatabase { db in
let person = PersistablePersonClass(id: nil, name: "Arthur")
let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42)
try person.insert(db)
XCTAssertTrue(person.exists(db))
@@ -10,13 +10,6 @@ class FetchableParent : DatabaseValueConvertible, CustomStringConvertible {
return self.init()
}
// TODO: this implementation is mandatory to avoid a Swift compiler error.
// Either avoid it, or document it.
class func fromRow(row: Row) -> Self {
// TODO: nice fatal error in case of error
return fromDatabaseValue(row.databaseValues.first!)!
}
required init() {
}
@@ -148,4 +148,20 @@ class SelectStatementTests : GRDBTestCase {
}
}
}
func testDatabaseErrorThrownBySelectStatementContainSQL() {
dbQueue.inDatabase { db in
do {
let _ = try db.selectStatement("SELECT * FROM blah")
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 1)
XCTAssertEqual(error.message!, "no such table: blah")
XCTAssertEqual(error.sql!, "SELECT * FROM blah")
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT * FROM blah`: no such table: blah")
} catch {
XCTFail("\(error)")
}
}
}
}
@@ -0,0 +1,264 @@
//
// StatementTests.swift
// GRDB
//
// Created by Gwendal Roué on 06/01/2016.
// Copyright © 2016 Gwendal Roué. All rights reserved.
//
import XCTest
import GRDB
class StatementArgumentsTests: GRDBTestCase {
override func setUp() {
super.setUp()
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"firstName TEXT, " +
"lastName TEXT, " +
"age INT" +
")")
}
assertNoError {
try migrator.migrate(dbQueue)
}
}
func testPositionalStatementArgumentsValidation() {
assertNoError {
try dbQueue.inDatabase { db in
let statement = try db.updateStatement("INSERT INTO persons (firstName, age) VALUES (?, ?)")
do {
// Correct number of arguments
try statement.validateArguments(["foo", 1])
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments([])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Two few arguments
try statement.validateArguments(["foo"])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Two many arguments
try statement.validateArguments(["foo", 1, "bar"])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments([:])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Unmappable arguments
try statement.validateArguments(["firstName": "foo", "age": 1])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
}
}
}
func testNamedStatementArgumentsValidation() {
assertNoError {
try dbQueue.inDatabase { db in
let statement = try db.updateStatement("INSERT INTO persons (firstName, age) VALUES (:firstName, :age)")
do {
// Correct number of arguments
try statement.validateArguments(["foo", 1])
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// All arguments are mapped
try statement.validateArguments(["firstName": "foo", "age": 1])
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// All arguments are mapped
try statement.validateArguments(["firstName": "foo", "age": 1, "bar": "baz"])
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments([])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments(["foo"])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Too many arguments
try statement.validateArguments(["foo", 1, "baz"])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments([:])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments(["firstName": "foo"])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
}
}
}
func testReusedNamedStatementArgumentsValidation() {
assertNoError {
try dbQueue.inDatabase { db in
let statement = try db.updateStatement("INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)")
do {
try statement.execute(arguments: ["name": "foo", "age": 1])
let row = Row.fetchOne(db, "SELECT * FROM persons")!
XCTAssertEqual(row.value(named: "firstName") as String, "foo")
XCTAssertEqual(row.value(named: "lastName") as String, "foo")
XCTAssertEqual(row.value(named: "age") as Int, 1)
}
do {
// Correct number of arguments
try statement.validateArguments(["foo", 1])
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// All arguments are mapped
try statement.validateArguments(["name": "foo", "age": 1])
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// All arguments are mapped
try statement.validateArguments(["name": "foo", "age": 1, "bar": "baz"])
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments([])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments(["foo"])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Too many arguments
try statement.validateArguments(["foo", 1, "baz"])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments([:])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
// Missing arguments
try statement.validateArguments(["name": "foo"])
XCTFail("Expected error")
} catch let error as DatabaseError {
print(error)
} catch {
XCTFail("Unexpected error: \(error)")
}
}
}
}
}
@@ -163,4 +163,91 @@ class UpdateStatementTests : GRDBTestCase {
}
}
}
func testExecuteMultipleStatement() {
assertNoError {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE wines (name TEXT, color INT); CREATE TABLE books (name TEXT, age INT)")
XCTAssertTrue(db.tableExists("wines"))
XCTAssertTrue(db.tableExists("books"))
}
}
}
func testExecuteMultipleStatementWithNamedArguments() {
assertNoError {
try dbQueue.inTransaction { db in
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);",
arguments: ["age1": 41, "age2": 32])
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
return .Rollback
}
try dbQueue.inTransaction { db in
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);",
arguments: [41, 32])
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
return .Rollback
}
}
}
func testExecuteMultipleStatementWithReusedNamedArguments() {
assertNoError {
try dbQueue.inTransaction { db in
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', :age);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', :age);",
arguments: ["age": 41])
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons"), [41, 41])
return .Rollback
}
// // The test below fails because 41 in consumed by the first statement,
// // leaving no argument for the second statement.
// //
// // TODO? make it work
// try dbQueue.inTransaction { db in
// try db.execute(
// "INSERT INTO persons (name, age) VALUES ('Arthur', :age);" +
// "INSERT INTO persons (name, age) VALUES ('Arthur', :age);",
// arguments: [41])
// XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons"), [41, 41])
// return .Rollback
// }
}
}
func testExecuteMultipleStatementWithPositionalArguments() {
assertNoError {
try dbQueue.inTransaction { db in
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);",
arguments: [41, 32])
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
return .Rollback
}
}
}
func testDatabaseErrorThrownByUpdateStatementContainSQL() {
dbQueue.inDatabase { db in
do {
let _ = try db.updateStatement("UPDATE blah SET id = 12")
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 1)
XCTAssertEqual(error.message!, "no such table: blah")
XCTAssertEqual(error.sql!, "UPDATE blah SET id = 12")
XCTAssertEqual(error.description, "SQLite error 1 with statement `UPDATE blah SET id = 12`: no such table: blah")
} catch {
XCTFail("\(error)")
}
}
}
}
+169 -119
View File
@@ -1,6 +1,7 @@
// All tests in this file must crash.
//
// To run those tests, check the GRDBOSXTests and GRDBiOSTests membership.
// To run those tests, run the GRDBOSXCrashTests target, and verify that each
// test crashes with the expected error message.
import XCTest
import GRDB
@@ -69,7 +70,7 @@ struct IntConvertible: DatabaseValueConvertible {
self.int = int
}
var databaseValue: DatabaseValue {
return DatabaseValue(int64: Int64(int))
return int.databaseValue
}
static func fromDatabaseValue(databaseValue: DatabaseValue) -> IntConvertible? {
guard let int = Int.fromDatabaseValue(databaseValue) else {
@@ -99,13 +100,13 @@ class CrashTests: GRDBTestCase {
// MARK: - Migrations
func testMigrationNamesMustBeUnique() {
assertCrash("Already registered migration: \"foo\"") {
assertCrash("already registered migration: \"foo\"") {
var migrator = DatabaseMigrator()
migrator.registerMigration("foo") { db in }
migrator.registerMigration("foo") { db in }
}
}
// =========================================================================
// MARK: - Queue
@@ -141,7 +142,7 @@ class CrashTests: GRDBTestCase {
}
func testRowSequenceCanNotBeGeneratedOutsideOfDatabaseQueue() {
assertCrash("Database was not used on the correct queue.") {
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)")
@@ -152,7 +153,7 @@ class CrashTests: GRDBTestCase {
}
func testRowSequenceCanNotBeIteratedOutsideOfDatabaseQueue() {
assertCrash("Database was not used on the correct queue.") {
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)")
@@ -166,37 +167,129 @@ class CrashTests: GRDBTestCase {
// =========================================================================
// MARK: - Statements
func testExecuteDoesNotSupportMultipleStatement() {
assertCrash("Invalid SQL string: multiple statements found.") {
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); CREATE TABLE books (name TEXT, age INT)")
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try! db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur"])
}
}
assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', ?);`: wrong number of statement arguments: 0") {
try dbQueue.inTransaction { db in
do {
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);")
XCTFail("Expected Error")
} catch {
XCTAssertTrue(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age").isEmpty)
}
return .Rollback
}
}
assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', ?);`: wrong number of statement arguments: 0") {
try dbQueue.inTransaction { db in
do {
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);",
arguments: [41])
XCTFail("Expected Error")
} catch {
// Partial fail
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [41])
}
return .Rollback
}
}
assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', :age1);`: missing statement argument(s): age1") {
try dbQueue.inTransaction { db in
do {
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);")
XCTFail("Expected Error")
} catch {
XCTAssertTrue(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age").isEmpty)
}
return .Rollback
}
}
assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', :age2);`: missing statement argument(s): age2") {
try dbQueue.inTransaction { db in
do {
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);",
arguments: ["age1": 41])
XCTFail("Expected Error")
} catch {
// Partial fail
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [41])
}
return .Rollback
}
}
assertCrash("wrong number of statement arguments: 3") {
try dbQueue.inTransaction { db in
do {
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);",
arguments: [41, 32, 17])
XCTFail("Expected Error")
} catch {
// Partial fail
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
}
return .Rollback
}
}
assertCrash("wrong number of statement arguments: 3") {
try dbQueue.inTransaction { db in
do {
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);",
arguments: [41, 32, 17])
XCTFail("Expected Error")
} catch {
// Partial fail
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
}
return .Rollback
}
}
}
func testInvalidNamedBinding() {
assertCrash("Key not found in SQLite statement: `:XXX`") {
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: ["XXX": "foo", "name": "Arthur", "age": 41])
}
}
}
// =========================================================================
// MARK: - RecordWithoutDatabaseTableName
func testRecordWithoutDatabaseTableNameCanNotBeFetchedByID() {
assertCrash("Nil returned from RecordWithoutDatabaseTableName.databaseTableName()") {
assertCrash("subclass must override") {
dbQueue.inDatabase { db in
RecordWithoutDatabaseTableName.fetchOne(db, primaryKey: 1)
RecordWithoutDatabaseTableName.fetchOne(db, key: 1)
}
}
}
func testRecordWithoutDatabaseTableNameCanNotBeFetchedByKey() {
assertCrash("Nil returned from RecordWithoutDatabaseTableName.databaseTableName()") {
assertCrash("subclass must override") {
dbQueue.inDatabase { db in
RecordWithoutDatabaseTableName.fetchOne(db, key: ["foo": "bar"])
}
@@ -204,7 +297,7 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithoutDatabaseTableNameCanNotBeInserted() {
assertCrash("Nil returned from RecordWithoutDatabaseTableName.databaseTableName()") {
assertCrash("subclass must override") {
try dbQueue.inDatabase { db in
try RecordWithoutDatabaseTableName().insert(db)
}
@@ -212,7 +305,7 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithoutDatabaseTableNameCanNotBeUpdated() {
assertCrash("Nil returned from RecordWithoutDatabaseTableName.databaseTableName()") {
assertCrash("subclass must override") {
try dbQueue.inDatabase { db in
try RecordWithoutDatabaseTableName().update(db)
}
@@ -220,7 +313,7 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithoutDatabaseTableNameCanNotBeSaved() {
assertCrash("Nil returned from RecordWithoutDatabaseTableName.databaseTableName()") {
assertCrash("subclass must override") {
try dbQueue.inDatabase { db in
try RecordWithoutDatabaseTableName().save(db)
}
@@ -228,23 +321,15 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithoutDatabaseTableNameCanNotBeDeleted() {
assertCrash("Nil returned from RecordWithoutDatabaseTableName.databaseTableName()") {
assertCrash("subclass must override") {
try dbQueue.inDatabase { db in
try RecordWithoutDatabaseTableName().delete(db)
}
}
}
func testRecordWithoutDatabaseTableNameCanNotBeReloaded() {
assertCrash("Nil returned from RecordWithoutDatabaseTableName.databaseTableName()") {
try dbQueue.inDatabase { db in
try RecordWithoutDatabaseTableName().reload(db)
}
}
}
func testRecordWithoutDatabaseTableNameCanNotBeTestedForExistence() {
assertCrash("Nil returned from RecordWithoutDatabaseTableName.databaseTableName()") {
assertCrash("subclass must override") {
dbQueue.inDatabase { db in
RecordWithoutDatabaseTableName().exists(db)
}
@@ -256,15 +341,15 @@ class CrashTests: GRDBTestCase {
// MARK: - RecordWithInexistingDatabaseTable
func testRecordWithInexistingDatabaseTableCanNotBeFetchedByID() {
assertCrash("Table \"foo\" does not exist.") {
assertCrash("no such table: foo") {
dbQueue.inDatabase { db in
RecordWithInexistingDatabaseTable.fetchOne(db, primaryKey: 1)
RecordWithInexistingDatabaseTable.fetchOne(db, key: 1)
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeFetchedByKey() {
assertCrash("no such table: foo") {
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])
}
@@ -272,7 +357,7 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithInexistingDatabaseTableCanNotBeInserted() {
assertCrash("Table \"foo\" does not exist.") {
assertCrash("no such table: foo") {
try dbQueue.inDatabase { db in
try RecordWithInexistingDatabaseTable().insert(db)
}
@@ -280,15 +365,15 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithInexistingDatabaseTableCanNotBeUpdated() {
assertCrash("Table \"foo\" does not exist.") {
assertCrash("no such table: foo") {
try dbQueue.inDatabase { db in
try RecordWithInexistingDatabaseTable().update(db)
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeSaved() {
assertCrash("Table \"foo\" does not exist.") {
assertCrash("no such table: foo") {
try dbQueue.inDatabase { db in
try RecordWithInexistingDatabaseTable().save(db)
}
@@ -296,23 +381,15 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithInexistingDatabaseTableCanNotBeDeleted() {
assertCrash("Table \"foo\" does not exist.") {
assertCrash("no such table: foo") {
try dbQueue.inDatabase { db in
try RecordWithInexistingDatabaseTable().delete(db)
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeReloaded() {
assertCrash("Table \"foo\" does not exist.") {
try dbQueue.inDatabase { db in
try RecordWithInexistingDatabaseTable().reload(db)
}
}
}
func testRecordWithInexistingDatabaseTableCanNotBeTestedForExistence() {
assertCrash("Table \"foo\" does not exist.") {
assertCrash("no such table: foo") {
dbQueue.inDatabase { db in
RecordWithInexistingDatabaseTable().exists(db)
}
@@ -324,7 +401,7 @@ class CrashTests: GRDBTestCase {
// MARK: - RecordWithEmptyPersistentDictionary
func testRecordWithEmptyPersistentDictionaryCanNotBeInserted() {
assertCrash("Invalid empty dictionary") {
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)
@@ -333,7 +410,7 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithEmptyPersistentDictionaryCanNotBeUpdated() {
assertCrash("Invalid empty dictionary") {
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)
@@ -342,7 +419,7 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithEmptyPersistentDictionaryCanNotBeSaved() {
assertCrash("Invalid empty dictionary") {
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)
@@ -351,7 +428,7 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithEmptyPersistentDictionaryCanNotBeDeleted() {
assertCrash("Invalid empty dictionary") {
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)
@@ -359,17 +436,8 @@ class CrashTests: GRDBTestCase {
}
}
func testRecordWithEmptyPersistentDictionaryCanNotBeReloaded() {
assertCrash("Invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithEmptyPersistentDictionary().reload(db)
}
}
}
func testRecordWithEmptyPersistentDictionaryCanNotBeTestedForExistence() {
assertCrash("Invalid empty dictionary") {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
RecordWithEmptyPersistentDictionary().exists(db)
@@ -382,7 +450,7 @@ class CrashTests: GRDBTestCase {
// MARK: - RecordWithNilPrimaryKey
func testRecordWithNilPrimaryKeyCanNotBeUpdated() {
assertCrash("Invalid primary key") {
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)
@@ -391,7 +459,7 @@ class CrashTests: GRDBTestCase {
}
func testRecordWithNilPrimaryKeyCanNotBeDeleted() {
assertCrash("Invalid primary key") {
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)
@@ -399,48 +467,39 @@ class CrashTests: GRDBTestCase {
}
}
func testRecordWithNilPrimaryKeyCanNotBeReloaded() {
assertCrash("Invalid primary key") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithNilPrimaryKey().reload(db)
}
}
}
func testRecordWithNilPrimaryKeyCanNotBeTestedForExistence() {
assertCrash("Invalid primary key") {
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("Primary key of table \"records\" is not made of a single column.") {
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, primaryKey: 1)
RecordForTableWithoutPrimaryKey.fetchOne(db, key: 1)
}
}
}
func testRecordForTableWithoutPrimaryKeyCanNotBeUpdated() {
assertCrash("Invalid primary key") {
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") {
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)
@@ -448,17 +507,8 @@ class CrashTests: GRDBTestCase {
}
}
func testRecordForTableWithoutPrimaryKeyCanNotBeReloaded() {
assertCrash("Invalid primary key") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
try RecordForTableWithoutPrimaryKey().reload(db)
}
}
}
func testRecordForTableWithoutPrimaryKeyCanNotBeTestedForExistence() {
assertCrash("Invalid primary key") {
assertCrash("invalid primary key in <RecordForTableWithoutPrimaryKey name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
RecordForTableWithoutPrimaryKey().exists(db)
@@ -471,10 +521,10 @@ class CrashTests: GRDBTestCase {
// MARK: - RecordForTableWithMultipleColumnsPrimaryKey
func testRecordForTableWithMultipleColumnsPrimaryKeyCanNotBeFetchedByID() {
assertCrash("Primary key of table \"records\" is not made of a single column.") {
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, primaryKey: 1)
RecordForTableWithMultipleColumnsPrimaryKey.fetchOne(db, key: 1)
}
}
}
@@ -484,14 +534,14 @@ class CrashTests: GRDBTestCase {
// MARK: - RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary
func testRecordWithRowIDPrimaryKeyNotExposedInPersistentDictionaryCanNotBeInserted() {
assertCrash("RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary.persistentDictionary must return the value for the primary key \"id\"") {
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().insert(db)
try RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary().update(db)
}
}
}
// =========================================================================
// MARK: - Concurrency
@@ -539,34 +589,34 @@ class CrashTests: GRDBTestCase {
// MARK: - DatabaseValueConvertible
func testCrashFetchDatabaseValueConvertibleFromStatement() {
assertCrash("Could not convert NULL to IntConvertible while iterating `SELECT int FROM ints ORDER BY int`.") {
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 = db.selectStatement("SELECT int FROM ints ORDER BY int")
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 while iterating `SELECT int FROM ints ORDER BY int`.") {
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 = db.selectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int")
let _ = IntConvertible.fetchAll(statement)
}
}
}
func testCrashFetchDatabaseValueConvertibleFromDatabase() {
assertCrash("Could not convert NULL to IntConvertible while iterating `SELECT int FROM ints ORDER BY int`.") {
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)")
@@ -577,9 +627,9 @@ class CrashTests: GRDBTestCase {
}
}
}
func testCrashFetchAllDatabaseValueConvertibleFromDatabase() {
assertCrash("Could not convert NULL to IntConvertible while iterating `SELECT int FROM ints ORDER BY int`.") {
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)")
@@ -591,15 +641,15 @@ class CrashTests: GRDBTestCase {
}
func testCrashDatabaseValueConvertibleInvalidConversionFromNULL() {
assertCrash("Could not convert NULL to IntConvertible.") {
let row = Row(dictionary: ["int": nil])
assertCrash("could not convert NULL to IntConvertible.") {
let row = Row(["int": nil])
let _ = row.value(named: "int") as IntConvertible
}
}
func testCrashDatabaseValueConvertibleInvalidConversionFromInvalidType() {
assertCrash("Could not convert \"foo\" to IntConvertible.") {
let row = Row(dictionary: ["int": "foo"])
assertCrash("could not convert \"foo\" to IntConvertible") {
let row = Row(["int": "foo"])
let _ = row.value(named: "int") as IntConvertible
}
}
@@ -609,34 +659,34 @@ class CrashTests: GRDBTestCase {
// MARK: - SQLiteStatementConvertible
func testCrashFetchSQLiteStatementConvertibleFromStatement() {
assertCrash("Found NULL") {
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 = db.selectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int")
let sequence = Int.fetch(statement)
for _ in sequence { }
}
}
}
func testCrashFetchAllSQLiteStatementConvertibleFromStatement() {
assertCrash("Found NULL") {
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 = db.selectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int")
let _ = Int.fetchAll(statement)
}
}
}
func testCrashFetchSQLiteStatementConvertibleFromDatabase() {
assertCrash("Found NULL") {
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)")
@@ -647,9 +697,9 @@ class CrashTests: GRDBTestCase {
}
}
}
func testCrashFetchAllSQLiteStatementConvertibleFromDatabase() {
assertCrash("Found NULL") {
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)")
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '0.36.0'
s.version = '0.39.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'Versatile SQLite toolkit for Swift.'
s.homepage = 'https://github.com/groue/GRDB.swift'
+165 -52
View File
@@ -23,15 +23,12 @@
560C97E81C0E22D300BF8471 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86221BA988F2001F9168 /* FMResultSet.m */; };
560C97EC1C0E22D300BF8471 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB861F1BA988F2001F9168 /* FMDatabaseQueue.m */; };
560C97F21C0E22D300BF8471 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB861D1BA988F2001F9168 /* FMDatabasePool.m */; };
560C98101C0E22D300BF8471 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
560C98121C0E22D300BF8471 /* SQLite.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56CA220F1BB414FE009A04C5 /* SQLite.framework */; };
560C98131C0E22D300BF8471 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; };
560C98141C0E22D300BF8471 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC3773F319C8CBB3004FCF85 /* GRDB.framework */; };
560C98161C0E22D300BF8471 /* FetchPerformanceTests.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 56BB86111BA9886D001F9168 /* FetchPerformanceTests.sqlite */; };
560C98221C0E23BB00BF8471 /* FMDBPerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CA221A1BB41533009A04C5 /* FMDBPerformanceTests.swift */; };
560C98231C0E23BB00BF8471 /* GRDBPerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86121BA9886D001F9168 /* GRDBPerformanceTests.swift */; };
560C98241C0E23BB00BF8471 /* PerformanceRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CA22211BB41565009A04C5 /* PerformanceRecord.swift */; };
560C98251C0E23BB00BF8471 /* StephenCelisSQLitePerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CA221B1BB41533009A04C5 /* StephenCelisSQLitePerformanceTests.swift */; };
560C98161C0E22D300BF8471 /* PerformanceTests.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */; };
560C98231C0E23BB00BF8471 /* InsertRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86121BA9886D001F9168 /* InsertRecordTests.swift */; };
560C98241C0E23BB00BF8471 /* PerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CA22211BB41565009A04C5 /* PerformanceTests.swift */; };
5614DEF01BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; };
5614DEF11BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; };
5614DEF81BAA1B43003163B3 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; };
@@ -39,6 +36,10 @@
56437C851C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */; };
564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; };
564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; };
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 /* MutableDatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */; };
5658420F1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */; };
565B0FEF1BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; };
@@ -115,8 +116,6 @@
56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; };
56A2387D1B9C75030082EB20 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238711B9C75030082EB20 /* Database.swift */; };
56A2387E1B9C75030082EB20 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238711B9C75030082EB20 /* Database.swift */; };
56A2387F1B9C75030082EB20 /* DatabaseChanges.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238721B9C75030082EB20 /* DatabaseChanges.swift */; };
56A238801B9C75030082EB20 /* DatabaseChanges.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238721B9C75030082EB20 /* DatabaseChanges.swift */; };
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; };
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; };
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238741B9C75030082EB20 /* DatabaseQueue.swift */; };
@@ -125,14 +124,8 @@
56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; };
56A238871B9C75030082EB20 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; };
56A238881B9C75030082EB20 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; };
56A238891B9C75030082EB20 /* SelectStatement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238771B9C75030082EB20 /* SelectStatement.swift */; };
56A2388A1B9C75030082EB20 /* SelectStatement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238771B9C75030082EB20 /* SelectStatement.swift */; };
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
56A2388D1B9C75030082EB20 /* StatementArguments.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238791B9C75030082EB20 /* StatementArguments.swift */; };
56A2388E1B9C75030082EB20 /* StatementArguments.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238791B9C75030082EB20 /* StatementArguments.swift */; };
56A2388F1B9C75030082EB20 /* UpdateStatement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2387A1B9C75030082EB20 /* UpdateStatement.swift */; };
56A238901B9C75030082EB20 /* UpdateStatement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2387A1B9C75030082EB20 /* UpdateStatement.swift */; };
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
56A238991B9C752B0082EB20 /* DatabaseTableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */; };
@@ -173,6 +166,16 @@
56CA21BA1BB3FCF7009A04C5 /* NSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CA21B91BB3FCF7009A04C5 /* NSDataTests.swift */; };
56CA21BB1BB3FCF7009A04C5 /* NSDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CA21B91BB3FCF7009A04C5 /* NSDataTests.swift */; };
56CA22291BB41663009A04C5 /* SQLite.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56CA220B1BB414FE009A04C5 /* SQLite.framework */; };
56DE7B111C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; };
56DE7B121C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; };
56DE7B241C412F7E00861EB8 /* InsertPositionalValuesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B231C412F7E00861EB8 /* InsertPositionalValuesTests.swift */; };
56DE7B261C412FDA00861EB8 /* InsertNamedValuesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B251C412FDA00861EB8 /* InsertNamedValuesTests.swift */; };
56DE7B281C41302500861EB8 /* FetchNamedValuesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */; };
56DE7B2A1C4130AF00861EB8 /* FetchPositionalValuesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */; };
56DE7B2C1C41311900861EB8 /* FetchRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B2B1C41311900861EB8 /* FetchRecordTests.swift */; };
56DE7B2F1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */; };
56DE7B351C42B37E00861EB8 /* CoreData.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56DE7B341C42B37E00861EB8 /* CoreData.framework */; };
56DE7B371C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */; };
56E5891F1BBA5D5400CC0140 /* NSURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E5891E1BBA5D5400CC0140 /* NSURL.swift */; };
56E589201BBA5D5400CC0140 /* NSURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E5891E1BBA5D5400CC0140 /* NSURL.swift */; };
56E5D7D41B4D3FEE00430942 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56E5D7CA1B4D3FED00430942 /* GRDB.framework */; };
@@ -185,8 +188,6 @@
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 */; };
56EB0AAF1BCD785C00A3DC55 /* DatabaseErrorFromStatementCreationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AAE1BCD785C00A3DC55 /* DatabaseErrorFromStatementCreationTests.swift */; };
56EB0AB01BCD785C00A3DC55 /* DatabaseErrorFromStatementCreationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AAE1BCD785C00A3DC55 /* DatabaseErrorFromStatementCreationTests.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 */; };
@@ -221,6 +222,13 @@
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
remoteInfo = GRDBOSX;
};
56553BDC1C3E906C00522B5C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = DC3773EA19C8CBB3004FCF85 /* Project object */;
proxyType = 1;
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
remoteInfo = GRDBOSX;
};
56CA220A1BB414FE009A04C5 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */;
@@ -311,6 +319,7 @@
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistable.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 /* MutableDatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableDatabasePersistableTests.swift; sourceTree = "<group>"; };
565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = "<group>"; };
565D5D671BBC604000DC9BD4 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = "<group>"; };
@@ -350,15 +359,11 @@
56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordSubClassTests.swift; sourceTree = "<group>"; };
56A238701B9C75030082EB20 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = "<group>"; };
56A238711B9C75030082EB20 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
56A238721B9C75030082EB20 /* DatabaseChanges.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseChanges.swift; sourceTree = "<group>"; };
56A238731B9C75030082EB20 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = "<group>"; };
56A238741B9C75030082EB20 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = "<group>"; };
56A238751B9C75030082EB20 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = "<group>"; };
56A238761B9C75030082EB20 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = "<group>"; };
56A238771B9C75030082EB20 /* SelectStatement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SelectStatement.swift; sourceTree = "<group>"; };
56A238781B9C75030082EB20 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = "<group>"; };
56A238791B9C75030082EB20 /* StatementArguments.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArguments.swift; sourceTree = "<group>"; };
56A2387A1B9C75030082EB20 /* UpdateStatement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpdateStatement.swift; sourceTree = "<group>"; };
56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTableMapping.swift; sourceTree = "<group>"; };
56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
@@ -378,8 +383,8 @@
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
56B8F49B1B4E2F3600C24296 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
56BB86111BA9886D001F9168 /* FetchPerformanceTests.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = FetchPerformanceTests.sqlite; sourceTree = "<group>"; };
56BB86121BA9886D001F9168 /* GRDBPerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBPerformanceTests.swift; sourceTree = "<group>"; };
56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceTests.sqlite; sourceTree = "<group>"; };
56BB86121BA9886D001F9168 /* InsertRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordTests.swift; sourceTree = "<group>"; };
56BB86181BA988F2001F9168 /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = "<group>"; };
56BB86191BA988F2001F9168 /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabase.m; sourceTree = "<group>"; };
56BB861A1BA988F2001F9168 /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseAdditions.h; sourceTree = "<group>"; };
@@ -397,11 +402,18 @@
56CA0D401BF5D8E20019C023 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = "<group>"; };
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>"; };
56CA221A1BB41533009A04C5 /* FMDBPerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FMDBPerformanceTests.swift; sourceTree = "<group>"; };
56CA221B1BB41533009A04C5 /* StephenCelisSQLitePerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StephenCelisSQLitePerformanceTests.swift; sourceTree = "<group>"; };
56CA22211BB41565009A04C5 /* PerformanceRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceRecord.swift; 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>"; };
56DE7B251C412FDA00861EB8 /* InsertNamedValuesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertNamedValuesTests.swift; sourceTree = "<group>"; };
56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchNamedValuesTests.swift; sourceTree = "<group>"; };
56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchPositionalValuesTests.swift; sourceTree = "<group>"; };
56DE7B2B1C41311900861EB8 /* FetchRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordTests.swift; sourceTree = "<group>"; };
56DE7B2E1C42B23B00861EB8 /* PerformanceModel.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = PerformanceModel.xcdatamodel; sourceTree = "<group>"; };
56DE7B341C42B37E00861EB8 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = System/Library/Frameworks/CoreData.framework; sourceTree = SDKROOT; };
56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceCoreDataTests.sqlite; sourceTree = "<group>"; };
56E1524B1B43FD5B00EE27AA /* TODO.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = TODO.md; sourceTree = "<group>"; };
56E5891E1BBA5D5400CC0140 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = "<group>"; };
56E5D7CA1B4D3FED00430942 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -409,7 +421,6 @@
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>"; };
56EB0AAE1BCD785C00A3DC55 /* DatabaseErrorFromStatementCreationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorFromStatementCreationTests.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>"; };
@@ -431,12 +442,22 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
56DE7B351C42B37E00861EB8 /* CoreData.framework in Frameworks */,
560C98121C0E22D300BF8471 /* SQLite.framework in Frameworks */,
560C98131C0E22D300BF8471 /* libsqlite3.tbd in Frameworks */,
560C98141C0E22D300BF8471 /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
56553C111C3E906C00522B5C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
56553C121C3E906C00522B5C /* libsqlite3.tbd in Frameworks */,
56553C131C3E906C00522B5C /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
56E5D7C61B4D3FED00430942 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@@ -528,7 +549,6 @@
569978D31B539038005EBEED /* Private */ = {
isa = PBXGroup;
children = (
56EB0AAE1BCD785C00A3DC55 /* DatabaseErrorFromStatementCreationTests.swift */,
56EB0AB11BCD787300A3DC55 /* NSDataMemoryTests.swift */,
);
path = Private;
@@ -647,6 +667,7 @@
isa = PBXGroup;
children = (
56A238211B9C74A90082EB20 /* SelectStatementTests.swift */,
56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */,
56A238221B9C74A90082EB20 /* UpdateStatementTests.swift */,
);
path = Statement;
@@ -695,15 +716,11 @@
56A238951B9C752B0082EB20 /* Protocols */,
56A238701B9C75030082EB20 /* Configuration.swift */,
56A238711B9C75030082EB20 /* Database.swift */,
56A238721B9C75030082EB20 /* DatabaseChanges.swift */,
56A238731B9C75030082EB20 /* DatabaseError.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
56A238771B9C75030082EB20 /* SelectStatement.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
56A238791B9C75030082EB20 /* StatementArguments.swift */,
56A2387A1B9C75030082EB20 /* UpdateStatement.swift */,
);
path = Core;
sourceTree = "<group>";
@@ -764,13 +781,18 @@
56BB86101BA9886D001F9168 /* Performance */ = {
isa = PBXGroup;
children = (
56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */,
56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */,
56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */,
56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */,
56DE7B2B1C41311900861EB8 /* FetchRecordTests.swift */,
56DE7B251C412FDA00861EB8 /* InsertNamedValuesTests.swift */,
56DE7B231C412F7E00861EB8 /* InsertPositionalValuesTests.swift */,
56BB86121BA9886D001F9168 /* InsertRecordTests.swift */,
56CA22211BB41565009A04C5 /* PerformanceTests.swift */,
56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */,
56BB86171BA988F2001F9168 /* fmdb */,
56BB86111BA9886D001F9168 /* FetchPerformanceTests.sqlite */,
56CA221A1BB41533009A04C5 /* FMDBPerformanceTests.swift */,
56BB86121BA9886D001F9168 /* GRDBPerformanceTests.swift */,
56CA22211BB41565009A04C5 /* PerformanceRecord.swift */,
56CA221B1BB41533009A04C5 /* StephenCelisSQLitePerformanceTests.swift */,
56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */,
);
path = Performance;
sourceTree = "<group>";
@@ -873,6 +895,7 @@
DC3773E919C8CBB3004FCF85 = {
isa = PBXGroup;
children = (
56DE7B341C42B37E00861EB8 /* CoreData.framework */,
56DBEC341C19A0020093A2EE /* CHANGELOG.md */,
DC37744719C8F50B004FCF85 /* README.md */,
56E1524B1B43FD5B00EE27AA /* TODO.md */,
@@ -893,6 +916,7 @@
56E5D7D31B4D3FEE00430942 /* GRDBTests.xctest */,
56E5D7F91B4D422D00430942 /* GRDBTests.xctest */,
560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */,
56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -979,6 +1003,24 @@
productReference = 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
56553BDA1C3E906C00522B5C /* GRDBOSXCrashTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 56553C151C3E906C00522B5C /* Build configuration list for PBXNativeTarget "GRDBOSXCrashTests" */;
buildPhases = (
56553BDD1C3E906C00522B5C /* Sources */,
56553C111C3E906C00522B5C /* Frameworks */,
56553C141C3E906C00522B5C /* Resources */,
);
buildRules = (
);
dependencies = (
56553BDB1C3E906C00522B5C /* PBXTargetDependency */,
);
name = GRDBOSXCrashTests;
productName = GRDBOSXTests;
productReference = 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
56E5D7C91B4D3FED00430942 /* GRDBiOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 56E5D7DB1B4D3FEE00430942 /* Build configuration list for PBXNativeTarget "GRDBiOS" */;
@@ -1096,6 +1138,7 @@
projectRoot = "";
targets = (
DC3773F219C8CBB3004FCF85 /* GRDBOSX */,
56553BDA1C3E906C00522B5C /* GRDBOSXCrashTests */,
56E5D7F81B4D422D00430942 /* GRDBOSXTests */,
560C97CF1C0E22D300BF8471 /* GRDBOSXPerformanceTests */,
56E5D7C91B4D3FED00430942 /* GRDBiOS */,
@@ -1168,7 +1211,15 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
560C98161C0E22D300BF8471 /* FetchPerformanceTests.sqlite in Resources */,
560C98161C0E22D300BF8471 /* PerformanceTests.sqlite in Resources */,
56DE7B371C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
56553C141C3E906C00522B5C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -1208,15 +1259,27 @@
buildActionMask = 2147483647;
files = (
560C97DA1C0E22D300BF8471 /* FMDatabase.m in Sources */,
560C98231C0E23BB00BF8471 /* GRDBPerformanceTests.swift in Sources */,
560C98231C0E23BB00BF8471 /* InsertRecordTests.swift in Sources */,
560C97DD1C0E22D300BF8471 /* FMDatabaseAdditions.m in Sources */,
56DE7B2C1C41311900861EB8 /* FetchRecordTests.swift in Sources */,
560C97E81C0E22D300BF8471 /* FMResultSet.m in Sources */,
560C98221C0E23BB00BF8471 /* FMDBPerformanceTests.swift in Sources */,
56DE7B281C41302500861EB8 /* FetchNamedValuesTests.swift in Sources */,
56DE7B241C412F7E00861EB8 /* InsertPositionalValuesTests.swift in Sources */,
560C97EC1C0E22D300BF8471 /* FMDatabaseQueue.m in Sources */,
560C97F21C0E22D300BF8471 /* FMDatabasePool.m in Sources */,
560C98251C0E23BB00BF8471 /* StephenCelisSQLitePerformanceTests.swift in Sources */,
560C98101C0E22D300BF8471 /* GRDBTestCase.swift in Sources */,
560C98241C0E23BB00BF8471 /* PerformanceRecord.swift in Sources */,
560C98241C0E23BB00BF8471 /* PerformanceTests.swift in Sources */,
56DE7B261C412FDA00861EB8 /* InsertNamedValuesTests.swift in Sources */,
56DE7B2F1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld in Sources */,
56DE7B2A1C4130AF00861EB8 /* FetchPositionalValuesTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
56553BDD1C3E906C00522B5C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */,
56553C1A1C3E91BC00522B5C /* CrashTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -1224,10 +1287,8 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56A238901B9C75030082EB20 /* UpdateStatement.swift in Sources */,
56437C851C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */,
56E589201BBA5D5400CC0140 /* NSURL.swift in Sources */,
56A2388E1B9C75030082EB20 /* StatementArguments.swift in Sources */,
56A2380A1B9C6DD20082EB20 /* StandardLibraryTypes.swift in Sources */,
5614DEF11BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */,
56A2387E1B9C75030082EB20 /* Database.swift in Sources */,
@@ -1246,9 +1307,7 @@
56B7F4271BE1491700E39BBF /* CGFloat.swift in Sources */,
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */,
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */,
56A2388A1B9C75030082EB20 /* SelectStatement.swift in Sources */,
56A2389C1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */,
56A238801B9C75030082EB20 /* DatabaseChanges.swift in Sources */,
565D5D691BBC604000DC9BD4 /* Row+Foundation.swift in Sources */,
31AEFE421C185E63003DB703 /* FetchedRecordsController.swift in Sources */,
56A238AE1B9C90090082EB20 /* NSNull.swift in Sources */,
@@ -1265,7 +1324,6 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56EB0AB01BCD785C00A3DC55 /* DatabaseErrorFromStatementCreationTests.swift in Sources */,
56A238601B9C74A90082EB20 /* RecordDescriptionTests.swift in Sources */,
56A238561B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */,
56A238501B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
@@ -1285,6 +1343,7 @@
56A238481B9C74A90082EB20 /* DetachedRowTests.swift in Sources */,
56A238541B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift in Sources */,
56FDECE31BB32DFD009AD709 /* MetalRowTests.swift in Sources */,
56DE7B121C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */,
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
56EB0AB31BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */,
56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */,
@@ -1324,7 +1383,6 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56EB0AAF1BCD785C00A3DC55 /* DatabaseErrorFromStatementCreationTests.swift in Sources */,
5614DEF81BAA1B43003163B3 /* DatabaseValueConversionTests.swift in Sources */,
56A2385F1B9C74A90082EB20 /* RecordDescriptionTests.swift in Sources */,
56A238551B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */,
@@ -1344,6 +1402,7 @@
56A238471B9C74A90082EB20 /* DetachedRowTests.swift in Sources */,
56FDECE21BB32DFD009AD709 /* MetalRowTests.swift in Sources */,
56A238531B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift in Sources */,
56DE7B111C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */,
56A238671B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
56A2385D1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */,
56A238431B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */,
@@ -1387,7 +1446,6 @@
56437C841C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */,
56E5891F1BBA5D5400CC0140 /* NSURL.swift in Sources */,
56A2389D1B9C752B0082EB20 /* RowConvertible.swift in Sources */,
56A2388D1B9C75030082EB20 /* StatementArguments.swift in Sources */,
5614DEF01BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */,
56A238051B9C6D670082EB20 /* NSDate.swift in Sources */,
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
@@ -1396,18 +1454,15 @@
317194AF1C2304AA002E3BDA /* FetchedRecordsController.swift in Sources */,
56A2380F1B9C74460082EB20 /* RawRepresentable.swift in Sources */,
56A238AA1B9C7E540082EB20 /* StatementArguments+Foundation.swift in Sources */,
56A238891B9C75030082EB20 /* SelectStatement.swift in Sources */,
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
56A238991B9C752B0082EB20 /* DatabaseTableMapping.swift in Sources */,
56CA0D411BF5D8E20019C023 /* DatabaseValue+Foundation.swift in Sources */,
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
56A238A41B9C753B0082EB20 /* Record.swift in Sources */,
56A2388F1B9C75030082EB20 /* UpdateStatement.swift in Sources */,
56A238091B9C6DD20082EB20 /* StandardLibraryTypes.swift in Sources */,
56A238021B9C6A650082EB20 /* DatabaseDateComponents.swift in Sources */,
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */,
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */,
56A2387F1B9C75030082EB20 /* DatabaseChanges.swift in Sources */,
56A238B31B9C919D0082EB20 /* NSNumber.swift in Sources */,
56A238B01B9C90BB0082EB20 /* NSString.swift in Sources */,
565D5D681BBC604000DC9BD4 /* Row+Foundation.swift in Sources */,
@@ -1433,6 +1488,11 @@
target = DC3773F219C8CBB3004FCF85 /* GRDBOSX */;
targetProxy = 560C97D31C0E22D300BF8471 /* PBXContainerItemProxy */;
};
56553BDB1C3E906C00522B5C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = DC3773F219C8CBB3004FCF85 /* GRDBOSX */;
targetProxy = 56553BDC1C3E906C00522B5C /* PBXContainerItemProxy */;
};
56CA22281BB4165C009A04C5 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "SQLite iOS";
@@ -1484,6 +1544,37 @@
};
name = Release;
};
56553C161C3E906C00522B5C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "GRDB Tests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.10;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
};
name = Debug;
};
56553C171C3E906C00522B5C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "GRDB Tests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.10;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
};
name = Release;
};
56E5D7DC1B4D3FEE00430942 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -1729,6 +1820,15 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
56553C151C3E906C00522B5C /* Build configuration list for PBXNativeTarget "GRDBOSXCrashTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
56553C161C3E906C00522B5C /* Debug */,
56553C171C3E906C00522B5C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
56E5D7DB1B4D3FEE00430942 /* Build configuration list for PBXNativeTarget "GRDBiOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
@@ -1775,6 +1875,19 @@
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCVersionGroup section */
56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */ = {
isa = XCVersionGroup;
children = (
56DE7B2E1C42B23B00861EB8 /* PerformanceModel.xcdatamodel */,
);
currentVersion = 56DE7B2E1C42B23B00861EB8 /* PerformanceModel.xcdatamodel */;
path = PerformanceModel.xcdatamodeld;
sourceTree = "<group>";
versionGroupType = wrapper.xcdatamodel;
};
/* End XCVersionGroup section */
};
rootObject = DC3773EA19C8CBB3004FCF85 /* Project object */;
}
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0710"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "56553BDA1C3E906C00522B5C"
BuildableName = "GRDBOSXCrashTests.xctest"
BlueprintName = "GRDBOSXCrashTests"
ReferencedContainer = "container:GRDB.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+13 -53
View File
@@ -3,21 +3,15 @@ import Foundation
/// Configuration are arguments to the DatabaseQueue initializers.
public struct Configuration {
// =========================================================================
// MARK: - Misc options
/// If true, the database has support for foreign keys.
///
/// Default is true.
public var foreignKeysEnabled: Bool
public var foreignKeysEnabled: Bool = true
public var readonly: Bool = false
/// If true, the database is opened readonly.
///
/// Default is false.
public var readonly: Bool
/// A function that is called on every statement executed by the database.
public var trace: TraceFunction?
// =========================================================================
// MARK: - Transactions
/// The transaction kind used by Database.inTransaction().
@@ -26,59 +20,25 @@ public struct Configuration {
public var defaultTransactionKind: TransactionKind
// =========================================================================
// MARK: - Concurrency
/// The busy Mode.
///
/// Default is `.ImmediateError`.
public var busyMode: BusyMode
/// The Threading mode
///
/// Not public because we don't expose any public API that could have a use
/// for it.
var threadingMode: ThreadingMode
public var busyMode: BusyMode = .ImmediateError
var threadingMode: ThreadingMode = .Default
// =========================================================================
// MARK: - Logging
/// A tracing function.
///
/// You can use the global GRDB.LogSQL function as a tracing function: it
/// logs all SQL statements with NSLog().
///
/// The default is nil.
public var trace: TraceFunction?
// =========================================================================
// MARK: - Factory Configuration
/// Returns a factory configuration:
///
/// - `foreignKeysEnabled`: true
/// - `readonly`: false
/// - `defaultTransactionKind`: Immediate
/// - `transactionObserver`: nil
/// - `busyMode`: Immediate error
/// - `trace`: nil
public init()
{
self.foreignKeysEnabled = true
self.readonly = false
self.defaultTransactionKind = .Immediate
self.busyMode = .ImmediateError
self.threadingMode = .Default
self.trace = nil
}
/// - foreignKeysEnabled: true
/// - readonly: false
/// - trace: nil
/// - defaultTransactionKind: .Immediate
/// - transactionObserver: nil
/// - busyMode: .ImmediateError
public init() { }
// =========================================================================
// MARK: - SQLite flags
var sqliteOpenFlags: Int32 {
+148 -52
View File
@@ -31,6 +31,16 @@ public final class Database {
return try SelectStatement(database: self, sql: sql)
}
func cachedSelectStatement(sql: String) throws -> SelectStatement {
if let statement = selectStatementCache[sql] {
return statement
}
let statement = try selectStatement(sql)
selectStatementCache[sql] = statement
return statement
}
// =========================================================================
// MARK: - Update Statements
@@ -50,46 +60,121 @@ public final class Database {
return try UpdateStatement(database: self, sql: sql)
}
/// Executes an update statement.
func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
if let statement = updateStatementCache[sql] {
return statement
}
let statement = try updateStatement(sql)
updateStatementCache[sql] = statement
return statement
}
/// Executes one or several SQL statements, separated by semi-colons.
///
/// db.excute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
/// try db.execute(
/// "INSERT INTO persons (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try db.execute(
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);",
/// arguments; ['Harry', 'Ron', 'Hermione'])
///
/// This method may throw a DatabaseError.
///
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A DatabaseChanges.
/// - throws: A DatabaseError whenever a SQLite error occurs.
public func execute(sql: String, arguments: StatementArguments = StatementArguments.Default) throws -> DatabaseChanges {
let statement = try updateStatement(sql)
return try statement.execute(arguments: arguments)
}
/// Executes multiple SQL statements, separated by semi-colons.
///
/// try db.executeMultiStatement(
/// "INSERT INTO persons (name) VALUES ('Harry');" +
/// "INSERT INTO persons (name) VALUES ('Ron');" +
/// "INSERT INTO persons (name) VALUES ('Hermione');")
///
/// This method may throw a DatabaseError.
///
/// - parameter sql: SQL containing multiple statements separated by
/// semi-colons.
/// - returns: A DatabaseChanges. Note that insertedRowID will always be nil.
/// - throws: A DatabaseError whenever a SQLite error occurs.
public func executeMultiStatement(sql: String) throws -> DatabaseChanges {
public func execute(sql: String, arguments: StatementArguments? = nil) throws -> DatabaseChanges {
preconditionValidQueue()
let changedRowsBefore = sqlite3_total_changes(sqliteConnection)
let code = sqlite3_exec(sqliteConnection, sql, nil, nil, nil)
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: lastErrorMessage, sql: sql, arguments: nil)
let usedArguments: StatementArguments
if let arguments = arguments {
usedArguments = arguments
} else {
usedArguments = []
}
// The tricky part is to consume arguments as statements are executed.
//
// Here we return two functions:
// - one that returns arguments for a statement
// - one that validates the remaining arguments, in the same way as
// Statement.validateArguments()
let (consumeArguments, validateRemainingArguments) = { () -> (UpdateStatement -> StatementArguments, () throws -> ()) in
switch usedArguments.kind {
case .Array(let values):
// Extract as many values as needed, statement after statement:
var remainingValues = values
let consumeArguments = { (statement: UpdateStatement) -> StatementArguments in
let argumentCount = statement.sqliteArgumentCount
defer {
if remainingValues.count >= argumentCount {
remainingValues = Array(remainingValues.suffixFrom(argumentCount))
} else {
remainingValues = []
}
}
return StatementArguments(remainingValues.prefix(argumentCount))
}
// It's not OK if there remains unused arguments:
let validateRemainingArguments = {
if !remainingValues.isEmpty {
fatalError("wrong number of statement arguments: \(values.count)")
}
}
return (consumeArguments, validateRemainingArguments)
case .Dictionary:
// Reuse the dictionary argument for all statements:
let consumeArguments = { (_: UpdateStatement) -> StatementArguments in return usedArguments }
let validateRemainingArguments = { () in }
return (consumeArguments, validateRemainingArguments)
}
}()
// Execute statements
let changedRowsBefore = sqlite3_total_changes(sqliteConnection)
let sqlCodeUnits = sql.nulTerminatedUTF8
let length = sqlCodeUnits.count
var error: ErrorType?
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)
let sqlEnd = sqlStart + length
var statementStart = sqlStart
while statementStart < sqlEnd - 1 {
var statementEnd: UnsafePointer<Int8> = nil
var sqliteStatement: SQLiteStatement = nil
let code = sqlite3_prepare_v2(sqliteConnection, statementStart, -1, &sqliteStatement, &statementEnd)
guard code == SQLITE_OK else {
error = DatabaseError(code: code, message: lastErrorMessage, sql: sql)
break
}
let sql = NSString(bytes: statementStart, length: statementEnd - statementStart, encoding: NSUTF8StringEncoding)! as String
let statement = UpdateStatement(database: self, sql: sql, sqliteStatement: sqliteStatement)
do {
try statement.execute(arguments: consumeArguments(statement))
} catch let statementError {
error = statementError
break
}
statementStart = statementEnd
}
}
if let error = error {
throw error
}
try validateRemainingArguments()
let changedRowsAfter = sqlite3_total_changes(sqliteConnection)
return DatabaseChanges(changedRowCount: changedRowsAfter - changedRowsBefore, insertedRowID: nil)
let lastInsertedRowID = sqlite3_last_insert_rowid(sqliteConnection)
let insertedRowID: Int64? = (lastInsertedRowID == 0) ? nil : lastInsertedRowID
return DatabaseChanges(changedRowCount: changedRowsAfter - changedRowsBefore, insertedRowID: insertedRowID)
}
@@ -489,17 +574,28 @@ public final class Database {
// =========================================================================
// MARK: - Database Informations
/// The database configuration
public let configuration: Configuration
/// The last error message
var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) }
private var columnInfosCache: [String: [ColumnInfo]] = [:]
private var primaryKeyCache: [String: PrimaryKey] = [:]
private var updateStatementCache: [String: UpdateStatement] = [:]
private var selectStatementCache: [String: SelectStatement] = [:]
/// Clears the database schema cache.
///
/// You may need to clear the cache if you modify the database schema
/// outside of a migration (see DatabaseMigrator).
/// outside of a database migration performed by DatabaseMigrator.
public func clearSchemaCache() {
preconditionValidQueue()
columnInfosCache = [:]
primaryKeyCache = [:]
updateStatementCache = [:]
selectStatementCache = [:]
}
/// The last error message
var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) }
/// Returns whether a table exists.
///
@@ -517,6 +613,10 @@ public final class Database {
///
/// This method is not thread-safe.
func primaryKey(tableName: String) -> PrimaryKey? {
if let primaryKey = primaryKeyCache[tableName] {
return primaryKey
}
// https://www.sqlite.org/pragma.html
//
// > PRAGMA database.table_info(table-name);
@@ -547,6 +647,7 @@ public final class Database {
return nil
}
let primaryKey: PrimaryKey
let pkColumnInfos = columnInfos
.filter { $0.primaryKeyIndex > 0 }
.sort { $0.primaryKeyIndex < $1.primaryKeyIndex }
@@ -554,7 +655,7 @@ public final class Database {
switch pkColumnInfos.count {
case 0:
// No primary key column
return PrimaryKey.None
primaryKey = PrimaryKey.None
case 1:
// Single column
let pkColumnInfo = pkColumnInfos.first!
@@ -580,14 +681,17 @@ public final class Database {
// We ignore the exception, and consider all INTEGER primary keys as
// aliases for the rowid:
if pkColumnInfo.type.uppercaseString == "INTEGER" {
return .Managed(pkColumnInfo.name)
primaryKey = .Managed(pkColumnInfo.name)
} else {
return .Unmanaged([pkColumnInfo.name])
primaryKey = .Unmanaged([pkColumnInfo.name])
}
default:
// Multi-columns primary key
return .Unmanaged(pkColumnInfos.map { $0.name })
primaryKey = .Unmanaged(pkColumnInfos.map { $0.name })
}
primaryKeyCache[tableName] = primaryKey
return primaryKey
}
// CREATE TABLE persons (
@@ -619,17 +723,14 @@ public final class Database {
}
// Cache for columnInfos()
private var columnInfosCache: [String: [ColumnInfo]] = [:]
private func columnInfos(tableName: String) -> [ColumnInfo] {
if let columnInfos = columnInfosCache[tableName] {
return columnInfos
} else {
// This pragma is case-insensitive: PRAGMA table_info("PERSONS") and
// PRAGMA table_info("persons") yield the same results.
let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
columnInfosCache[tableName] = columnInfos
return columnInfos
}
let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
columnInfosCache[tableName] = columnInfos
return columnInfos
}
@@ -640,13 +741,6 @@ public final class Database {
public let sqliteConnection: SQLiteConnection
// =========================================================================
// MARK: - Configuration
/// The database configuration
public let configuration: Configuration
// =========================================================================
// MARK: - Initialization
@@ -666,7 +760,9 @@ public final class Database {
throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection)))
}
setupTrace() // First, so that all queries, including initialization queries, are traced.
// Setup trace first, so that all queries, including initialization queries, are traced.
setupTrace()
try setupForeignKeys()
setupBusyMode()
setupTransactionHooks()
@@ -686,7 +782,7 @@ public final class Database {
// MARK: - Misc
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, use fetchAll() instead: it returns an Array that can be iterated on any thread.")
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 setupForeignKeys() throws {
-13
View File
@@ -1,13 +0,0 @@
/// Represents the various changes made to the database via execution of one or
/// more SQL statements.
public struct DatabaseChanges {
/// The number of rows affected by the statement(s)
public let changedRowCount: Int
/// The inserted Row ID.
///
/// This value is only relevant after the execution of a single INSERT
/// statement, via Database.execute() or UpdateStatement.execute().
public let insertedRowID: Int64?
}
+1 -1
View File
@@ -32,7 +32,7 @@ extension DatabaseError: CustomStringConvertible {
if let sql = sql {
description += " with statement `\(sql)`"
}
if let arguments = arguments {
if let arguments = arguments where !arguments.isEmpty {
description += " arguments \(arguments)"
}
if let message = message {
+1 -1
View File
@@ -139,7 +139,7 @@ public final class DatabaseQueue {
/// inTransaction(), which would create a deadlock
/// - warning the user the he uses a statement outside of the database
/// queue.
private lazy var databaseQueueID: DatabaseQueueID = { [unowned self] in
private lazy var databaseQueueID: DatabaseQueueID = {
unsafeBitCast(self, DatabaseQueueID.self) // pointer to self
}()
+1 -1
View File
@@ -152,7 +152,7 @@ public struct DatabaseValue : Hashable {
/// - returns: A *Value*.
public func value<Value: DatabaseValueConvertible>() -> Value {
guard let value = Value.fromDatabaseValue(self) as Value? else {
fatalError("Could not convert \(self) to \(Value.self).")
fatalError("could not convert \(self) to \(Value.self).")
}
return value
}
+62 -23
View File
@@ -428,7 +428,7 @@ public extension DatabasePersistable {
// MARK: - DataMapper
/// DataMapper takes care of DatabasePersistable CRUD
final class DataMapper {
private class DataMapper {
/// The database
let db: Database
@@ -450,7 +450,7 @@ final class DataMapper {
/// An excerpt from persistentDictionary whose keys are primary key columns.
///
/// It is nil when persistable has no primary key.
lazy var primaryKeyDictionary: [String: DatabaseValueConvertible?]? = { [unowned self] in
lazy var primaryKeyDictionary: [String: DatabaseValueConvertible?]? = {
let columns = self.primaryKey.columns
guard columns.count > 0 else {
return nil
@@ -468,7 +468,7 @@ final class DataMapper {
///
/// It is nil when the primaryKeyDictionary is nil or unable to identify a
/// row in the database.
lazy var resolvingPrimaryKeyDictionary: [String: DatabaseValueConvertible?]? = { [unowned self] in
lazy var resolvingPrimaryKeyDictionary: [String: DatabaseValueConvertible?]? = {
// IMPLEMENTATION NOTE
//
// https://www.sqlite.org/lang_createtable.html
@@ -510,12 +510,12 @@ final class DataMapper {
// Fail early if database table does not exist.
guard let primaryKey = db.primaryKey(databaseTableName) else {
fatalError("Table \(databaseTableName.quotedDatabaseIdentifier) does not exist. See \(persistable.dynamicType).databaseTableName()")
fatalError("no such table: \(databaseTableName)")
}
// Fail early if persistentDictionary is empty
let persistentDictionary = persistable.persistentDictionary
precondition(persistentDictionary.count > 0, "Invalid empty dictionary returned from \(persistable.dynamicType).persistentDictionary")
precondition(persistentDictionary.count > 0, "\(persistable.dynamicType).persistentDictionary: invalid empty dictionary")
self.db = db
self.persistable = persistable
@@ -528,19 +528,20 @@ final class DataMapper {
// MARK: - Statement builders
func insertStatement() -> UpdateStatement {
let insertStatement = try! db.updateStatement(DataMapper.insertSQL(tableName: databaseTableName, insertedColumns: Array(persistentDictionary.keys)))
insertStatement.arguments = StatementArguments(persistentDictionary.values)
let insertStatement = try! db.cachedUpdateStatement(DataMapper.insertSQL(tableName: databaseTableName, insertedColumns: Array(persistentDictionary.keys)))
insertStatement.unsafeSetArguments(StatementArguments(persistentDictionary.values))
return insertStatement
}
func updateStatement() -> UpdateStatement {
// Fail early if primary key does not resolve to a database row.
guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else {
fatalError("Invalid primary key in \(persistable)")
fatalError("invalid primary key in \(persistable)")
}
// Don't update primary key columns
var updatedDictionary = persistentDictionary
// Don't update primary key columns
for column in primaryKeyDictionary.keys {
updatedDictionary.removeValueForKey(column)
}
@@ -555,24 +556,24 @@ final class DataMapper {
//
// The goal is to be able to write tests with minimal tables,
// including tables made of a single primary key column.
updatedDictionary = persistentDictionary
updatedDictionary = primaryKeyDictionary
}
// Update
let updateStatement = try! db.updateStatement(DataMapper.updateSQL(tableName: databaseTableName, updatedColumns: Array(updatedDictionary.keys), conditionColumns: Array(primaryKeyDictionary.keys)))
updateStatement.arguments = StatementArguments(Array(updatedDictionary.values) + Array(primaryKeyDictionary.values))
let updateStatement = try! db.cachedUpdateStatement(DataMapper.updateSQL(tableName: databaseTableName, updatedColumns: Array(updatedDictionary.keys), conditionColumns: Array(primaryKeyDictionary.keys)))
updateStatement.unsafeSetArguments(StatementArguments(Array(updatedDictionary.values) + Array(primaryKeyDictionary.values)))
return updateStatement
}
func deleteStatement() -> UpdateStatement {
// Fail early if primary key does not resolve to a database row.
guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else {
fatalError("Invalid primary key in \(persistable)")
fatalError("invalid primary key in \(persistable)")
}
// Delete
let deleteStatement = try! db.updateStatement(DataMapper.deleteSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys)))
deleteStatement.arguments = StatementArguments(primaryKeyDictionary.values)
let deleteStatement = try! db.cachedUpdateStatement(DataMapper.deleteSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys)))
deleteStatement.unsafeSetArguments(StatementArguments(primaryKeyDictionary.values))
return deleteStatement
}
@@ -581,27 +582,58 @@ final class DataMapper {
func existsStatement() -> SelectStatement {
// Fail early if primary key does not resolve to a database row.
guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else {
fatalError("Invalid primary key in \(persistable)")
fatalError("invalid primary key in \(persistable)")
}
// Fetch
let existsStatement = try! db.selectStatement(DataMapper.existsSQL(tableName: databaseTableName, conditionColumns: Array(primaryKeyDictionary.keys)))
existsStatement.arguments = StatementArguments(primaryKeyDictionary.values)
existsStatement.unsafeSetArguments(StatementArguments(primaryKeyDictionary.values))
return existsStatement
}
// MARK: - SQL query builders
private struct InsertQuery: Hashable {
let tableName: String
let insertedColumns: [String]
var hashValue: Int {
return tableName.hashValue
}
}
private static var insertSQLCache: [InsertQuery: String] = [:]
private class func insertSQL(tableName tableName: String, insertedColumns: [String]) -> String {
let query = InsertQuery(tableName: tableName, insertedColumns: insertedColumns)
if let sql = insertSQLCache[query] {
return sql
}
let columnSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joinWithSeparator(",")
let valuesSQL = Array(count: insertedColumns.count, repeatedValue: "?").joinWithSeparator(",")
return "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnSQL)) VALUES (\(valuesSQL))"
let sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnSQL)) VALUES (\(valuesSQL))"
insertSQLCache[query] = sql
return sql
}
private struct UpdateQuery: Hashable {
let tableName: String
let updatedColumns: [String]
let conditionColumns: [String]
var hashValue: Int {
return tableName.hashValue
}
}
private static var updateSQLCache: [UpdateQuery: String] = [:]
private class func updateSQL(tableName tableName: String, updatedColumns: [String], conditionColumns: [String]) -> String {
let query = UpdateQuery(tableName: tableName, updatedColumns: updatedColumns, conditionColumns: conditionColumns)
if let sql = updateSQLCache[query] {
return sql
}
let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(",")
return "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL(conditionColumns))"
let sql = "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL(conditionColumns))"
updateSQLCache[query] = sql
return sql
}
private class func deleteSQL(tableName tableName: String, conditionColumns: [String]) -> String {
@@ -611,12 +643,19 @@ final class DataMapper {
private class func existsSQL(tableName tableName: String, conditionColumns: [String]) -> String {
return "SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))"
}
private class func reloadSQL(tableName tableName: String, conditionColumns: [String]) -> String {
return "SELECT * FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL(conditionColumns))"
}
private class func whereSQL(conditionColumns: [String]) -> String {
return conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(" AND ")
}
}
private func == (lhs: DataMapper.InsertQuery, rhs: DataMapper.InsertQuery) -> Bool {
if lhs.tableName != rhs.tableName { return false }
return lhs.insertedColumns == rhs.insertedColumns
}
private func == (lhs: DataMapper.UpdateQuery, rhs: DataMapper.UpdateQuery) -> Bool {
if lhs.tableName != rhs.tableName { return false }
if lhs.updatedColumns != rhs.updatedColumns { return false }
return lhs.conditionColumns == rhs.conditionColumns
}
@@ -71,12 +71,12 @@ extension RowConvertible where Self: DatabaseTableMapping {
// Fail early if database table does not exist.
guard let primaryKey = db.primaryKey(databaseTableName) else {
fatalError("Table \(databaseTableName.quotedDatabaseIdentifier) does not exist. See \(self).databaseTableName()")
fatalError("no such table: \(databaseTableName)")
}
// Fail early if database table has not one column in its primary key
let columns = primaryKey.columns
precondition(columns.count == 1, "Primary key of table \(databaseTableName.quotedDatabaseIdentifier) is not made of a single column. See \(self).databaseTableName()")
precondition(columns.count == 1, "expected single column primary key in table: \(databaseTableName)")
let keys = keys.map { $0 as DatabaseValueConvertible? }
@@ -65,20 +65,12 @@ public extension DatabaseValueConvertible {
/// remaining elements are undefined.
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence.
public static func fetch(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Self> {
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
let sqliteStatement = statement.sqliteStatement
return statement.fetch(arguments: arguments) {
let dbv = DatabaseValue(sqliteStatement: sqliteStatement, index: 0)
guard let value = Self.fromDatabaseValue(dbv) else {
if let arguments = statement.arguments {
fatalError("Could not convert \(dbv) to \(Self.self) while iterating `\(statement.sql)` with arguments \(arguments).")
} else {
fatalError("Could not convert \(dbv) to \(Self.self) while iterating `\(statement.sql)`.")
}
}
return value
DatabaseValue(sqliteStatement: sqliteStatement, index: 0).value()
}
}
@@ -88,9 +80,9 @@ public extension DatabaseValueConvertible {
/// let names = String.fetchAll(statement) // [String]
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array.
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> [Self] {
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
return Array(fetch(statement, arguments: arguments))
}
@@ -103,14 +95,13 @@ public extension DatabaseValueConvertible {
/// let name = String.fetchOne(statement) // String?
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional value.
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> Self? {
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
let sequence: DatabaseSequence<Self?> = statement.fetch(arguments: arguments) {
fromDatabaseValue(DatabaseValue(sqliteStatement: statement.sqliteStatement, index: 0))
}
var generator = sequence.generate()
if let value = generator.next() { // Unwrap Self? from Self??
if let value = sequence.generate().next() { // Unwrap Self? from Self??
return value
}
return nil
@@ -137,9 +128,9 @@ public extension DatabaseValueConvertible {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence.
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Self> {
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
}
@@ -149,9 +140,9 @@ public extension DatabaseValueConvertible {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array.
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> [Self] {
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
}
@@ -164,9 +155,9 @@ public extension DatabaseValueConvertible {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional value.
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> Self? {
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments)
}
}
@@ -207,9 +198,9 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// remaining elements are undefined.
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of optional values.
public static func fetch(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Wrapped?> {
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Wrapped?> {
let sqliteStatement = statement.sqliteStatement
return statement.fetch(arguments: arguments) {
Wrapped.fromDatabaseValue(DatabaseValue(sqliteStatement: sqliteStatement, index: 0))
@@ -222,9 +213,9 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// let names = Optional<String>.fetchAll(statement) // [String?]
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of optional values.
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> [Wrapped?] {
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Wrapped?] {
return Array(fetch(statement, arguments: arguments))
}
@@ -249,9 +240,9 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of optional values.
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Wrapped?> {
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Wrapped?> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
}
@@ -261,9 +252,9 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of optional values.
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> [Wrapped?] {
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Wrapped?] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
}
}
+13 -14
View File
@@ -62,9 +62,9 @@ extension RowConvertible {
/// remaining elements are undefined.
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence.
public static func fetch(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Self> {
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
// Metal rows can be reused. And reusing them yields better performance.
let row = Row(metalStatement: statement)
return statement.fetch(arguments: arguments) {
@@ -80,9 +80,9 @@ extension RowConvertible {
/// let persons = Person.fetchAll(statement) // [Person]
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array.
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> [Self] {
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
return Array(fetch(statement, arguments: arguments))
}
@@ -92,11 +92,10 @@ extension RowConvertible {
/// let persons = Person.fetchOne(statement) // Person?
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional value.
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> Self? {
var generator = fetch(statement, arguments: arguments).generate()
return generator.next()
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
return fetch(statement, arguments: arguments).generate().next()
}
@@ -120,9 +119,9 @@ extension RowConvertible {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence.
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Self> {
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
}
@@ -132,9 +131,9 @@ extension RowConvertible {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array.
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> [Self] {
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
}
@@ -144,9 +143,9 @@ extension RowConvertible {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional value.
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> Self? {
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments)
}
}
@@ -52,17 +52,13 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
/// remaining elements are undefined.
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of values.
public static func fetch(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Self> {
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
let sqliteStatement = statement.sqliteStatement
return statement.fetch(arguments: arguments) {
if sqlite3_column_type(sqliteStatement, 0) == SQLITE_NULL {
if let arguments = statement.arguments {
fatalError("Could not convert NULL to \(Self.self) while iterating `\(statement.sql)` with arguments \(arguments).")
} else {
fatalError("Could not convert NULL to \(Self.self) while iterating `\(statement.sql)`.")
}
fatalError("could not convert NULL to \(Self.self).")
} else {
return Self.init(sqliteStatement: sqliteStatement, index: 0)
}
@@ -75,9 +71,9 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
/// let names = String.fetchAll(statement) // [String]
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of values.
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> [Self] {
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
return Array(fetch(statement, arguments: arguments))
}
@@ -87,10 +83,10 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
/// let name = String.fetchOne(statement) // String?
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional value.
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> Self? {
var generator = statement.fetch(arguments: arguments, yield: { }).generate()
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
let generator = statement.fetch(arguments: arguments, yield: { }).generate()
guard generator.next() != nil else {
return nil
}
@@ -122,9 +118,9 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of values.
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Self> {
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
}
@@ -134,9 +130,9 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of values.
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> [Self] {
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
}
@@ -146,9 +142,9 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional value.
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> Self? {
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments)
}
}
+35 -53
View File
@@ -25,12 +25,8 @@ public final class Row: CollectionType {
/// Builds a row from an dictionary of values.
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
var databaseDictionary = [String: DatabaseValue]()
for (key, value) in dictionary {
databaseDictionary[key] = value?.databaseValue ?? .Null
}
self.sqliteStatement = nil
self.impl = DictionaryRowImpl(databaseDictionary: databaseDictionary)
self.impl = DictionaryRowImpl(dictionary: dictionary)
}
/// Returns a copy of the row.
@@ -65,7 +61,7 @@ public final class Row: CollectionType {
/// - parameter index: A column index.
/// - returns: An Int64, Double, String, NSData or nil.
public func value(atIndex index: Int) -> DatabaseValueConvertible? {
precondition(index >= 0 && index < count, "Row index out of range")
precondition(index >= 0 && index < count, "row index out of range")
return impl
.databaseValue(atIndex: index)
.value()
@@ -91,7 +87,7 @@ public final class Row: CollectionType {
/// - parameter index: A column index.
/// - returns: An optional *Value*.
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? {
precondition(index >= 0 && index < count, "Row index out of range")
precondition(index >= 0 && index < count, "row index out of range")
return impl
.databaseValue(atIndex: index)
.value()
@@ -122,7 +118,7 @@ public final class Row: CollectionType {
/// - parameter index: A column index.
/// - returns: An optional *Value*.
public func value<Value: protocol<DatabaseValueConvertible, SQLiteStatementConvertible>>(atIndex index: Int) -> Value? {
precondition(index >= 0 && index < count, "Row index out of range")
precondition(index >= 0 && index < count, "row index out of range")
let sqliteStatement = self.sqliteStatement
if sqliteStatement != nil {
// Metal row
@@ -157,7 +153,7 @@ public final class Row: CollectionType {
/// - parameter index: A column index.
/// - returns: A *Value*.
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value {
precondition(index >= 0 && index < count, "Row index out of range")
precondition(index >= 0 && index < count, "row index out of range")
return impl
.databaseValue(atIndex: index)
.value()
@@ -188,7 +184,7 @@ public final class Row: CollectionType {
/// - parameter index: A column index.
/// - returns: A *Value*.
public func value<Value: protocol<DatabaseValueConvertible, SQLiteStatementConvertible>>(atIndex index: Int) -> Value {
precondition(index >= 0 && index < count, "Row index out of range")
precondition(index >= 0 && index < count, "row index out of range")
let sqliteStatement = self.sqliteStatement
if sqliteStatement != nil {
// Metal row
@@ -196,7 +192,7 @@ public final class Row: CollectionType {
// Perform a NULL check, and prevent SQLite from converting NULL to
// a 0 integer, for example.
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
fatalError("Could not convert NULL to \(Value.self).")
fatalError("could not convert NULL to \(Value.self).")
}
return Value(sqliteStatement: sqliteStatement, index: Int32(index))
} else {
@@ -301,7 +297,7 @@ public final class Row: CollectionType {
/// - returns: An optional *Value*.
public func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value {
guard let index = impl.indexForColumn(named: columnName) else {
fatalError("No such column: \(String(reflecting: columnName))")
fatalError("no such column: \(columnName)")
}
return value(atIndex: index)
}
@@ -332,7 +328,7 @@ public final class Row: CollectionType {
/// - returns: An optional *Value*.
public func value<Value: protocol<DatabaseValueConvertible, SQLiteStatementConvertible>>(named columnName: String) -> Value {
guard let index = impl.indexForColumn(named: columnName) else {
fatalError("No such column: \(String(reflecting: columnName))")
fatalError("no such column: \(columnName)")
}
return value(atIndex: index)
}
@@ -351,7 +347,7 @@ public final class Row: CollectionType {
/// - parameter index: A column index.
/// - returns: An optional NSData.
public func dataNoCopy(atIndex index: Int) -> NSData? {
precondition(index >= 0 && index < count, "Row index out of range")
precondition(index >= 0 && index < count, "row index out of range")
return impl.dataNoCopy(atIndex: index)
}
@@ -473,9 +469,9 @@ public final class Row: CollectionType {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of rows.
public static func fetch(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<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(metalStatement: statement)
return statement.fetch(arguments: arguments) { row }
@@ -487,9 +483,9 @@ public final class Row: CollectionType {
/// let rows = Row.fetchAll(statement)
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of rows.
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> [Row] {
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Row] {
let sequence = statement.fetch(arguments: arguments) {
Row(detachedStatement: statement)
}
@@ -502,14 +498,13 @@ public final class Row: CollectionType {
/// let row = Row.fetchOne(statement)
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional row.
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> Row? {
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Row? {
let sequence = statement.fetch(arguments: arguments) {
Row(detachedStatement: statement)
}
var generator = sequence.generate()
return generator.next()
return sequence.generate().next()
}
@@ -544,9 +539,9 @@ public final class Row: CollectionType {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of rows.
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Row> {
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Row> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
}
@@ -556,9 +551,9 @@ public final class Row: CollectionType {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of rows.
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> [Row] {
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Row] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
}
@@ -568,28 +563,15 @@ public final class Row: CollectionType {
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional row.
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> Row? {
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Row? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments)
}
// MARK: - Not Public
/// There a three different RowImpl:
///
/// - MetalRowImpl: metal rows grant direct access to the current state of
/// an SQLite statement. Such rows are reused during the iteration of a
/// statement.
///
/// - DetachedRowImpl: detached rows hold a copy of the values that come
/// from an SQLite statement.
///
/// - DictionaryRowImpl: dictionary rows are created by the library users.
/// They do not come from the database.
///
/// - EmptyRowImpl: empty row
let impl: RowImpl
/// Only metal rows have a SQLiteStatement.
@@ -622,16 +604,16 @@ public final class Row: CollectionType {
// MARK: - DictionaryRowImpl
/// See Row.init(databaseDictionary:)
/// See Row.init(dictionary:)
private struct DictionaryRowImpl : RowImpl {
let databaseDictionary: [String: DatabaseValue]
let dictionary: [String: DatabaseValueConvertible?]
init (databaseDictionary: [String: DatabaseValue]) {
self.databaseDictionary = databaseDictionary
init (dictionary: [String: DatabaseValueConvertible?]) {
self.dictionary = dictionary
}
var count: Int {
return databaseDictionary.count
return dictionary.count
}
func dataNoCopy(atIndex index:Int) -> NSData? {
@@ -639,20 +621,20 @@ public final class Row: CollectionType {
}
func databaseValue(atIndex index: Int) -> DatabaseValue {
return databaseDictionary[databaseDictionary.startIndex.advancedBy(index)].1
return dictionary[dictionary.startIndex.advancedBy(index)].1?.databaseValue ?? .Null
}
func columnName(atIndex index: Int) -> String {
return databaseDictionary[databaseDictionary.startIndex.advancedBy(index)].0
return dictionary[dictionary.startIndex.advancedBy(index)].0
}
// This method MUST be case-insensitive.
func indexForColumn(named name: String) -> Int? {
let lowercaseName = name.lowercaseString
guard let index = databaseDictionary.indexOf({ (column, value) in column.lowercaseString == lowercaseName }) else {
guard let index = dictionary.indexOf({ (column, value) in column.lowercaseString == lowercaseName }) else {
return nil
}
return databaseDictionary.startIndex.distanceTo(index)
return dictionary.startIndex.distanceTo(index)
}
func copiedRow(row: Row) -> Row {
@@ -753,15 +735,15 @@ public final class Row: CollectionType {
var count: Int { return 0 }
func databaseValue(atIndex index: Int) -> DatabaseValue {
fatalError("Empty row has no column")
fatalError("row index out of range")
}
func dataNoCopy(atIndex index:Int) -> NSData? {
fatalError("Empty row has no column")
fatalError("row index out of range")
}
func columnName(atIndex index: Int) -> String {
fatalError("Empty row has no column")
fatalError("row index out of range")
}
func indexForColumn(named name: String) -> Int? {
-103
View File
@@ -1,103 +0,0 @@
/// A subclass of Statement that fetches database rows.
///
/// You create SelectStatement with the Database.selectStatement() method:
///
/// dbQueue.inDatabase { db in
/// let statement = db.selectStatement("SELECT * FROM persons WHERE age > ?")
/// let moreThanTwentyCount = Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement {
/// The number of columns in the resulting rows.
public lazy var columnCount: Int = { [unowned self] in
Int(sqlite3_column_count(self.sqliteStatement))
}()
/// The column names, ordered from left to right.
public lazy var columnNames: [String] = { [unowned self] in
(0..<self.columnCount).map { index in
return String.fromCString(sqlite3_column_name(self.sqliteStatement, Int32(index)))!
}
}()
// MARK: - Not public
/// The DatabaseSequence builder.
func fetch<T>(arguments arguments: StatementArguments, yield: () -> T) -> DatabaseSequence<T> {
if !arguments.isDefault {
self.arguments = arguments
}
validateArguments()
return DatabaseSequence(statement: self, yield: yield)
}
/// The column index, case insensitive.
func indexForColumn(named name: String) -> Int? {
return lowercaseColumnIndexes[name] ?? lowercaseColumnIndexes[name.lowercaseString]
}
/// Support for indexForColumn(named:)
private lazy var lowercaseColumnIndexes: [String: Int] = { [unowned self] in
var indexes = [String: Int]()
let count = self.columnCount
// Reverse so that we return indexes for the leftmost columns.
// SELECT 1 AS a, 2 AS a -> lowercaseColumnIndexes["a”] = 0
for (index, columnName) in self.columnNames.reverse().enumerate() {
indexes[columnName.lowercaseString] = count - index - 1
}
return indexes
}()
}
/// A sequence of elements fetched from the database.
public struct DatabaseSequence<T>: SequenceType {
private let generateImpl: () -> DatabaseGenerator<T>
private init(statement: SelectStatement, yield: () -> T) {
generateImpl = {
let preconditionValidQueue = statement.database.preconditionValidQueue
let sqliteStatement = statement.sqliteStatement
// Check that sequence is built on a valid queue.
preconditionValidQueue()
// DatabaseSequence can be restarted:
statement.reset()
return DatabaseGenerator {
// Check that generator is used on a valid queue.
preconditionValidQueue()
let code = sqlite3_step(sqliteStatement)
switch code {
case SQLITE_DONE:
return nil
case SQLITE_ROW:
return yield()
default:
fatalError(DatabaseError(code: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments).description)
}
}
}
}
init() {
generateImpl = { return DatabaseGenerator { return nil } }
}
/// Return a *generator* over the elements of this *sequence*.
@warn_unused_result
public func generate() -> DatabaseGenerator<T> {
return generateImpl()
}
}
/// A generator of elements fetched from the database.
public struct DatabaseGenerator<T>: GeneratorType {
private let nextImpl: () -> T?
public mutating func next() -> T? {
return nextImpl()
}
}
+490 -68
View File
@@ -13,23 +13,24 @@ public class Statement {
/// The SQL query
public let sql: String
/// The query arguments
public var arguments: StatementArguments? {
didSet {
validateArguments()
reset() // necessary before applying new arguments
clearBindings()
if let arguments = arguments {
arguments.bindInStatement(self)
}
}
/// The statement arguments
public var arguments: StatementArguments {
get { return _arguments }
set { try! setArgumentsWithValidation(newValue) }
}
// MARK: - Not public
// MARK: Not public
/// The database
let database: Database
init(database: Database, sql: String, sqliteStatement: SQLiteStatement) {
self.database = database
self.sql = sql
self.sqliteStatement = sqliteStatement
}
init(database: Database, sql: String) throws {
database.preconditionValidQueue()
@@ -53,8 +54,9 @@ public class Statement {
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql)
}
guard consumedCharactersCount == sqlCodeUnits.count else {
fatalError("Invalid SQL string: multiple statements found. To execute multiple statements, use Database.executeMultiStatement() instead.")
throw DatabaseError(code: SQLITE_MISUSE, message: "Invalid SQL string: multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
}
}
@@ -73,84 +75,169 @@ public class Statement {
}
// MARK: - Arguments
// MARK: Arguments
private var argumentCount: Int {
return Int(sqlite3_bind_parameter_count(sqliteStatement))
}
var argumentsNeedValidation = true
var _arguments: StatementArguments = []
private lazy var sqliteArgumentNames: Set<String> = { [unowned self] in
let sqliteStatement = self.sqliteStatement
var argumentNames = Set<String>()
for i in 1...self.argumentCount {
if let name = String.fromCString(sqlite3_bind_parameter_name(sqliteStatement, Int32(i))) {
argumentNames.insert(name)
}
}
return argumentNames
lazy var sqliteArgumentCount: Int = {
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
}()
func validateArguments() {
if let argumentsKind = arguments?.kind {
switch argumentsKind {
case .Default:
fatalError("Invalid StatementArguments.Default arguments in `\(sql)`.")
case .Array(count: let count):
if count != argumentCount {
fatalError("SQLite statement arguments mismatch: got \(count) argument(s) instead of \(argumentCount) in `\(sql)`.")
}
case .Dictionary(keys: let keys):
let inputArgumentNames = keys.map { ":\($0)" }
if Set(inputArgumentNames) != sqliteArgumentNames {
func caseInsensitiveSort(strings: [String]) -> [String] {
return strings
.map { ($0.lowercaseString, $0) }
.sort { $0.0 < $1.0 }
.map { $0.1 }
}
let input = caseInsensitiveSort(inputArgumentNames).joinWithSeparator(",")
let expected = caseInsensitiveSort(Array(sqliteArgumentNames)).joinWithSeparator(",")
fatalError("SQLite statement argument names mismatch: got [\(input)] instead of [\(expected)] in `\(sql)`.")
// Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
private lazy var sqliteArgumentNames: [String?] = {
guard self.sqliteArgumentCount > 0 else {
return []
}
return (1...self.sqliteArgumentCount).map {
guard let parameterName = String.fromCString(sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0))) else {
return nil
}
return String(parameterName.characters.dropFirst()) // Drop initial ":"
}
}()
/// Set arguments without any validation. Trades safety for performance.
func unsafeSetArguments(arguments: StatementArguments) {
_arguments = arguments
argumentsNeedValidation = false
// Apply
reset()
clearBindings()
switch arguments.kind {
case .Array(let array):
for (index, value) in array.enumerate() {
try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1))
}
break
case .Dictionary(let dictionary):
// TODO: test
for (index, argumentName) in sqliteArgumentNames.enumerate() {
if let argumentName = argumentName, let value = dictionary[argumentName] {
try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1))
}
}
} else if argumentCount > 0 {
fatalError("SQLite statement arguments mismatch: got 0 argument(s) instead of \(argumentCount) in `\(sql)`.")
}
}
// Exposed for StatementArguments. Don't make this one public unless we keep
// the arguments property in sync.
//
// As in sqlite3_bind_xxx methods, index is one-based.
final func setArgument(value: DatabaseValueConvertible?, atIndex index: Int) {
let databaseValue = value?.databaseValue ?? .Null
let code: Int32
private func setArgumentsWithValidation(arguments: StatementArguments) throws {
// Validate
let bindings = try validatedBindings(arguments)
_arguments = arguments
argumentsNeedValidation = false
// Apply
reset()
clearBindings()
for (index, databaseValue) in bindings.enumerate() {
try bindDatabaseValue(databaseValue, atIndex: Int32(index + 1))
}
}
private func bindDatabaseValue(databaseValue: DatabaseValue, atIndex index: Int32) throws {
let code: Int32
switch databaseValue.storage {
case .Null:
code = sqlite3_bind_null(sqliteStatement, Int32(index))
code = sqlite3_bind_null(sqliteStatement, index)
case .Int64(let int64):
code = sqlite3_bind_int64(sqliteStatement, Int32(index), int64)
code = sqlite3_bind_int64(sqliteStatement, index, int64)
case .Double(let double):
code = sqlite3_bind_double(sqliteStatement, Int32(index), double)
code = sqlite3_bind_double(sqliteStatement, index, double)
case .String(let string):
code = sqlite3_bind_text(sqliteStatement, Int32(index), string, -1, SQLITE_TRANSIENT)
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
case .Blob(let data):
code = sqlite3_bind_blob(sqliteStatement, Int32(index), data.bytes, Int32(data.length), SQLITE_TRANSIENT)
code = sqlite3_bind_blob(sqliteStatement, index, data.bytes, Int32(data.length), SQLITE_TRANSIENT)
}
if code != SQLITE_OK {
fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description)
throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql)
}
}
// Exposed for StatementArguments. Don't make this one public unless we keep
// the arguments property in sync.
final func setArgument(value: DatabaseValueConvertible?, forKey key: String) {
let argumentName = ":\(key)"
let index = Int(sqlite3_bind_parameter_index(sqliteStatement, argumentName))
precondition(index > 0, "Argument not found in SQLite statement: `\(argumentName)`")
setArgument(value, atIndex: index)
/// 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)
}
// Returns a validated array of as many DatabaseValue as there are
// parameters in the statement.
@warn_unused_result
private func validatedBindings(arguments: StatementArguments) throws -> [DatabaseValue] {
// An array of (key, value) pairs.
//
// The key is not nil if the statement has a named parameter at given index.
// The value is not nil if the arguments have a value at given index.
//
// The array may be longer than the number of arguments in the statement.
//
// If the returned array is longer than the number of arguments in the statement,
// then we have extra arguments.
//
// If one of the values is nil, then we have a missing argument.
let keyValueBindings: [(String?, DatabaseValue?)] = {
switch arguments.kind {
case .Array(let array):
var keyValueBindings: [(String?, DatabaseValue?)] = []
var argumentNameGen = sqliteArgumentNames.generate()
var valuesGen = array.map { $0?.databaseValue ?? .Null }.generate()
var argumentNameOpt = argumentNameGen.next()
var valueOpt = valuesGen.next()
outer: while true {
switch (argumentNameOpt, valueOpt) {
case (let argumentName?, let value?):
keyValueBindings.append((argumentName, value))
argumentNameOpt = argumentNameGen.next()
valueOpt = valuesGen.next()
case (nil, let value?):
keyValueBindings.append((nil, value))
valueOpt = valuesGen.next()
case (let argumentName?, nil):
keyValueBindings.append((argumentName, nil))
argumentNameOpt = argumentNameGen.next()
case (nil, nil):
break outer
}
}
return keyValueBindings
case .Dictionary(let dictionary):
return sqliteArgumentNames.map { argumentName in
if let argumentName = argumentName {
if let value = dictionary[argumentName] {
return (argumentName, value?.databaseValue ?? .Null)
} else {
return (argumentName, nil)
}
}
return (nil, nil)
}
}
}()
assert(keyValueBindings.count >= sqliteArgumentCount)
if keyValueBindings.count > sqliteArgumentCount {
throw DatabaseError(code: SQLITE_MISUSE, message: "wrong number of statement arguments: \(keyValueBindings.count)", sql: sql, arguments: nil)
}
if case let missingKeys = keyValueBindings.filter({ $0.1 == nil }).map({ $0.0 }) where !missingKeys.isEmpty {
if case let namedMissingKeys = missingKeys.flatMap({ $0 }) where namedMissingKeys.count == missingKeys.count {
func caseInsensitiveSort(strings: [String]) -> [String] {
return strings
.map { ($0.lowercaseString, $0) }
.sort { $0.0 < $1.0 }
.map { $0.1 }
}
throw DatabaseError(code: SQLITE_MISUSE, message: "missing statement argument(s): \(caseInsensitiveSort(namedMissingKeys).joinWithSeparator(", "))", sql: sql, arguments: nil)
} else {
throw DatabaseError(code: SQLITE_MISUSE, message: "wrong number of statement arguments: \(sqliteArgumentCount - missingKeys.count)", sql: sql, arguments: nil)
}
}
return keyValueBindings.map { $0.1! }
}
// Don't make this one public unless we keep the arguments property in sync.
@@ -160,8 +247,343 @@ public class Statement {
fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description)
}
}
private func prepareWithArguments(arguments: StatementArguments?) throws {
if let arguments = arguments {
try setArgumentsWithValidation(arguments)
} else if argumentsNeedValidation {
try validateArguments(self.arguments)
}
}
}
// MARK: - SelectStatement
/// A subclass of Statement that fetches database rows.
///
/// You create SelectStatement with the Database.selectStatement() method:
///
/// dbQueue.inDatabase { db in
/// let statement = db.selectStatement("SELECT * FROM persons WHERE age > ?")
/// let moreThanTwentyCount = Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement {
/// The number of columns in the resulting rows.
public lazy var columnCount: Int = {
Int(sqlite3_column_count(self.sqliteStatement))
}()
/// 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)))! }
}()
// MARK: Not public
/// The DatabaseSequence builder.
func fetch<T>(arguments arguments: StatementArguments?, yield: () -> T) -> DatabaseSequence<T> {
try! prepareWithArguments(arguments)
return DatabaseSequence(statement: self, yield: yield)
}
/// The column index, case insensitive.
func indexForColumn(named name: String) -> Int? {
return lowercaseColumnIndexes[name] ?? lowercaseColumnIndexes[name.lowercaseString]
}
/// Support for indexForColumn(named:)
private lazy var lowercaseColumnIndexes: [String: Int] = {
var indexes = [String: Int]()
let count = self.columnCount
// Reverse so that we return indexes for the leftmost columns.
// SELECT 1 AS a, 2 AS a -> lowercaseColumnIndexes["a”] = 0
for (index, columnName) in self.columnNames.reverse().enumerate() {
indexes[columnName.lowercaseString] = count - index - 1
}
return indexes
}()
}
/// A sequence of elements fetched from the database.
public struct DatabaseSequence<T>: SequenceType {
private let generateImpl: () -> DatabaseGenerator<T>
private init(statement: SelectStatement, yield: () -> T) {
generateImpl = {
let preconditionValidQueue = statement.database.preconditionValidQueue
let sqliteStatement = statement.sqliteStatement
// Check that sequence is built on a valid queue.
preconditionValidQueue()
// DatabaseSequence can be restarted:
statement.reset()
return DatabaseGenerator {
// Check that generator is used on a valid queue.
preconditionValidQueue()
let code = sqlite3_step(sqliteStatement)
switch code {
case SQLITE_DONE:
return nil
case SQLITE_ROW:
return yield()
default:
fatalError(DatabaseError(code: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments).description)
}
}
}
}
init() {
generateImpl = { return DatabaseGenerator { return nil } }
}
/// Return a *generator* over the elements of this *sequence*.
@warn_unused_result
public func generate() -> DatabaseGenerator<T> {
return generateImpl()
}
}
/// A generator of elements fetched from the database.
public struct DatabaseGenerator<T>: GeneratorType {
private let nextImpl: () -> T?
public func next() -> T? {
return nextImpl()
}
}
// MARK: - UpdateStatement
/// A subclass of Statement that executes SQL queries.
///
/// You create UpdateStatement with the Database.updateStatement() method:
///
/// try dbQueue.inTransaction { db in
/// let statement = try db.updateStatement("INSERT INTO persons (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// return .Commit
/// }
public final class UpdateStatement : Statement {
/// Executes the SQL query.
///
/// - parameter arguments: Statement arguments.
/// - returns: A DatabaseChanges.
/// - throws: A DatabaseError whenever a SQLite error occurs.
public func execute(arguments arguments: StatementArguments? = nil) throws -> DatabaseChanges {
try! prepareWithArguments(arguments) // Crash on invalid arguments
reset()
let changes: DatabaseChanges
let code = sqlite3_step(sqliteStatement)
switch code {
case SQLITE_DONE:
let changedRowCount = Int(sqlite3_changes(database.sqliteConnection))
let lastInsertedRowID = sqlite3_last_insert_rowid(database.sqliteConnection)
let insertedRowID: Int64? = (lastInsertedRowID == 0) ? nil : lastInsertedRowID
changes = DatabaseChanges(changedRowCount: changedRowCount, insertedRowID: insertedRowID)
case SQLITE_ROW:
// A row? The UpdateStatement is not supposed to return any...
//
// What are our options?
//
// 1. throw a DatabaseError with code SQLITE_ROW.
// 2. raise a fatal error.
// 3. log a warning about the ignored row, and return successfully.
// 4. silently ignore the row, and return successfully.
//
// The problem with 1 is that this error is uneasy to understand.
// See https://github.com/groue/GRDB.swift/issues/15 where both the
// user and I were stupidly stuck in front of `PRAGMA journal_mode=WAL`.
//
// The problem with 2 is that the user would be forced to load a
// value he does not care about (even if he should, but we can't
// judge).
//
// The problem with 3 is that there is no way to avoid this warning.
//
// So let's just silently ignore the row, and return successfully.
changes = DatabaseChanges(changedRowCount: 0, insertedRowID: nil)
default:
// This error may be a consequence of an error thrown by
// TransactionObserverType.transactionWillCommit().
// Let database handle this case, before throwing a error:
try database.updateStatementDidFail()
let errorArguments = self.arguments // self.arguments, not the arguments parameter.
throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql, arguments: errorArguments)
}
// Now that changes information has been loaded, we can trigger database
// transaction delegate callbacks that may eventually perform more
// changes to the database.
database.updateStatementDidExecute()
return changes
}
}
/// Represents the various changes made to the database via execution of one or
/// more SQL statements.
public struct DatabaseChanges {
/// The number of rows affected by the statement(s)
public let changedRowCount: Int
/// The inserted Row ID.
///
/// This value is only relevant after the execution of a single INSERT
/// statement, via Database.execute() or UpdateStatement.execute().
public let insertedRowID: Int64?
}
// MARK: - StatementArguments
/// SQL statements can have arguments:
///
/// INSERT INTO persons (name, age) VALUES (?, ?)
/// INSERT INTO persons (name, age) VALUES (:name, :age)
///
/// To fill question mark arguments, feed StatementArguments with an array:
///
/// db.execute("INSERT ... (?, ?)", arguments: StatementArguments(["Arthur", 41]))
///
/// Array literals are automatically converted to StatementArguments:
///
/// db.execute("INSERT ... (?, ?)", arguments: ["Arthur", 41])
///
/// To fill named arguments, feed StatementArguments with a dictionary:
///
/// db.execute("INSERT ... (:name, :age)", arguments: StatementArguments(["name": "Arthur", "age": 41]))
///
/// Dictionary literals are automatically converted to StatementArguments:
///
/// db.execute("INSERT ... (:name, :age)", arguments: ["name": "Arthur", "age": 41])
///
/// See https://www.sqlite.org/lang_expr.html#varparam for more information.
public struct StatementArguments {
// MARK: Positional Arguments
/// Initializes arguments from a sequence of optional values.
///
/// let values: [String?] = ["foo", "bar", nil]
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of optional values that adopt the
/// DatabaseValueConvertible protocol.
/// - returns: A StatementArguments.
public init<Sequence: SequenceType where Sequence.Generator.Element == Optional<DatabaseValueConvertible>>(_ sequence: Sequence) {
kind = .Array(Array(sequence))
}
// MARK: Named Arguments
/// Initializes arguments from a dictionary of optional values.
///
/// let values: [String: String?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
///
/// - parameter dictionary: A dictionary of optional values that adopt the
/// DatabaseValueConvertible protocol.
/// - returns: A StatementArguments.
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
kind = .Dictionary(dictionary)
}
public var isEmpty: Bool {
switch kind {
case .Array(let array):
return array.isEmpty
case .Dictionary(let dictionary):
return dictionary.isEmpty
}
}
// MARK: Not Public
enum Kind {
case Array([DatabaseValueConvertible?])
case Dictionary([String: DatabaseValueConvertible?])
}
let kind: Kind
private init(kind: Kind) {
self.kind = kind
}
}
extension StatementArguments : ArrayLiteralConvertible {
/// Returns a StatementArguments from an array literal:
///
/// db.selectRows("SELECT ...", arguments: ["Arthur", 41])
public init(arrayLiteral elements: DatabaseValueConvertible?...) {
self.init(elements)
}
}
extension StatementArguments : DictionaryLiteralConvertible {
/// Returns a StatementArguments from a dictionary literal:
///
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "age": 41])
public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
var dictionary = [String: DatabaseValueConvertible?]()
for (key, value) in elements {
dictionary[key] = value
}
self.init(dictionary)
}
}
extension StatementArguments : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch kind {
case .Array(let values):
return "["
+ values
.map { value in
if let value = value {
return String(reflecting: value)
} else {
return "nil"
}
}
.joinWithSeparator(", ")
+ "]"
case .Dictionary(let dictionary):
return "["
+ dictionary.map { (key, value) in
if let value = value {
return "\(key):\(String(reflecting: value))"
} else {
return "\(key):nil"
}
}
.joinWithSeparator(", ")
+ "]"
}
}
}
// MARK: - SQLite identifier quoting
extension String {
-251
View File
@@ -1,251 +0,0 @@
/// SQL statements can have arguments:
///
/// INSERT INTO persons (name, age) VALUES (?, ?)
/// INSERT INTO persons (name, age) VALUES (:name, :age)
///
/// To fill question mark arguments, feed StatementArguments with an array:
///
/// db.execute("INSERT ... (?, ?)", arguments: StatementArguments(["Arthur", 41]))
///
/// Array literals are automatically converted to StatementArguments:
///
/// db.execute("INSERT ... (?, ?)", arguments: ["Arthur", 41])
///
/// To fill named arguments, feed StatementArguments with a dictionary:
///
/// db.execute("INSERT ... (:name, :age)", arguments: StatementArguments(["name": "Arthur", "age": 41]))
///
/// Dictionary literals are automatically converted to StatementArguments:
///
/// db.execute("INSERT ... (:name, :age)", arguments: ["name": "Arthur", "age": 41])
///
/// GRDB.swift only supports colon-prefixed named arguments, even though SQLite
/// supports other syntaxes. See https://www.sqlite.org/lang_expr.html#varparam
/// for more information.
public struct StatementArguments {
// MARK: - Positional Arguments
/// Initializes arguments from a sequence of optional values.
///
/// let values: [String?] = ["foo", "bar", nil]
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of optional values that adopt the
/// DatabaseValueConvertible protocol.
/// - returns: A StatementArguments.
public init<Sequence: SequenceType where Sequence.Generator.Element == Optional<DatabaseValueConvertible>>(_ sequence: Sequence) {
impl = StatementArgumentsArrayImpl(values: Array(sequence))
}
// MARK: - Named Arguments
/// Initializes arguments from a dictionary of optional values.
///
/// let values: [String: String?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
///
/// GRDB.swift only supports colon-prefixed named arguments, even though
/// SQLite supports other syntaxes. See https://www.sqlite.org/lang_expr.html#varparam
/// for more information.
///
/// - parameter dictionary: A dictionary of optional values that adopt the
/// DatabaseValueConvertible protocol.
/// - returns: A StatementArguments.
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
impl = StatementArgumentsDictionaryImpl(dictionary: dictionary)
}
// MARK: - Default Arguments
/// Whenever you need to write a method with optional statement arguments,
/// do not use nil as a sentinel. This is because StatementArguments has
/// failable initializers, and you do not want such a failed initializer
/// have your method behave as if no arguments was given.
///
/// Instead, use a non-optional StatementArguments parameter type, and use
/// StatementArguments.Default as its default value.
///
/// Compare:
///
/// func bad(arguments: StatementArguments? = nil)
/// func good(arguments: StatementArguments = StatementArguments.Default)
///
/// let badDict: NSDictionary = ["foo": NSObject()] // can't be used as arguments
/// let arguments = StatementArguments(badDict) // nil, actually
///
/// // Bad function swallows nil. Bad, bad function!
/// bad(arguments: arguments)
///
/// // Good function forces the user to handle the invalid input case:
/// good(arguments: arguments) // won't compile
/// if let arguments = arguments {
/// good(arguments: arguments)
/// } else {
/// // handle wrong dictionary
/// }
public static var Default = StatementArguments(impl: DefaultStatementArgumentsImpl())
/// True if and only if the receiver is StatementArguments.Default.
public var isDefault: Bool { return kind.isDefault }
// MARK: - Not Public
let impl: StatementArgumentsImpl
var kind: StatementArgumentsKind { return impl.kind }
init(impl: StatementArgumentsImpl) {
self.impl = impl
}
// Supported usage: Statement.arguments property
//
// let statement = db.UpdateStatement("INSERT INTO persons (name, age) VALUES (?,?)"
// statement.execute(arguments: ["Arthur", 41])
func bindInStatement(statement: Statement) {
impl.bindInStatement(statement)
}
// Mark: - StatementArguments.DefaultImpl
private struct DefaultStatementArgumentsImpl : StatementArgumentsImpl {
var kind: StatementArgumentsKind { return .Default }
func bindInStatement(statement: Statement) {
fatalError("DefaultStatementArgumentsImpl is a sentinel value and must not be used.")
}
var description: String {
return "StatementArguments.DefaultImpl"
}
}
// MARK: - StatementArgumentsArrayImpl
/// Support for positional arguments
private struct StatementArgumentsArrayImpl : StatementArgumentsImpl {
let values: [DatabaseValueConvertible?]
var kind: StatementArgumentsKind { return .Array(count: values.count) }
init(values: [DatabaseValueConvertible?]) {
self.values = values
}
func bindInStatement(statement: Statement) {
for (index, value) in values.enumerate() {
statement.setArgument(value, atIndex: index + 1)
}
}
var description: String {
return "["
+ values
.map { value in
if let value = value {
return String(reflecting: value)
} else {
return "nil"
}
}
.joinWithSeparator(", ")
+ "]"
}
}
// MARK: - StatementArgumentsDictionaryImpl
/// Support for named arguments
private struct StatementArgumentsDictionaryImpl : StatementArgumentsImpl {
let dictionary: [String: DatabaseValueConvertible?]
var kind: StatementArgumentsKind { return .Dictionary(keys: Array(dictionary.keys)) }
init(dictionary: [String: DatabaseValueConvertible?]) {
self.dictionary = dictionary
}
func bindInStatement(statement: Statement) {
for (key, value) in dictionary {
statement.setArgument(value, forKey: key) // crash if key is not found
}
}
var description: String {
return "["
+ dictionary.map { (key, value) in
if let value = value {
return "\(key):\(String(reflecting: value))"
} else {
return "\(key):nil"
}
}
.joinWithSeparator(", ")
+ "]"
}
}
}
// This enum lets Statement validate its arguments.
enum StatementArgumentsKind {
case Default
case Array(count: Int)
case Dictionary(keys: [String])
var isDefault: Bool {
switch self {
case .Default:
return true
default:
return false
}
}
}
// The protocol for StatementArguments underlying implementation
protocol StatementArgumentsImpl : CustomStringConvertible {
var kind: StatementArgumentsKind { get }
func bindInStatement(statement: Statement)
}
// MARK: - ArrayLiteralConvertible
extension StatementArguments : ArrayLiteralConvertible {
/// Returns a StatementArguments from an array literal:
///
/// db.selectRows("SELECT ...", arguments: ["Arthur", 41])
public init(arrayLiteral elements: DatabaseValueConvertible?...) {
self.init(elements)
}
}
// MARK: - DictionaryLiteralConvertible
extension StatementArguments : DictionaryLiteralConvertible {
/// Returns a StatementArguments from a dictionary literal:
///
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "age": 41])
public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
var dictionary = [String: DatabaseValueConvertible?]()
for (key, value) in elements {
dictionary[key] = value
}
self.init(dictionary)
}
}
// MARK: - CustomStringConvertible
extension StatementArguments : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return impl.description
}
}
-71
View File
@@ -1,71 +0,0 @@
/// A subclass of Statement that executes SQL queries.
///
/// You create UpdateStatement with the Database.updateStatement() method:
///
/// try dbQueue.inTransaction { db in
/// let statement = try db.updateStatement("INSERT INTO persons (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// return .Commit
/// }
public final class UpdateStatement : Statement {
/// Executes the SQL query.
///
/// - parameter arguments: Statement arguments.
/// - returns: A DatabaseChanges.
/// - throws: A DatabaseError whenever a SQLite error occurs.
public func execute(arguments arguments: StatementArguments = StatementArguments.Default) throws -> DatabaseChanges {
if !arguments.isDefault {
self.arguments = arguments
}
validateArguments()
reset()
let changes: DatabaseChanges
let code = sqlite3_step(sqliteStatement)
switch code {
case SQLITE_DONE:
let changedRowCount = Int(sqlite3_changes(database.sqliteConnection))
let lastInsertedRowID = sqlite3_last_insert_rowid(database.sqliteConnection)
let insertedRowID: Int64? = (lastInsertedRowID == 0) ? nil : lastInsertedRowID
changes = DatabaseChanges(changedRowCount: changedRowCount, insertedRowID: insertedRowID)
case SQLITE_ROW:
// A row? The UpdateStatement is not supposed to return any...
//
// What are our options?
//
// 1. throw a DatabaseError with code SQLITE_ROW.
// 2. raise a fatal error.
// 3. log a warning about the ignored row, and return successfully.
// 4. silently ignore the row, and return successfully.
//
// The problem with 1 is that this error is uneasy to understand.
// See https://github.com/groue/GRDB.swift/issues/15 where both the
// user and I were stupidly stuck in front of `PRAGMA journal_mode=WAL`.
//
// The problem with 2 is that the user would be forced to load a
// value he does not care about (even if he should, but we can't
// judge).
//
// The problem with 3 is that there is no way to avoid this warning.
//
// So let's just silently ignore the row, and return successfully.
changes = DatabaseChanges(changedRowCount: 0, insertedRowID: nil)
default:
// This error may be a consequence of an error thrown by
// TransactionObserverType.transactionWillCommit().
// Let database handle this case, before throwing a error.
try database.updateStatementDidFail()
let errorArguments = self.arguments // self.arguments, not the arguments parameter.
throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql, arguments: errorArguments)
}
// Now that changes information has been loaded, we can trigger database
// transaction delegate callbacks that may eventually perform more
// changes to the database.
database.updateStatementDidExecute()
return changes
}
}
-8
View File
@@ -23,12 +23,4 @@ extension NSData : DatabaseValueConvertible {
return nil
}
}
public static func fromRow(row: Row) -> Self {
// TODO: test
guard let data = fromDatabaseValue(row.databaseValues.first!) else {
fatalError("Could not convert \(row.databaseValues.first!) to NSData.")
}
return data
}
}
-8
View File
@@ -68,14 +68,6 @@ extension NSDate : DatabaseValueConvertible {
return nil
}
public static func fromRow(row: Row) -> Self {
// TODO: test
guard let date = fromDatabaseValue(row.databaseValues.first!) else {
fatalError("Could not convert \(row.databaseValues.first!) to NSDate.")
}
return date
}
}
/// The DatabaseDate date formatter for stored dates.
-5
View File
@@ -12,9 +12,4 @@ extension NSNull: DatabaseValueConvertible {
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
return nil
}
public static func fromRow(row: Row) -> Self {
// TODO: test
fatalError("Could not convert \(row.databaseValues.first!) to NSNull.")
}
}
-8
View File
@@ -52,12 +52,4 @@ extension NSNumber: DatabaseValueConvertible {
return nil
}
}
public static func fromRow(row: Row) -> Self {
// TODO: test
guard let number = fromDatabaseValue(row.databaseValues.first!) else {
fatalError("Could not convert \(row.databaseValues.first!) to NSNumber.")
}
return number
}
}
-8
View File
@@ -18,12 +18,4 @@ extension NSString: DatabaseValueConvertible {
}
return self.init(string: string)
}
public static func fromRow(row: Row) -> Self {
// TODO: test
guard let string = fromDatabaseValue(row.databaseValues.first!) else {
fatalError("Could not convert \(row.databaseValues.first!) to NSString.")
}
return string
}
}
-8
View File
@@ -19,12 +19,4 @@ extension NSURL : DatabaseValueConvertible {
}
return self.init(string: string)
}
public static func fromRow(row: Row) -> Self {
// TODO: test
guard let url = fromDatabaseValue(row.databaseValues.first!) else {
fatalError("Could not convert \(row.databaseValues.first!) to NSURL.")
}
return url
}
}
@@ -2,6 +2,8 @@ import Foundation
extension StatementArguments {
// MARK: Positional Arguments
/// Initializes arguments from an NSArray.
///
/// The result is nil unless all objects adopt DatabaseValueConvertible
@@ -35,6 +37,9 @@ extension StatementArguments {
self.init(values)
}
// MARK: Named Arguments
/// Initializes arguments from an NSDictionary.
///
/// The result is nil unless all dictionary keys are strings, and values
@@ -44,10 +49,6 @@ extension StatementArguments {
/// let values: NSDictionary = ["firstName": "Arthur", "lastName": "Miller"]
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values)!)
///
/// GRDB.swift only supports colon-prefixed named arguments, even though
/// SQLite supports other syntaxes. See https://www.sqlite.org/lang_expr.html#varparam
/// for more information.
///
/// - parameter dictionary: An NSDictionary
/// - returns: A StatementArguments.
public init?(_ dictionary: NSDictionary) {
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>0.36.0</string>
<string>0.39.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+2 -2
View File
@@ -58,7 +58,7 @@ public struct DatabaseMigrator {
///
/// // Add a NOT NULL constraint on persons.name:
/// migrator.registerMigration("AddNotNullCheckOnName", withDisabledForeignKeyChecks: true) { db in
/// try db.executeMultiStatement(
/// try db.execute(
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
/// "INSERT INTO new_persons SELECT * FROM persons;" +
/// "DROP TABLE persons;" +
@@ -92,7 +92,7 @@ public struct DatabaseMigrator {
private var migrations: [Migration] = []
private mutating func registerMigration(migration: Migration) {
precondition(migrations.map({ $0.identifier }).indexOf(migration.identifier) == nil, "Already registered migration: \"\(migration.identifier)\"")
precondition(migrations.map({ $0.identifier }).indexOf(migration.identifier) == nil, "already registered migration: \"\(migration.identifier)\"")
migrations.append(migration)
}
+1 -1
View File
@@ -63,7 +63,7 @@ public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable
///
/// - returns: The name of a database table.
public class func databaseTableName() -> String {
fatalError("Subclass must override.")
fatalError("subclass must override")
}
/// Returns the values that should be stored in the database.
+217 -197
View File
@@ -1,11 +1,11 @@
GRDB.swift
==========
GRDB.swift is an [SQLite](https://www.sqlite.org) toolkit for Swift 2, from the author of [GRMustache](https://github.com/groue/GRMustache).
GRDB.swift is an [SQLite](https://www.sqlite.org) toolkit for Swift 2.
It ships with a low-level database API, plus application-level tools.
**December 28, 2015: GRDB.swift 0.36.0 is out** - [Release notes](CHANGELOG.md). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
**January 11, 2016: GRDB.swift 0.39.0 is out** - [Release notes](CHANGELOG.md). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
**Requirements**: iOS 7.0+ / OSX 10.9+, Xcode 7+
@@ -19,11 +19,11 @@ Why GRDB, when we already have the excellent [ccgus/fmdb](https://github.com/ccg
**GRDB owes a lot to FMDB.** You will use the familiar and safe [database queues](#database-queues) you are used to. Yet you may appreciate that [database errors](#error-handling) are handled in the Swift way, and that [fetching data](#fetch-queries) is somewhat easier.
**Your SQL skills are rewarded here.** Complex queries are never treated differently from the simple ones. You won't lose a single feature or convenience by crafting custom SQL queries, on the contrary. And you are granted with type safety and all the niceties you expect from a real Swift library.
**Your SQL skills are rewarded here.** You don't have to learn a complex query builder that makes it uneasy to express the SQL you have in mind.
**GRDB provides [protocols and a Record class](#database-protocols-and-record)** that help isolating database management code into database layer types, and avoid cluterring the rest of your application.
**GRDB is fast**. As fast, when not faster, than FMDB and SQLite.swift.
**GRDB is fast**, and usually faster than FMDB and SQLite.swift (see the [Performance wiki page](https://github.com/groue/GRDB.swift/wiki/Performance)).
**You can query your database [right from the debugger](https://twitter.com/groue/status/679347658557902849).**
@@ -32,7 +32,7 @@ Features
--------
- **A low-level [SQLite API](#sqlite-api)** that leverages the Swift 2 standard library.
- **A [Record](#record) class** that wraps result sets, eats your custom SQL queries for breakfast, provides persistence operations, and changes tracking.
- **[Protocols and a ready-made class](#database-protocols-and-record)** that eat your SQL queries for breakfast, provide persistence, and changes tracking.
- **[Swift type freedom](#values)**: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types.
- **[Database migrations](#migrations)**
- **[Database changes observation hooks](#database-changes-observation)**
@@ -41,7 +41,7 @@ Features
Documentation
=============
- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.36.0/index.html)** (on cocoadocs.org)
- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.39.0/index.html)** (on cocoadocs.org)
- **[Installation](#installation)**
@@ -97,7 +97,7 @@ To use GRDB.swift with Cocoapods, specify in your Podfile:
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
pod 'GRDB.swift', '0.36.0'
pod 'GRDB.swift', '~> 0.39.0'
```
@@ -108,7 +108,7 @@ pod 'GRDB.swift', '0.36.0'
To use GRDB.swift with Carthage, specify in your Cartfile:
```
github "groue/GRDB.swift" == 0.36.0
github "groue/GRDB.swift" ~> 0.39.0
```
@@ -160,7 +160,7 @@ try dbQueue.inDatabase { db in
## Database Queues
You access SQLite databases through **thread-safe database queues** (inspired by [ccgus/fmdb](https://github.com/ccgus/fmdb)):
You access SQLite databases through **database queues** (inspired by [ccgus/fmdb](https://github.com/ccgus/fmdb)):
```swift
import GRDB
@@ -169,26 +169,9 @@ let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
let inMemoryDBQueue = DatabaseQueue()
```
SQLite creates the database file if it does not already exist.
SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated.
The connection is closed when the database queue gets deallocated.
**Configure** databases:
```swift
var config = Configuration()
config.trace = { print($0) } // Prints all SQL statements
let dbQueue = try DatabaseQueue(
path: "/path/to/database.sqlite",
configuration: config)
```
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.36.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details.
Once connected, the `inDatabase` and `inTransaction` methods perform your **database statements** in a dedicated, serial, queue:
**A database queue can be used from any thread.** The `inDatabase` and `inTransaction` methods block the current thread until your database statements are executed:
```swift
// Execute database statements:
@@ -200,20 +183,35 @@ dbQueue.inDatabase { db in
}
}
// Extract values from the database:
let wineCount = dbQueue.inDatabase { db in
Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
}
// Wrap database statements in a transaction:
try dbQueue.inTransaction { db in
try db.execute("INSERT ...")
try db.execute("DELETE FROM ...")
return .Commit
}
// Extract values from the database:
let wineCount = dbQueue.inDatabase { db in
Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
}
print(wineCount)
```
See [Transactions](#transactions) for more information about GRDB transaction handling.
You can **configure** databases:
```swift
var config = Configuration()
config.readonly = true
config.trace = { print($0) } // Prints all SQL statements
let dbQueue = try DatabaseQueue(
path: "/path/to/database.sqlite",
configuration: config)
```
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.39.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details.
## Executing Updates
@@ -230,29 +228,37 @@ try dbQueue.inDatabase { db in
"name TEXT NOT NULL," +
"age INT" +
")")
try db.execute(
"INSERT INTO persons (name, age) VALUES (?, ?)",
arguments: ["Arthur", 36])
try db.execute(
"INSERT INTO persons (name, age) VALUES (:name, :age)",
arguments: ["name": "Barbara", "age": 39])
// Join multiple statements with a semicolon:
try db.execute(
"INSERT INTO persons (name, age) VALUES (?, ?); " +
"INSERT INTO persons (name, age) VALUES (?, ?)",
arguments: ["Arthur", 36, "Barbara", 39])
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the **statements arguments**. You pass arguments in with arrays or dictionaries, as in the example above (arguments are actually of type StatementArguments, which happens to adopt the ArrayLiteralConvertible and DictionaryLiteralConvertible protocols).
See [Values](#values) for more information on supported arguments types (Bool, Int, String, NSDate, Swift enums, etc.).
The `?` and colon-prefixed keys like `:name` in the SQL query are the **statements arguments**. You pass arguments in with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, NSDate, Swift enums, etc.).
**After an INSERT statement**, you extract the inserted Row ID from the result of the `execute` method:
```swift
let insertedRowID = try db.execute(
let personID = try db.execute(
"INSERT INTO persons (name, age) VALUES (?, ?)",
arguments: ["Arthur", 36]).insertedRowID
```
Don't miss the [DatabasePersistable protocol](#databasepersistable-protocol) and the [Record class](#record), that provide classic **persistence methods**:
```swift
let person = Person(name: "Arthur", age: 36)
try person.insert(db)
print("Inserted \(person.id)")
```
## Fetch Queries
@@ -262,10 +268,14 @@ GRDB lets you fetch **rows**, **values**, and **custom models**.
```swift
dbQueue.inDatabase { db in
Row.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Row>
Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row]
Row.fetchOne(db, "SELECT ...", arguments: ...) // Row?
// Example:
for row in Row.fetch(db, "SELECT * FROM wines") {
let name: String = row.value(named: "name")
let color: Color = row.value(named: "color")
print(name, color)
}
}
```
@@ -274,9 +284,16 @@ dbQueue.inDatabase { db in
```swift
dbQueue.inDatabase { db in
let redWineCount = Int.fetchOne(db,
"SELECT COUNT(*) FROM wines WHERE color = ?",
arguments: [Color.Red])!
Int.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Int>
Int.fetchAll(db, "SELECT ...", arguments: ...) // [Int]
Int.fetchOne(db, "SELECT ...", arguments: ...) // Int?
// When database may contain NULL:
Int?.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Int?>
Int?.fetchAll(db, "SELECT ...", arguments: ...) // [Int?]
// Example:
let wineCount = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
}
```
@@ -284,26 +301,28 @@ dbQueue.inDatabase { db in
```swift
dbQueue.inDatabase { db in
// By SQL:
Wine.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Wine>
Wine.fetchAll(db, "SELECT ...", arguments: ...) // [Wine]
Wine.fetchOne(db, "SELECT ...", arguments: ...) // Wine?
// By key:
Wine.fetch(db, keys: ...) // DatabaseSequence<Wine>
Wine.fetchAll(db, keys: ...) // [Wine]
Wine.fetchOne(db, key: ...) // Wine?
// Example:
let wines = Wine.fetchAll(db, "SELECT * FROM wines ORDER BY name")
let favoriteWine = Wine.fetchOne(db, key: user.favoriteWineId)
let favoriteWine = Wine.fetchOne(db, key: favoriteWineID)
}
```
Rows, values, and custom models can all be fetched in three fashions. Pick one, depending on the number of values you expect, and the way you use them:
- The `fetch()` method returns a memory-efficient sequence that goes in the database as it is iterated.
- The `fetchAll()` method returns an array which is less memory-efficient, but can be used from any thread.
- The `fetchOne()` method returns a single optional value.
Most of those methods take an SQL query as an argument. If SQL is not your cup of tea, then maybe you are looking for a query builder. [stephencelis/SQLite.swift](https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md#selecting-rows) is a pretty popular one.
### Row Queries
- [Fetching Rows](#fetching-rows)
- [Column Values](#column-values)
- [Rows as Dictionaries](#rows-as-dictionaries)
- [Convenience Rows](#convenience-rows)
#### Fetching Rows
@@ -340,11 +359,8 @@ See [Values](#values) for more information on supported arguments types (Bool, I
Both `fetch` and `fetchAll` let you iterate the full list of fetched rows. The differences are:
- The array returned by `fetchAll` can take a lot of memory. Yet it can be iterated on any thread.
- The sequence returned by `fetch` only goes to the database as you iterate it, and is thus more memory efficient. The price for this efficiency is that the sequence must be iterated in the database queue (you'll get a fatal error if you do otherwise).
- The sequence returned by `fetch` will return a different set of results if the database has been modified between two sequence iterations.
Row sequences also grant the fastest access to the database. This performance advantage comes with extra precautions:
- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory.
- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise).
> :point_up: **Don't turn a row sequence into an array** with `Array(rowSequence)` or `rowSequence.filter { ... }`: you would not get the distinct rows you expect. To get an array, use `Row.fetchAll(...)`.
>
@@ -392,17 +408,6 @@ row.value(...) as Int!
> row.value(...) as? Int // NO NO NO DON'T DO THAT!
> ```
When you ask for a missing column, you will get nil, or a fatal error:
```swift
let row = Row.fetchOne(db, "SELECT 'foo' AS foo")!
row.value(named: "missing") as String? // nil
row.value(named: "missing") as String // fatal error: No such column: "missing"
row.value(atIndex: 1) // fatal error: Row index out of range
```
You can explicitly check for a column presence with the `hasColumn` method.
Generally speaking, you can extract the type you need, *provided it can be converted from the underlying SQLite value*:
- **Successful conversions include:**
@@ -419,25 +424,33 @@ Generally speaking, you can extract the type you need, *provided it can be conve
let row = Row.fetchOne(db, "SELECT 'foo'")!
row.value(atIndex: 0) as String // "foo"
row.value(atIndex: 0) as NSDate? // nil
row.value(atIndex: 0) as NSDate // fatal error: Could not convert "foo" to NSDate.
row.value(atIndex: 0) as NSDate // fatal error: could not convert "foo" to NSDate.
```
- **GRDB crashes when you try to convert NULL to a non-optional value.**
This behavior is notably different from SQLite C API, or from ccgus/fmdb, that both turn NULL to 0 when extracting an integer, for example:
Notably, NULL won't turn to anything:
```swift
let row = Row.fetchOne(db, "SELECT NULL")!
row.value(atIndex: 0) as Int? // nil
row.value(atIndex: 0) as Int // fatal error: Could not convert NULL to Int.
row.value(atIndex: 0) as Int // fatal error: could not convert NULL to Int.
```
- **Missing columns return nil.**
```swift
let row = Row.fetchOne(db, "SELECT 'foo' AS foo")!
row.value(named: "missing") as String? // nil
row.value(named: "missing") as String // fatal error: no such column: missing
```
You can explicitly check for a column presence with the `hasColumn` method.
- **The convenience conversions of SQLite, such as Blob to String, String to Int, or huge Double values to Int, are not guaranteed to apply.** You must not rely on them.
#### Rows as Dictionaries
You may prefer thinking of rows as dictionaries of `DatabaseValue`, an intermediate type between SQLite and your values:
**Rows can be seen as dictionaries** of `DatabaseValue`, an intermediate type between SQLite and your values:
```swift
// Test if the column `date` is present:
@@ -469,15 +482,28 @@ if let databaseValue = row["date"] {
}
```
Iterate all the tuples (columnName, databaseValue) in a row, from left to right:
**You can build rows from scratch** using the dictionary and NSDictionary initializers (see [Values](#values) for more information on supported types):
```swift
let row = Row(["name": "foo", "date": nil])
```
**Rows are standard [collections](https://developer.apple.com/library/ios/documentation/Swift/Reference/Swift_CollectionType_Protocol/index.html)**:
```swift
// the number of columns
row.count
// All the (columnName, databaseValue) tuples, from left to right:
for (columnName, databaseValue) in row {
...
}
```
Rows are not real dictionaries, though. They may contain duplicate keys:
**Rows may contain duplicate keys**:
```swift
let row = Row.fetchOne(db, "SELECT 1 AS foo, 2 AS foo")!
@@ -488,30 +514,19 @@ for (columnName, databaseValue) in row { ... } // ("foo", 1), ("foo", 2)
```
#### Convenience Rows
From time to time, you'll want to build a custom Row from scratch. Use the dictionary and NSDictionary initializers:
```swift
Row(["name": "foo", "date": nil])
```
See [Values](#values) for more information on supported types.
### Value Queries
Instead of rows, you can directly fetch **[values](#values)**. Like rows, fetch them as **sequences**, **arrays**, or **single** values. Values are extracted from the leftmost column of the SQL queries:
```swift
dbQueue.inDatabase { db in
Int.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Int>
Int.fetchAll(db, "SELECT ...", arguments: ...) // [Int]
Int.fetchOne(db, "SELECT ...", arguments: ...) // Int?
Int.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Int>
Int.fetchAll(db, "SELECT ...", arguments: ...) // [Int]
Int.fetchOne(db, "SELECT ...", arguments: ...) // Int?
// When database may contain NULL:
Optional<Int>.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Int?>
Optional<Int>.fetchAll(db, "SELECT ...", arguments: ...) // [Int?]
Int?.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence<Int?>
Int?.fetchAll(db, "SELECT ...", arguments: ...) // [Int?]
}
```
@@ -520,15 +535,15 @@ There are many supported value types (Bool, Int, String, NSDate, Swift enums, et
```swift
dbQueue.inDatabase { db in
// The number of persons with an email ending in @example.com:
let count = Int.fetchOne(db,
let count: Int = Int.fetchOne(db,
"SELECT COUNT(*) FROM persons WHERE email LIKE ?",
arguments: ["%@example.com"])!
// All URLs:
let urls = NSURL.fetchAll(db, "SELECT url FROM links")
let urls: [NSURL] = NSURL.fetchAll(db, "SELECT url FROM links")
// The emails of people who own at least two pets:
let emails = Optional<String>.fetchAll(db,
let emails: [String?] = String?.fetchAll(db,
"SELECT persons.email " +
"FROM persons " +
"JOIN pets ON pets.masterId = persons.id " +
@@ -539,9 +554,8 @@ dbQueue.inDatabase { db in
Both `fetch` and `fetchAll` let you iterate the full list of fetched values. The differences are:
- The array returned by `fetchAll` can take a lot of memory. Yet it can be iterated on any thread.
- The sequence returned by `fetch` only goes to the database as you iterate it, and is thus more memory efficient. The price for this efficiency is that the sequence must be iterated in the database queue (you'll get a fatal error if you do otherwise).
- The sequence returned by `fetch` will return a different set of results if the database has been modified between two sequence iterations.
- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory.
- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise).
`fetchOne` returns an optional value which is nil in two cases: either the SELECT statement yielded no row, or one row with a NULL value.
@@ -939,13 +953,7 @@ dbQueue.inTransaction(.Exclusive) { db in ... }
## Error Handling
**No SQLite error goes unnoticed.** Yet when such an error happens, some GRDB.swift functions throw a DatabaseError error, and some crash with a fatal error.
**The rule is:**
- Methods that write to the database throw.
- Methods that build [prepared statements](#prepared-statements) throw.
- All other methods crash without notice (but with a detailed error message).
**No SQLite error goes unnoticed.** Yet when such an error happens, some GRDB.swift functions throw a DatabaseError error, and some crash with a fatal error:
```swift
// fatal error:
@@ -977,6 +985,47 @@ do {
See [SQLite Result Codes](https://www.sqlite.org/rescode.html).
**Fatal errors can be avoided.** For example, let's consider a scenario where your application has to perform a fetch query with untrusted SQL and query arguments.
The following code is dangerous for your application, because it has many opportunities to crash:
```swift
func fetchUserQuery(db: Database, sql: String, arguments: NSDictionary) throws -> [Row] {
// Crashes if sql is invalid, if dictionary arguments contains invalid
// values, or if arguments don't fit the SQL query:
return Row.fetchAll(db, sql, arguments: StatementArguments(arguments))
}
// fatal error: no such table: foo
try fetchUserQuery(db, sql: "SELECT * FROM foo", arguments: NSDictionary())
// fatal error: missing statement argument(s): id.
try fetchUserQuery(db, sql: "SELECT * FROM persons WHERE id = :id", arguments: NSDictionary(dictionary: ["name": "Arthur"]))
```
Compare with the safe version:
```swift
func fetchUserQuery(db: Database, sql: String, arguments: NSDictionary) throws -> [Row] {
// Dictionary arguments may contain invalid values
guard let arguments = StatementArguments(arguments) else {
throw NSError(
domain: "MyDomain",
code: 0,
userInfo: [NSLocalizedDescriptionKey: "Invalid arguments"])
}
// SQL may be invalid
let statement = try db.selectStatement(sql)
// Arguments may not fit the statement
try statement.validateArguments(arguments)
// OK now
return Row.fetchAll(statement, arguments: arguments)
}
```
## Prepared Statements
@@ -1229,17 +1278,16 @@ var migrator = DatabaseMigrator()
// v1.0 database
migrator.registerMigration("createTables") { db in
try db.execute("CREATE TABLE persons (...)")
try db.execute("CREATE TABLE books (...)")
try db.execute(
"CREATE TABLE persons (...); " +
"CREATE TABLE books (...)")
}
// v2.0 database
migrator.registerMigration("AddAgeToPersons") { db in
try db.execute("ALTER TABLE persons ADD COLUMN age INT")
}
migrator.registerMigration("AddYearToBooks") { db in
try db.execute("ALTER TABLE books ADD COLUMN year INT")
try db.execute(
"ALTER TABLE persons ADD COLUMN age INT; " +
"ALTER TABLE books ADD COLUMN year INT")
}
// (Insert migrations for future versions here)
@@ -1251,32 +1299,6 @@ try migrator.migrate(dbQueue)
**The memory of applied migrations is stored in the database itself** (in a reserved table). When you are tuning your migrations, you may need to execute one several times. All you need then is to feed your application with a database file from a previous state.
You might use Database.executeMultiStatement(): this method takes an SQL string containing multiple statements separated by semi-colons:
```swift
migrator.registerMigration("createTables") { db in
try db.executeMultiStatement(
"CREATE TABLE persons (...);" +
"CREATE TABLE books (...);" +
"...")
}
```
You might even store your migrations as bundle resources:
```swift
// Execute migration01.sql, migration02.sql, etc.
NSBundle.mainBundle()
.pathsForResourcesOfType("sql", inDirectory: "databaseMigrations")
.sort()
.forEach { path in
let migrationName = (path as NSString).lastPathComponent
migrator.registerMigration(migrationName) { db in
let sql = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
try db.executeMultiStatement(sql)
}
}
```
### Advanced Database Schema Changes
@@ -1287,7 +1309,7 @@ Yet any kind of schema change is still possible. The SQLite documentation explai
```swift
// Add a NOT NULL constraint on persons.name:
migrator.registerMigration("AddNotNullCheckOnName", withDisabledForeignKeyChecks: true) { db in
try db.executeMultiStatement(
try db.execute(
"CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
"INSERT INTO new_persons SELECT * FROM persons;" +
"DROP TABLE persons;" +
@@ -1302,32 +1324,31 @@ While your migration code runs with disabled foreign key checks, those are re-en
**GRDB provides protocols and a Record class** that help isolating database management code into database layer types, and avoid cluterring the rest of your application.
The [Record](#record) class grants its subclasses with fetching methods, persistence methods, and changes tracking:
```swift
class Person : Record { ... }
try dbQueue.inDatabase { db in
// Store
let person = Person(name: "Arthur")
try person.save(db)
- The [RowConvertible protocol](#rowconvertible-protocol) grants adopting types with fetching methods:
// Fetch
let person = Person.fetch(db, key: personId)
for person in Person.fetch(db, "SELECT * FROM persons") {
print(person.name)
}
```swift
struct Person : RowConvertible { ... }
let persons = Person.fetchAll(db, "SELECT * FROM persons")
let person = let Person.fetchOne(db, key: 1)
```
// Changes tracking
- The [DatabasePersistable protocol](#databasepersistable-protocol) grants adopting types with persistence methods:
```swift
struct Person : DatabasePersistable { ... }
try Person(name: "Arthur").insert(db)
```
- The [Record class](#record) grants its subclasses with fetching methods, persistence methods, and changes tracking:
```swift
class Person : Record { ... }
let person = Person.fetchOne(db, key: 1)!
person.name = "Barbara"
person.persistentChangedValues.keys // ["name"]
if person.hasPersistentChangedValues { // Avoid useless UPDATE statements
try person.save(db)
if person.hasPersistentChangedValues {
try person.update(db)
}
}
```
Whenever your application types can't inherit from Record, they can still adopt [RowConvertible](#rowconvertible-protocol), which grants fetching methods, and [DatabasePersistable](#databasepersistable-protocol), which grants persistence methods.
```
### RowConvertible Protocol
@@ -1370,9 +1391,8 @@ See [Column Values](#column-values) for more information about the `row.value()`
Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are:
- The array returned by `fetchAll` can take a lot of memory. Yet it can be iterated on any thread.
- The sequence returned by `fetch` only goes to the database as you iterate it, and is thus more memory efficient. The price for this efficiency is that the sequence must be iterated in the database queue (you'll get a fatal error if you do otherwise).
- The sequence returned by `fetch` will return a different set of results if the database has been modified between two sequence iterations.
- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory.
- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise).
> :point_up: **Note**: For performance reasons, the same row argument to `fromRow(:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `result.row = row.copy()`.
@@ -1426,9 +1446,8 @@ Person.fetchOne(db, key: ...) // Person?
Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are:
- The array returned by `fetchAll` can take a lot of memory. Yet it can be iterated on any thread.
- The sequence returned by `fetch` only goes to the database as you iterate it, and is thus more memory efficient. The price for this efficiency is that the sequence must be iterated in the database queue (you'll get a fatal error if you do otherwise).
- The sequence returned by `fetch` will return a different set of results if the database has been modified between two sequence iterations.
- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory.
- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise).
The order of sequences and arrays returned by the key-based methods is undefined. To specify the order of returned elements, use a raw SQL query.
@@ -1523,7 +1542,7 @@ Yet, here is the rule:
- If your type is a struct that mutates on insertion, choose `MutableDatabasePersistable`. For example, if your table has an INTEGER PRIMARY KEY, you want to store the inserted id on successful insertion.
- Otherwise, stick with `DatabasePersistable`.
For example, the Country struct below has no INTEGER PRIMARY KEY, and is not mutated on insertion. On the other side, the Person struct is interested in its rowID, and mutates itself on insertion:
For example, the Country struct below has no INTEGER PRIMARY KEY, and is not mutated on insertion:
```swift
// CREATE TABLE countries (
@@ -1546,7 +1565,11 @@ struct Country : DatabasePersistable {
// Declare the country as `let`, since its insertion does not mutate it:
let country = Country(isoCode: "FR", name: "France")
try country.insert(db)
```
On the other side, the Person struct is interested in its rowID, and mutates itself on insertion:
```swift
// CREATE TABLE persons (
// id INTEGER PRIMARY KEY,
// name TEXT
@@ -1586,11 +1609,11 @@ The `persistentDictionary` property returns a dictionary whose keys are column n
Types that adopt DatabasePersistable or MutableDatabasePersistable are given default implementations for methods that insert, update, and delete:
```swift
try object.insert(db) // INSERT
try object.update(db) // UPDATE
try object.save(db) // Inserts or updates
try object.delete(db) // DELETE
object.exists(db) // Bool
try object.insert(db) // INSERT
try object.update(db) // UPDATE
try object.save(db) // Inserts or updates
try object.delete(db) // DELETE
object.exists(db) // Bool
```
- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails.
@@ -1678,7 +1701,7 @@ struct Link : DatabasePersistable {
#### Record Overview
**Record** is a class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. It is designed to be subclassed.
**Record** is a class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. It builds on top of the [RowConvertible](#rowconvertible-protocol) and [DatabasePersistable](#databasepersistable-protocol) protocols, and is designed to be subclassed.
```swift
// Define Record subclass
@@ -1696,8 +1719,6 @@ try dbQueue.inDatabase { db in
}
```
It builds on top of the [RowConvertible](#rowconvertible-protocol) and [DatabasePersistable](#databasepersistable-protocol) protocols.
**Record is not a smart class.** It is no replacement for Core Data’s NSManagedObject, [Realm](https://realm.io)’s Object, or for an Active Record pattern. It does not provide any uniquing, automatic refresh, or synthesized properties. It has no knowledge of external references and table relationships, and will not generate JOIN queries for you.
Yet, it does a few things well:
@@ -1720,10 +1741,10 @@ Yet, it does a few things well:
```swift
let person = Person(...)
try person.insert(db) // INSERT
try person.update(db) // UPDATE
try person.save(db) // Inserts or updates
try person.delete(db) // DELETE
try person.insert(db) // INSERT
try person.update(db) // UPDATE
try person.save(db) // Inserts or updates
try person.delete(db) // DELETE
```
- **It tracks changes. Real changes**: setting a column to the same value does not constitute a change.
@@ -1773,7 +1794,7 @@ class Person {
// Persistence
func insert(db: Database) throws
func update(db: Database) throws
func save(db: Database) throws // inserts or updates
func save(db: Database) throws
func delete(db: Database) throws -> Bool
func exists(db: Database) -> Bool
@@ -1895,7 +1916,7 @@ class Person : Record {
}
/// Update person ID after a successful insertion
func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
id = rowID
}
}
@@ -1932,16 +1953,15 @@ dbQueue.inDatabase { db in
Both `fetch` and `fetchAll` let you iterate the full list of fetched records. The differences are:
- The array returned by `fetchAll` can take a lot of memory. Yet it can be iterated on any thread.
- The sequence returned by `fetch` only goes to the database as you iterate it, and is thus more memory efficient. The price for this efficiency is that the sequence must be iterated in the database queue (you'll get a fatal error if you do otherwise).
- The sequence returned by `fetch` will return a different set of results if the database has been modified between two sequence iterations.
- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory.
- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise).
For example:
```swift
dbQueue.inDatabase { db in
// All persons with an email ending in @example.com:
Person.fetch(db,
Person.fetchAll(db,
"SELECT * FROM persons WHERE email LIKE ?",
arguments: ["%@example.com"])
@@ -1990,11 +2010,11 @@ class Person : Record {
try dbQueue.inDatabase { db in
let person = Person(...)
try person.insert(db) // INSERT
try person.update(db) // UPDATE
try person.save(db) // Inserts or updates
try person.delete(db) // DELETE
person.exists(db) // Bool
try person.insert(db) // INSERT
try person.update(db) // UPDATE
try person.save(db) // Inserts or updates
try person.delete(db) // DELETE
person.exists(db) // Bool
}
```
@@ -2328,6 +2348,6 @@ Sample Code
**Thanks**
- [Pierlis](http://pierlis.com), where we write great software.
- [@pierlo](https://github.com/pierlo) for his feedback on GRDB.
- [@Chiliec](https://github.com/Chiliec), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss) and [@pierlo](https://github.com/pierlo) for their feedback on GRDB.
- [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL.
- [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency.
+3 -3
View File
@@ -1,9 +1,9 @@
- [ ] Unify Database.execute() and Database.executeMultiStatement()
- [ ] Try to remove DefaultArgument.
- [ ] Move DatabaseErrorFromStatementCreationTests.swift to tests of public APIs, now that prepared statement factory methods can throw errors.
- [ ] Expose Statement.unsafeSetArguments()
- [ ] How to have robust single writer/several readers?
Not sure:
- [ ] 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.
- [ ] Conversion should crash when type mismatch (Optional<String>.fetchOne(db, "SELECT 1"))