swift-DEVELOPMENT-SNAPSHOT-2016-05-09-a

This commit is contained in:
Gwendal Roué committed 2016-06-02 08:38:15 +02:00
1 parent 90f304a881
commit 7c4ff7677d
155 files changed
+3372 -3349

No files matched your search

@@ -3,8 +3,8 @@ import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]? = [:]) -> Bool {
setupDatabase(application)
return true
}
@@ -4,20 +4,20 @@ import UIKit
// The shared database queue
var dbQueue: DatabaseQueue!
func setupDatabase(application: UIApplication) {
func setupDatabase(_ application: UIApplication) {
// Connect to the database
// See https://github.com/groue/GRDB.swift/#database-connections
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
let databasePath = documentsPath.stringByAppendingPathComponent("db.sqlite")
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
dbQueue = try! DatabaseQueue(path: databasePath)
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
dbQueue.setupMemoryManagement(application: application)
dbQueue.setupMemoryManagement(in: application)
// Use DatabaseMigrator to setup the database
@@ -2,9 +2,9 @@ import UIKit
class DemoViewController: UITableViewController {
override func viewWillAppear(animated: Bool) {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
navigationController?.toolbarHidden = true
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Demo", style: .Plain, target: nil, action: nil)
navigationController?.isToolbarHidden = true
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Demo", style: .plain, target: nil, action: nil)
}
}
@@ -17,11 +17,11 @@ class Person: Record {
return "persons"
}
required init(_ row: Row) {
required init(row: Row) {
id = row.value(named: "id")
name = row.value(named: "name")
score = row.value(named: "score")
super.init(row)
super.init(row: row)
}
override var persistentDictionary: [String : DatabaseValueConvertible?] {
@@ -31,7 +31,7 @@ class Person: Record {
"score": score]
}
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
@@ -1,7 +1,7 @@
import UIKit
protocol PersonEditionViewControllerDelegate: class {
func personEditionControllerDidComplete(controller: PersonEditionViewController)
func personEditionControllerDidComplete(_ controller: PersonEditionViewController)
}
class PersonEditionViewController: UITableViewController {
@@ -58,14 +58,14 @@ class PersonEditionViewController: UITableViewController {
extension PersonEditionViewController {
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
override func shouldPerformSegue(withIdentifier identifier: String, sender: AnyObject?) -> Bool {
// Force keyboard to dismiss early
view.endEditing(true)
return true
}
override func willMoveToParentViewController(parent: UIViewController?) {
super.willMoveToParentViewController(parent)
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: parent)
if parent == nil {
// Self is popping from its navigation controller
@@ -80,14 +80,14 @@ extension PersonEditionViewController {
extension PersonEditionViewController: UITextFieldDelegate {
override func viewWillAppear(animated: Bool) {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
nameTextField.becomeFirstResponder()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let cell = tableView.cellForRowAtIndexPath(indexPath)
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: NSIndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let cell = tableView.cellForRow(at: indexPath)
if cell === nameCell {
nameTextField.becomeFirstResponder()
} else if cell === scoreCell {
@@ -95,7 +95,7 @@ extension PersonEditionViewController: UITextFieldDelegate {
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameTextField {
scoreTextField.becomeFirstResponder()
}
@@ -8,7 +8,7 @@ class PersonsViewController: UITableViewController {
super.viewDidLoad()
navigationItem.rightBarButtonItems = [
UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: .addPerson),
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: .addPerson),
editButtonItem()
]
@@ -20,28 +20,28 @@ class PersonsViewController: UITableViewController {
},
tableViewEvent: { [unowned self] (controller, record, event) in
switch event {
case .Insertion(let indexPath):
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .insertion(let indexPath):
self.tableView.insertRows(at: [indexPath], with: .fade)
case .Deletion(let indexPath):
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .deletion(let indexPath):
self.tableView.deleteRows(at: [indexPath], with: .fade)
case .Update(let indexPath, _):
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) {
self.configureCell(cell, atIndexPath: indexPath)
case .update(let indexPath, _):
if let cell = self.tableView.cellForRow(at: indexPath) {
self.configure(cell, at: indexPath)
}
case .Move(let indexPath, let newIndexPath, _):
case .move(let indexPath, let newIndexPath, _):
// Actually move cells around for more demo effect :-)
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
self.tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath)
let cell = self.tableView.cellForRow(at: indexPath)
self.tableView.moveRow(at: indexPath, to: newIndexPath)
if let cell = cell {
self.configureCell(cell, atIndexPath: newIndexPath)
self.configure(cell, at: newIndexPath)
}
// A quieter animation:
// self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
// self.tableView.deleteRows(at: [indexPath], with: .fade)
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
}
},
recordsDidChange: { [unowned self] _ in
@@ -52,9 +52,9 @@ class PersonsViewController: UITableViewController {
configureToolbar()
}
override func viewWillAppear(animated: Bool) {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.toolbarHidden = false
navigationController?.isToolbarHidden = false
}
}
@@ -63,9 +63,9 @@ class PersonsViewController: UITableViewController {
extension PersonsViewController : PersonEditionViewControllerDelegate {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditPerson" {
let person = personsController.recordAtIndexPath(tableView.indexPathForSelectedRow!)
let person = personsController.record(at: tableView.indexPathForSelectedRow!)
let controller = segue.destinationViewController as! PersonEditionViewController
controller.title = person.name
controller.person = person
@@ -82,8 +82,8 @@ extension PersonsViewController : PersonEditionViewControllerDelegate {
}
}
@IBAction func addPerson(sender: AnyObject?) {
performSegueWithIdentifier("NewPerson", sender: sender)
@IBAction func addPerson(_ sender: AnyObject?) {
performSegue(withIdentifier: "NewPerson", sender: sender)
}
@IBAction func cancelPersonEdition(segue: UIStoryboardSegue) {
@@ -102,7 +102,7 @@ extension PersonsViewController : PersonEditionViewControllerDelegate {
}
}
func personEditionControllerDidComplete(controller: PersonEditionViewController) {
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
// Person edition: back button was tapped
controller.applyChanges()
let person = controller.person
@@ -118,29 +118,29 @@ extension PersonsViewController : PersonEditionViewControllerDelegate {
// MARK: - UITableViewDataSource
extension PersonsViewController {
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let person = personsController.recordAtIndexPath(indexPath)
func configure(_ cell: UITableViewCell, at indexPath: NSIndexPath) {
let person = personsController.record(at: indexPath)
cell.textLabel?.text = person.name
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
override func numberOfSections(in tableView: UITableView) -> Int {
return personsController.sections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return personsController.sections[section].numberOfRecords
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Person", forIndexPath: indexPath)
configureCell(cell, atIndexPath: indexPath)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
configure(cell, at: indexPath)
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: NSIndexPath) {
// Delete the person
let person = personsController.recordAtIndexPath(indexPath)
let person = personsController.record(at: indexPath)
try! dbQueue.inDatabase { db in
try person.delete(db)
}
@@ -154,11 +154,11 @@ extension PersonsViewController {
private func configureToolbar() {
toolbarItems = [
UIBarButtonItem(title: "Name ⬆︎", style: .Plain, target: self, action: .sortByName),
UIBarButtonItem(title: "Score ⬇︎", style: .Plain, target: self, action: .sortByScore),
UIBarButtonItem(title: "Randomize", style: .Plain, target: self, action: .randomizeScores),
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "💣", style: .Plain, target: self, action: .stressTest)
UIBarButtonItem(title: "Name ⬆︎", style: .plain, target: self, action: .sortByName),
UIBarButtonItem(title: "Score ⬇︎", style: .plain, target: self, action: .sortByScore),
UIBarButtonItem(title: "Randomize", style: .plain, target: self, action: .randomizeScores),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "💣", style: .plain, target: self, action: .stressTest)
]
}
@@ -180,7 +180,7 @@ extension PersonsViewController {
person.score = Person.randomScore()
try person.update(db)
}
return .Commit
return .commit
}
}
@@ -216,7 +216,7 @@ extension PersonsViewController {
}
}
}
return .Commit
return .commit
}
}
}
@@ -8,12 +8,12 @@ class SimplePersonsViewController: UITableViewController {
super.viewDidLoad()
navigationItem.rightBarButtonItems = [
UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(SimplePersonsViewController.addPerson(_:))),
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SimplePersonsViewController.addPerson(_:))),
editButtonItem()
]
}
override func viewWillAppear(animated: Bool) {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadPersons()
tableView.reloadData()
@@ -31,7 +31,7 @@ class SimplePersonsViewController: UITableViewController {
extension SimplePersonsViewController : PersonEditionViewControllerDelegate {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditPerson" {
let person = persons[tableView.indexPathForSelectedRow!.row]
let controller = segue.destinationViewController as! PersonEditionViewController
@@ -50,8 +50,8 @@ extension SimplePersonsViewController : PersonEditionViewControllerDelegate {
}
}
@IBAction func addPerson(sender: AnyObject?) {
performSegueWithIdentifier("NewPerson", sender: sender)
@IBAction func addPerson(_ sender: AnyObject?) {
performSegue(withIdentifier: "NewPerson", sender: sender)
}
@IBAction func cancelPersonEdition(segue: UIStoryboardSegue) {
@@ -70,7 +70,7 @@ extension SimplePersonsViewController : PersonEditionViewControllerDelegate {
}
}
func personEditionControllerDidComplete(controller: PersonEditionViewController) {
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
// Person edition: back button was tapped
controller.applyChanges()
let person = controller.person
@@ -86,29 +86,29 @@ extension SimplePersonsViewController : PersonEditionViewControllerDelegate {
// MARK: - UITableViewDataSource
extension SimplePersonsViewController {
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
func configure(_ cell: UITableViewCell, at indexPath: NSIndexPath) {
let person = persons[indexPath.row]
cell.textLabel?.text = person.name
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return persons.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Person", forIndexPath: indexPath)
configureCell(cell, atIndexPath: indexPath)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
configure(cell, at: indexPath)
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: NSIndexPath) {
// Delete the person
let person = persons[indexPath.row]
try! dbQueue.inDatabase { db in
try person.delete(db)
}
persons.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
persons.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
@@ -24,7 +24,7 @@ func setupDatabase() {
// See https://github.com/groue/GRDB.swift/#database-queues
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
let databasePath = documentsPath.stringByAppendingPathComponent("db.sqlite")
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
dbQueue = try! DatabaseQueue(path: databasePath)
@@ -38,7 +38,7 @@ func setupDatabase() {
}
dbQueue.inDatabase { db in
db.addCollation(collation)
db.add(collation: collation)
}
@@ -3,7 +3,7 @@ class Person : Record {
var firstName: String?
var lastName: String?
var fullName: String {
return [firstName, lastName].flatMap { $0 }.filter { !$0.isEmpty }.joinWithSeparator(" ")
return [firstName, lastName].flatMap { $0 }.filter { !$0.isEmpty }.joined(separator: " ")
}
init(firstName: String? = nil, lastName: String? = nil) {
@@ -19,11 +19,11 @@ class Person : Record {
return "persons"
}
required init(_ row: Row) {
required init(row: Row) {
id = row.value(named: "id")
firstName = row.value(named: "firstName")
lastName = row.value(named: "lastName")
super.init(row)
super.init(row: row)
}
@@ -34,7 +34,7 @@ class Person : Record {
"lastName": lastName]
}
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
@@ -33,7 +33,7 @@ class PersonEditionViewController: UITableViewController, UITextFieldDelegate {
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Tapping Return key focuses next text field.
if textField == firstNameTextField {
lastNameTextField.becomeFirstResponder()
@@ -46,7 +46,7 @@ class PersonsViewController: UITableViewController {
// Reload persons, and insert a cell.
reloadPersons()
let index = persons.indexOf { $0.id == person.id }!
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Automatic)
tableView.insertRows(at: [NSIndexPath(forRow: index, inSection: 0)], with: .automatic)
}
@@ -70,10 +70,10 @@ class PersonsViewController: UITableViewController {
let person = persons[indexPath.row]
try! dbQueue.inTransaction { db in
try person.delete(db)
return .Commit
return .commit
}
persons.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
persons.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
+4 -10
View File
@@ -65,15 +65,15 @@ public struct Configuration {
/// The default kind of transaction.
///
/// Default: Immediate
public var defaultTransactionKind: TransactionKind = .Immediate
public var defaultTransactionKind: TransactionKind = .immediate
// MARK: - Concurrency
/// The behavior in case of SQLITE_BUSY error. See https://www.sqlite.org/rescode.html#busy
///
/// Default: ImmediateError
public var busyMode: BusyMode = .ImmediateError
/// Default: immediateError
public var busyMode: BusyMode = .immediateError
/// The maximum number of concurrent readers (applies to database
/// pools only).
@@ -90,7 +90,7 @@ public struct Configuration {
// MARK: - Not Public
var threadingMode: ThreadingMode = .Default
var threadingMode: ThreadingMode = .SQLiteDefault
var SQLiteConnectionDidOpen: (() -> ())?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())?
var SQLiteConnectionDidClose: (() -> ())?
@@ -101,9 +101,3 @@ public struct Configuration {
/// A tracing function that takes an SQL string.
public typealias TraceFunction = (String) -> Void
/// A tracing function that logs SQL statements with NSLog
public func LogSQL(sql: String) {
NSLog("SQLite: %@", sql)
}
+227 -219
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -11,7 +11,7 @@
#endif
/// DatabaseError wraps an SQLite error.
public struct DatabaseError : ErrorType {
public struct DatabaseError : ErrorProtocol {
/// The SQLite error code (see https://www.sqlite.org/c3ref/c_abort.html).
public let code: Int32
+43 -41
View File
@@ -62,7 +62,7 @@ public final class DatabasePool {
// Readers
readerConfig = configuration
readerConfig.readonly = true
readerConfig.defaultTransactionKind = .Deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections.
readerConfig.defaultTransactionKind = .deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections.
readerPool = Pool<SerializedDatabase>(maximumCount: configuration.maximumReaderCount)
readerPool.makeElement = { [unowned self] in
@@ -73,10 +73,10 @@ public final class DatabasePool {
serializedDatabase.performSync { db in
for function in self.functions {
db.addFunction(function)
db.add(function: function)
}
for collation in self.collations {
db.addCollation(collation)
db.add(collation: collation)
}
}
@@ -90,7 +90,7 @@ public final class DatabasePool {
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
NSNotificationCenter.defaultCenter().removeObserver(self)
NSNotificationCenter.default().removeObserver(self)
}
#endif
@@ -111,7 +111,7 @@ public final class DatabasePool {
/// more information.
///
/// - parameter kind: The checkpoint mode (default passive)
public func checkpoint(kind: CheckpointMode = .Passive) throws {
public func checkpoint(_ kind: CheckpointMode = .passive) throws {
try writer.performSync { db in
// TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and
// check whether we need a busy handler on writer and/or readers
@@ -155,22 +155,22 @@ public final class DatabasePool {
/// - param application: The UIApplication that will start a background
/// task to let the database pool release its memory when the application
/// enters background.
public func setupMemoryManagement(application application: UIApplication) {
public func setupMemoryManagement(in application: UIApplication) {
self.application = application
let center = NSNotificationCenter.defaultCenter()
let center = NSNotificationCenter.default()
center.addObserver(self, selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
private var application: UIApplication!
@objc private func applicationDidEnterBackground(notification: NSNotification) {
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
return
}
var task: UIBackgroundTaskIdentifier! = nil
task = application.beginBackgroundTaskWithExpirationHandler(nil)
task = application.beginBackgroundTask(expirationHandler: nil)
if task == UIBackgroundTaskInvalid {
// Perform releaseMemory() synchronously.
@@ -184,7 +184,7 @@ public final class DatabasePool {
}
}
@objc private func applicationDidReceiveMemoryWarning(notification: NSNotification) {
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.releaseMemory()
}
@@ -205,10 +205,10 @@ public final class DatabasePool {
/// The available [checkpoint modes](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html).
public enum CheckpointMode: Int32 {
case Passive = 0 // SQLITE_CHECKPOINT_PASSIVE
case Full = 1 // SQLITE_CHECKPOINT_FULL
case Restart = 2 // SQLITE_CHECKPOINT_RESTART
case Truncate = 3 // SQLITE_CHECKPOINT_TRUNCATE
case passive = 0 // SQLITE_CHECKPOINT_PASSIVE
case full = 1 // SQLITE_CHECKPOINT_FULL
case restart = 2 // SQLITE_CHECKPOINT_RESTART
case truncate = 3 // SQLITE_CHECKPOINT_TRUNCATE
}
@@ -264,15 +264,15 @@ extension DatabasePool : DatabaseReader {
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(block: (db: Database) throws -> T) rethrows -> T {
public func read<T>(_ block: (db: Database) throws -> T) rethrows -> T {
// The block isolation comes from the DEFERRED transaction.
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
return try readerPool.get { reader in
try reader.performSync { db in
var result: T? = nil
try db.inTransaction(.Deferred) {
try db.inTransaction(.deferred) {
result = try block(db: db)
return .Commit
return .commit
}
return result!
}
@@ -299,7 +299,7 @@ extension DatabasePool : DatabaseReader {
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
public func nonIsolatedRead<T>(_ block: (db: Database) throws -> T) rethrows -> T {
return try readerPool.get { reader in
try reader.performSync { db in
try block(db: db)
@@ -319,22 +319,23 @@ extension DatabasePool : DatabaseReader {
/// }
/// return int + 1
/// }
/// dbPool.addFunction(fn)
/// dbPool.add(function: fn)
/// dbPool.read { db in
/// Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func addFunction(function: DatabaseFunction) {
public func add(function: DatabaseFunction) {
// TODO: Use Set.update when available: https://github.com/apple/swift-evolution/blob/master/proposals/0059-updated-set-apis.md#other-changes)
functions.remove(function)
functions.insert(function)
writer.performSync { db in db.addFunction(function) }
readerPool.forEach { $0.performSync { db in db.addFunction(function) } }
writer.performSync { db in db.add(function: function) }
readerPool.forEach { $0.performSync { db in db.add(function: function) } }
}
/// Remove an SQL function.
public func removeFunction(function: DatabaseFunction) {
public func remove(function: DatabaseFunction) {
functions.remove(function)
writer.performSync { db in db.removeFunction(function) }
readerPool.forEach { $0.performSync { db in db.removeFunction(function) } }
writer.performSync { db in db.remove(function: function) }
readerPool.forEach { $0.performSync { db in db.remove(function: function) } }
}
@@ -345,22 +346,23 @@ extension DatabasePool : DatabaseReader {
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// dbPool.addCollation(collation)
/// dbPool.add(collation: collation)
/// dbPool.write { db in
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func addCollation(collation: DatabaseCollation) {
public func add(collation: DatabaseCollation) {
// TODO: Use Set.update when available: https://github.com/apple/swift-evolution/blob/master/proposals/0059-updated-set-apis.md#other-changes)
collations.remove(collation)
collations.insert(collation)
writer.performSync { db in db.addCollation(collation) }
readerPool.forEach { $0.performSync { db in db.addCollation(collation) } }
writer.performSync { db in db.add(collation: collation) }
readerPool.forEach { $0.performSync { db in db.add(collation: collation) } }
}
/// Remove a collation.
public func removeCollation(collation: DatabaseCollation) {
public func remove(collation: DatabaseCollation) {
collations.remove(collation)
writer.performSync { db in db.removeCollation(collation) }
readerPool.forEach { $0.performSync { db in db.removeCollation(collation) } }
writer.performSync { db in db.remove(collation: collation) }
readerPool.forEach { $0.performSync { db in db.remove(collation: collation) } }
}
}
@@ -383,7 +385,7 @@ extension DatabasePool : DatabaseWriter {
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func write<T>(block: (db: Database) throws -> T) rethrows -> T {
public func write<T>(_ block: (db: Database) throws -> T) rethrows -> T {
return try writer.performSync(block)
}
@@ -395,7 +397,7 @@ extension DatabasePool : DatabaseWriter {
///
/// try dbPool.writeInTransaction { db in
/// db.execute(...)
/// return .Commit
/// return .commit
/// }
///
/// This method is *not* reentrant.
@@ -403,12 +405,12 @@ extension DatabasePool : DatabaseWriter {
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - block: A block that executes SQL statements and return either
/// .Commit or .Rollback.
/// .commit or .rollback.
/// - throws: The error thrown by the block.
public func writeInTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) throws {
public func writeInTransaction(_ kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) throws {
try writer.performSync { db in
try db.inTransaction(kind) {
try block(db: db)
@@ -442,18 +444,18 @@ extension DatabasePool : DatabaseWriter {
///
/// The database pool releases the writing dispatch queue early, before the
/// block has finished.
public func readFromWrite(block: (db: Database) -> Void) {
public func readFromWrite(_ block: (db: Database) -> Void) {
writer.preconditionValidQueue()
let semaphore = dispatch_semaphore_create(0)
let semaphore = dispatch_semaphore_create(0)!
self.readerPool.get { reader in
reader.performAsync { db in
// Assume COMMIT DEFERRED TRANSACTION does not throw error.
try! db.inTransaction(.Deferred) {
try! db.inTransaction(.deferred) {
// Now we're isolated: release the writing queue
dispatch_semaphore_signal(semaphore)
block(db: db)
return .Commit
return .commit
}
}
}
+27 -27
View File
@@ -24,7 +24,7 @@ public final class DatabaseQueue {
serializedDatabase = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: DatabaseSchemaCache())
schemaCache: SimpleDatabaseSchemaCache())
}
/// Opens an in-memory SQLite database.
@@ -39,7 +39,7 @@ public final class DatabaseQueue {
serializedDatabase = try! SerializedDatabase(
path: ":memory:",
configuration: configuration,
schemaCache: DatabaseSchemaCache())
schemaCache: SimpleDatabaseSchemaCache())
}
#if os(iOS)
@@ -48,7 +48,7 @@ public final class DatabaseQueue {
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
NSNotificationCenter.defaultCenter().removeObserver(self)
NSNotificationCenter.default().removeObserver(self)
}
#endif
@@ -79,7 +79,7 @@ public final class DatabaseQueue {
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func inDatabase<T>(block: (db: Database) throws -> T) rethrows -> T {
public func inDatabase<T>(_ block: (db: Database) throws -> T) rethrows -> T {
return try serializedDatabase.performSync(block)
}
@@ -91,7 +91,7 @@ public final class DatabaseQueue {
///
/// try dbQueue.inTransaction { db in
/// db.execute(...)
/// return .Commit
/// return .commit
/// }
///
/// This method is *not* reentrant.
@@ -99,12 +99,12 @@ public final class DatabaseQueue {
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - block: A block that executes SQL statements and return either
/// .Commit or .Rollback.
/// .commit or .rollback.
/// - throws: The error thrown by the block.
public func inTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) throws {
public func inTransaction(_ kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) throws {
try serializedDatabase.performSync { db in
try db.inTransaction(kind) {
try block(db: db)
@@ -135,22 +135,22 @@ public final class DatabaseQueue {
/// - param application: The UIApplication that will start a background
/// task to let the database queue release its memory when the application
/// enters background.
public func setupMemoryManagement(application application: UIApplication) {
public func setupMemoryManagement(in application: UIApplication) {
self.application = application
let center = NSNotificationCenter.defaultCenter()
let center = NSNotificationCenter.default()
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
private var application: UIApplication?
@objc private func applicationDidEnterBackground(notification: NSNotification) {
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
return
}
var task: UIBackgroundTaskIdentifier! = nil
task = application.beginBackgroundTaskWithExpirationHandler(nil)
task = application.beginBackgroundTask(expirationHandler: nil)
if task == UIBackgroundTaskInvalid {
// Perform releaseMemory() synchronously.
@@ -164,7 +164,7 @@ public final class DatabaseQueue {
}
}
@objc private func applicationDidReceiveMemoryWarning(notification: NSNotification) {
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.releaseMemory()
}
@@ -223,14 +223,14 @@ extension DatabaseQueue : DatabaseReader {
/// Alias for inDatabase
///
/// This method is part of the DatabaseReader protocol adoption.
public func read<T>(block: (db: Database) throws -> T) rethrows -> T {
public func read<T>(_ block: (db: Database) throws -> T) rethrows -> T {
return try serializedDatabase.performSync(block)
}
/// Alias for inDatabase
///
/// This method is part of the DatabaseReader protocol adoption.
public func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
public func nonIsolatedRead<T>(_ block: (db: Database) throws -> T) rethrows -> T {
return try serializedDatabase.performSync(block)
}
@@ -246,20 +246,20 @@ extension DatabaseQueue : DatabaseReader {
/// }
/// return int + 1
/// }
/// dbQueue.addFunction(fn)
/// dbQueue.add(function: fn)
/// dbQueue.inDatabase { db in
/// Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func addFunction(function: DatabaseFunction) {
public func add(function: DatabaseFunction) {
serializedDatabase.performSync { db in
db.addFunction(function)
db.add(function: function)
}
}
/// Remove an SQL function.
public func removeFunction(function: DatabaseFunction) {
public func remove(function: DatabaseFunction) {
serializedDatabase.performSync { db in
db.removeFunction(function)
db.remove(function: function)
}
}
@@ -271,20 +271,20 @@ extension DatabaseQueue : DatabaseReader {
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// dbQueue.addCollation(collation)
/// dbQueue.add(collation: collation)
/// try dbQueue.inDatabase { db in
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func addCollation(collation: DatabaseCollation) {
public func add(collation: DatabaseCollation) {
serializedDatabase.performSync { db in
db.addCollation(collation)
db.add(collation: collation)
}
}
/// Remove a collation.
public func removeCollation(collation: DatabaseCollation) {
public func remove(collation: DatabaseCollation) {
serializedDatabase.performSync { db in
db.removeCollation(collation)
db.remove(collation: collation)
}
}
}
@@ -300,7 +300,7 @@ extension DatabaseQueue : DatabaseWriter {
/// Alias for inDatabase
///
/// This method is part of the DatabaseWriter protocol adoption.
public func write<T>(block: (db: Database) throws -> T) rethrows -> T {
public func write<T>(_ block: (db: Database) throws -> T) rethrows -> T {
return try serializedDatabase.performSync(block)
}
@@ -308,7 +308,7 @@ extension DatabaseQueue : DatabaseWriter {
///
/// This method is part of the DatabaseWriter protocol adoption, and must
/// be called from the protected database dispatch queue.
public func readFromWrite(block: (db: Database) -> Void) {
public func readFromWrite(_ block: (db: Database) -> Void) {
serializedDatabase.perform(block)
}
}
+10 -11
View File
@@ -49,7 +49,7 @@ public protocol DatabaseReader : class {
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
func read<T>(block: (db: Database) throws -> T) rethrows -> T
func read<T>(_ block: (db: Database) throws -> T) rethrows -> T
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
@@ -71,7 +71,7 @@ public protocol DatabaseReader : class {
/// let int1 = Int.fetchOne(db, sql)
/// let int2 = Int.fetchOne(db, sql)
/// }
func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T
func nonIsolatedRead<T>(_ block: (db: Database) throws -> T) rethrows -> T
// MARK: - Functions
@@ -85,12 +85,12 @@ public protocol DatabaseReader : class {
/// }
/// return int + 1
/// }
/// reader.addFunction(fn)
/// reader.add(function: fn)
/// Int.fetchOne(reader, "SELECT succ(1)")! // 2
func addFunction(function: DatabaseFunction)
func add(function: DatabaseFunction)
/// Remove an SQL function.
func removeFunction(function: DatabaseFunction)
func remove(function: DatabaseFunction)
// MARK: - Collations
@@ -100,12 +100,12 @@ public protocol DatabaseReader : class {
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// reader.addCollation(collation)
/// reader.add(collation: collation)
/// try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard")
func addCollation(collation: DatabaseCollation)
func add(collation: DatabaseCollation)
/// Remove a collation.
func removeCollation(collation: DatabaseCollation)
func remove(collation: DatabaseCollation)
}
extension DatabaseReader {
@@ -127,11 +127,10 @@ extension DatabaseReader {
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws {
try read { dbFrom in
try writer.write { dbDest in
let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main")
guard backup != nil else {
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
throw DatabaseError(code: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
}
guard backup != unsafeBitCast(Int(SQLITE_ERROR), COpaquePointer.self) else {
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError(code: SQLITE_ERROR)
}
+20 -20
View File
@@ -25,23 +25,23 @@
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class DatabaseScheduler {
private static let specificKey = unsafeBitCast(DatabaseScheduler.self, UnsafePointer<Void>.self) // some unique pointer
private static let specificKey = unsafeBitCast(DatabaseScheduler.self, to: UnsafePointer<Void>.self) // some unique pointer
private var allowedSerializedDatabases: [Database]
private init(allowedSerializedDatabase database: Database) {
allowedSerializedDatabases = [database]
}
static func makeSerializedQueueAllowing(database database: Database) -> dispatch_queue_t {
let queue = dispatch_queue_create("GRDB.SerializedDatabase", nil)
static func makeSerializedQueueAllowing(database: Database) -> dispatch_queue_t {
let queue = dispatch_queue_create("GRDB.SerializedDatabase", nil)!
let scheduler = DatabaseScheduler(allowedSerializedDatabase: database)
let unmanagedScheduler = Unmanaged.passRetained(scheduler)
let schedulerPointer = unsafeBitCast(unmanagedScheduler, UnsafeMutablePointer<Void>.self)
let schedulerPointer = unsafeBitCast(unmanagedScheduler, to: UnsafeMutablePointer<Void>.self)
dispatch_queue_set_specific(queue, DatabaseScheduler.specificKey, schedulerPointer, destroyDatabaseScheduler)
return queue
}
static func dispatchSync<T>(queue: dispatch_queue_t, database: Database, block: (db: Database) throws -> T) rethrows -> T {
static func dispatchSync<T>(_ queue: dispatch_queue_t, database: Database, block: (db: Database) throws -> T) rethrows -> T {
if let sourceScheduler = currentScheduler() {
// We're in a queue where some databases are allowed.
//
@@ -76,16 +76,16 @@ final class DatabaseScheduler {
// currently allowed databases inside.
//
// The impl function helps us turn dispatch_sync into a rethrowing function
func impl(queue: dispatch_queue_t, database: Database, block: (db: Database) throws -> T, onError: (ErrorType) throws -> ()) rethrows -> T {
func impl(_ queue: dispatch_queue_t, database: Database, block: (db: Database) throws -> T, onError: (ErrorProtocol) throws -> ()) rethrows -> T {
var result: T? = nil
var blockError: ErrorType? = nil
var blockError: ErrorProtocol? = nil
dispatch_sync(queue) {
let targetScheduler = currentScheduler()!
assert(targetScheduler.allowedSerializedDatabases[0] === database) // sanity check
do {
let backup = targetScheduler.allowedSerializedDatabases
targetScheduler.allowedSerializedDatabases.appendContentsOf(sourceScheduler.allowedSerializedDatabases)
targetScheduler.allowedSerializedDatabases.append(contentsOf: sourceScheduler.allowedSerializedDatabases)
defer {
targetScheduler.allowedSerializedDatabases = backup
}
@@ -105,9 +105,9 @@ final class DatabaseScheduler {
// block to queue.
//
// The impl function helps us turn dispatch_sync into a rethrowing function
func impl(queue: dispatch_queue_t, database: Database, block: (db: Database) throws -> T, onError: (ErrorType) throws -> ()) rethrows -> T {
func impl(_ queue: dispatch_queue_t, database: Database, block: (db: Database) throws -> T, onError: (ErrorProtocol) throws -> ()) rethrows -> T {
var result: T? = nil
var blockError: ErrorType? = nil
var blockError: ErrorProtocol? = nil
dispatch_sync(queue) {
do {
result = try block(db: database)
@@ -124,33 +124,33 @@ final class DatabaseScheduler {
}
}
static func preconditionValidQueue(db: Database, @autoclosure _ message: () -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(allows(db), message, file: file, line: line)
}
static func allows(db: Database) -> Bool {
static func allows(_ db: Database) -> Bool {
return currentScheduler()?.allows(db) ?? false
}
private func allows(db: Database) -> Bool {
private func allows(_ db: Database) -> Bool {
return allowedSerializedDatabases.contains { $0 === db }
}
private static func currentScheduler() -> DatabaseScheduler? {
return scheduler(from: dispatch_get_specific(specificKey))
guard let schedulerPointer = dispatch_get_specific(specificKey) else {
return nil
}
return scheduler(from: schedulerPointer)
}
private static func scheduler(from schedulerPointer: UnsafeMutablePointer<Void>) -> DatabaseScheduler? {
guard schedulerPointer != nil else {
return nil
}
let unmanagedScheduler = unsafeBitCast(schedulerPointer, Unmanaged<DatabaseScheduler>.self)
let unmanagedScheduler = unsafeBitCast(schedulerPointer, to: Unmanaged<DatabaseScheduler>.self)
return unmanagedScheduler.takeUnretainedValue()
}
}
/// Destructor for dispatch_queue_set_specific
private func destroyDatabaseScheduler(schedulerPointer: UnsafeMutablePointer<Void>) {
let unmanagedScheduler = unsafeBitCast(schedulerPointer, Unmanaged<DatabaseScheduler>.self)
private func destroyDatabaseScheduler(schedulerPointer: UnsafeMutablePointer<Void>?) {
let unmanagedScheduler = unsafeBitCast(schedulerPointer, to: Unmanaged<DatabaseScheduler>.self)
unmanagedScheduler.release()
}
+9 -9
View File
@@ -1,36 +1,36 @@
/// A thread-unsafe database schema cache
final class DatabaseSchemaCache: DatabaseSchemaCacheType {
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
private var primaryKeys: [String: PrimaryKey?] = [:]
func clear() {
primaryKeys = [:]
}
func primaryKey(tableName tableName: String) -> PrimaryKey?? {
func primaryKey(_ tableName: String) -> PrimaryKey?? {
guard let pk = primaryKeys[tableName] else {
return nil
}
return pk
}
func setPrimaryKey(primaryKey: PrimaryKey?, forTableName tableName: String) {
func set(primaryKey: PrimaryKey?, for tableName: String) {
primaryKeys[tableName] = primaryKey
}
}
/// A thread-safe database schema cache
final class SharedDatabaseSchemaCache: DatabaseSchemaCacheType {
private let cache = ReadWriteBox(DatabaseSchemaCache())
final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
private let cache = ReadWriteBox(SimpleDatabaseSchemaCache())
func clear() {
cache.write { $0.clear() }
}
func primaryKey(tableName tableName: String) -> PrimaryKey?? {
return cache.read { $0.primaryKey(tableName: tableName) }
func primaryKey(_ tableName: String) -> PrimaryKey?? {
return cache.read { $0.primaryKey(tableName) }
}
func setPrimaryKey(primaryKey: PrimaryKey?, forTableName tableName: String) {
cache.write { $0.setPrimaryKey(primaryKey, forTableName: tableName) }
func set(primaryKey: PrimaryKey?, for tableName: String) {
cache.write { $0.set(primaryKey: primaryKey, for: tableName) }
}
}
+8 -8
View File
@@ -18,7 +18,7 @@ class DatabaseStore {
}
let databaseFileName = (path as NSString).lastPathComponent
let directoryPath = (path as NSString).stringByDeletingLastPathComponent
let directoryPath = (path as NSString).deletingLastPathComponent
// Apply file attributes on existing files
DatabaseStore.setFileAttributes(
@@ -33,13 +33,13 @@ class DatabaseStore {
let directoryDescriptor = open(directoryPath, O_EVTONLY)
guard directoryDescriptor != -1 else {
// Let NSFileManager throw a nice NSError
try NSFileManager.defaultManager().contentsOfDirectoryAtPath(directoryPath)
try NSFileManager.default().contentsOfDirectory(atPath: directoryPath)
// Come on, NSFileManager... OK just throw something that is somewhat relevant
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
let queue = dispatch_queue_create("GRDB.DatabaseStore", nil)
let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(directoryDescriptor), DISPATCH_VNODE_WRITE, queue)
let queue = dispatch_queue_create("GRDB.DatabaseStore", nil)!
let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(directoryDescriptor), DISPATCH_VNODE_WRITE, queue)!
self.queue = queue
self.source = source
@@ -63,8 +63,8 @@ class DatabaseStore {
}
}
private static func setFileAttributes(directoryPath directoryPath: String, databaseFileName: String, attributes: [String: AnyObject]) {
let fm = NSFileManager.defaultManager()
private static func setFileAttributes(directoryPath: String, databaseFileName: String, attributes: [String: AnyObject]) {
let fm = NSFileManager.default()
// TODO: handle symbolic links:
//
// According to https://www.sqlite.org/changes.html
@@ -72,10 +72,10 @@ class DatabaseStore {
// > On unix, if a symlink to a database file is opened, then the
// > corresponding journal files are based on the actual filename,
// > not the symlink name.
let fileNames = try! fm.contentsOfDirectoryAtPath(directoryPath).filter({ $0.hasPrefix(databaseFileName) })
let fileNames = try! fm.contentsOfDirectory(atPath: directoryPath).filter({ $0.hasPrefix(databaseFileName) })
for fileName in fileNames {
do {
try fm.setAttributes(attributes, ofItemAtPath: (directoryPath as NSString).stringByAppendingPathComponent(fileName))
try fm.setAttributes(attributes, ofItemAtPath: (directoryPath as NSString).appendingPathComponent(fileName))
} catch let error as NSError {
guard error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError else {
try! { throw error }()
+41 -41
View File
@@ -22,26 +22,26 @@ public struct DatabaseValue {
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
public enum Storage {
/// The NULL storage class.
case Null
case null
/// The INTEGER storage class, wrapping an Int64.
case Int64(Swift.Int64)
case int64(Int64)
/// The REAL storage class, wrapping a Double.
case Double(Swift.Double)
case double(Double)
/// The TEXT storage class, wrapping a String.
case String(Swift.String)
case string(String)
/// The BLOB storage class, wrapping NSData.
case Blob(NSData)
case blob(NSData)
}
/// The SQLite storage
public let storage: Storage
/// The NULL DatabaseValue.
public static let Null = DatabaseValue(storage: .Null)
public static let null = DatabaseValue(storage: .null)
// MARK: - Extracting Value
@@ -49,7 +49,7 @@ public struct DatabaseValue {
/// Returns true if databaseValue is NULL.
public var isNull: Bool {
switch storage {
case .Null:
case .null:
return true
default:
return false
@@ -59,15 +59,15 @@ public struct DatabaseValue {
/// Returns Int64, Double, String, NSData or nil.
public func value() -> DatabaseValueConvertible? {
switch storage {
case .Null:
case .null:
return nil
case .Int64(let int64):
case .int64(let int64):
return int64
case .Double(let double):
case .double(let double):
return double
case .String(let string):
case .string(let string):
return string
case .Blob(let data):
case .blob(let data):
return data
}
}
@@ -121,18 +121,18 @@ public struct DatabaseValue {
init(sqliteValue: SQLiteValue) {
switch sqlite3_value_type(sqliteValue) {
case SQLITE_NULL:
storage = .Null
storage = .null
case SQLITE_INTEGER:
storage = .Int64(sqlite3_value_int64(sqliteValue))
storage = .int64(sqlite3_value_int64(sqliteValue))
case SQLITE_FLOAT:
storage = .Double(sqlite3_value_double(sqliteValue))
storage = .double(sqlite3_value_double(sqliteValue))
case SQLITE_TEXT:
let cString = UnsafePointer<Int8>(sqlite3_value_text(sqliteValue))
storage = .String(Swift.String.fromCString(cString)!)
storage = .string(String(cString: cString!))
case SQLITE_BLOB:
let bytes = sqlite3_value_blob(sqliteValue)
let length = sqlite3_value_bytes(sqliteValue)
storage = .Blob(NSData(bytes: bytes, length: Int(length))) // copy bytes
storage = .blob(NSData(bytes: bytes, length: Int(length))) // copy bytes
case let type:
fatalError("Unexpected SQLite value type: \(type)")
}
@@ -148,16 +148,16 @@ extension DatabaseValue : Hashable {
/// The hash value
public var hashValue: Int {
switch storage {
case .Null:
case .null:
return 0
case .Int64(let int64):
case .int64(let int64):
// 1 == 1.0, hence 1 and 1.0 must have the same hash:
return Double(int64).hashValue
case .Double(let double):
case .double(let double):
return double.hashValue
case .String(let string):
case .string(let string):
return string.hashValue
case .Blob(let data):
case .blob(let data):
return data.hashValue
}
}
@@ -166,19 +166,19 @@ extension DatabaseValue : Hashable {
/// DatabaseValue adopts Equatable.
public func ==(lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
switch (lhs.storage, rhs.storage) {
case (.Null, .Null):
case (.null, .null):
return true
case (.Int64(let lhs), .Int64(let rhs)):
case (.int64(let lhs), .int64(let rhs)):
return lhs == rhs
case (.Double(let lhs), .Double(let rhs)):
case (.double(let lhs), .double(let rhs)):
return lhs == rhs
case (.Int64(let lhs), .Double(let rhs)):
case (.int64(let lhs), .double(let rhs)):
return int64EqualDouble(lhs, rhs)
case (.Double(let lhs), .Int64(let rhs)):
case (.double(let lhs), .int64(let rhs)):
return int64EqualDouble(rhs, lhs)
case (.String(let lhs), .String(let rhs)):
case (.string(let lhs), .string(let rhs)):
return lhs == rhs
case (.Blob(let lhs), .Blob(let rhs)):
case (.blob(let lhs), .blob(let rhs)):
return lhs == rhs
default:
return false
@@ -187,7 +187,7 @@ public func ==(lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
/// Returns true if i and d hold exactly the same value, and if converting one
/// type into the other does not lose any information.
private func int64EqualDouble(i: Int64, _ d: Double) -> Bool {
private func int64EqualDouble(_ i: Int64, _ d: Double) -> Bool {
// See http://stackoverflow.com/questions/33719132/how-to-test-for-lossless-double-integer-conversion/33784296#33784296
return (d >= Double(Int64.min))
&& (d < Double(Int64.max))
@@ -206,7 +206,7 @@ extension DatabaseValue : DatabaseValueConvertible {
}
/// Returns *databaseValue*, or nil for NULL input.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseValue? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseValue? {
// Follow protocol semantics: DatabaseValueConvertible types turn NULL
// into nil:
//
@@ -224,18 +224,18 @@ extension DatabaseValue : StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, Int32(index)) {
case SQLITE_NULL:
storage = .Null
storage = .null
case SQLITE_INTEGER:
storage = .Int64(sqlite3_column_int64(sqliteStatement, Int32(index)))
storage = .int64(sqlite3_column_int64(sqliteStatement, Int32(index)))
case SQLITE_FLOAT:
storage = .Double(sqlite3_column_double(sqliteStatement, Int32(index)))
storage = .double(sqlite3_column_double(sqliteStatement, Int32(index)))
case SQLITE_TEXT:
let cString = UnsafePointer<Int8>(sqlite3_column_text(sqliteStatement, Int32(index)))
storage = .String(String.fromCString(cString)!)
storage = .string(String(cString: cString!))
case SQLITE_BLOB:
let bytes = sqlite3_column_blob(sqliteStatement, Int32(index))
let length = sqlite3_column_bytes(sqliteStatement, Int32(index))
storage = .Blob(NSData(bytes: bytes, length: Int(length))) // copy bytes
storage = .blob(NSData(bytes: bytes, length: Int(length))) // copy bytes
case let type:
fatalError("Unexpected SQLite column type: \(type)")
}
@@ -250,15 +250,15 @@ extension DatabaseValue : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch storage {
case .Null:
case .null:
return "NULL"
case .Int64(let int64):
case .int64(let int64):
return String(int64)
case .Double(let double):
case .double(let double):
return String(double)
case .String(let string):
case .string(let string):
return String(reflecting: string)
case .Blob(let data):
case .blob(let data):
return data.description
}
}
+26 -26
View File
@@ -8,18 +8,18 @@
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// String.fetch(statement, arguments:...) // DatabaseSequence<String?>
/// String.fetchAll(statement, arguments:...) // [String?]
/// String.fetchOne(statement, arguments:...) // String?
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public protocol DatabaseValueConvertible : _SQLExpressionType {
public protocol DatabaseValueConvertible : _SQLExpressible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from *databaseValue*, if possible.
static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self?
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self?
}
@@ -30,7 +30,7 @@ public protocol DatabaseValueConvertible : _SQLExpressionType {
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// String.fetch(statement, arguments:...) // DatabaseSequence<String>
/// String.fetchAll(statement, arguments:...) // [String]
/// String.fetchOne(statement, arguments:...) // String
@@ -43,7 +43,7 @@ public extension DatabaseValueConvertible {
/// Returns a sequence of values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let names = String.fetch(statement) // DatabaseSequence<String>
///
/// The returned sequence can be consumed several times, but it may yield
@@ -63,7 +63,7 @@ public extension DatabaseValueConvertible {
/// - arguments: Optional statement arguments.
/// - returns: A sequence.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
let sqliteStatement = statement.sqliteStatement
return statement.fetchSequence(arguments: arguments) {
DatabaseValue(sqliteStatement: sqliteStatement, index: 0).value()
@@ -72,7 +72,7 @@ public extension DatabaseValueConvertible {
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let names = String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -80,7 +80,7 @@ public extension DatabaseValueConvertible {
/// - arguments: Optional statement arguments.
/// - returns: An array.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
return Array(fetch(statement, arguments: arguments))
}
@@ -89,7 +89,7 @@ public extension DatabaseValueConvertible {
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let name = String.fetchOne(statement) // String?
///
/// - parameters:
@@ -97,11 +97,11 @@ public extension DatabaseValueConvertible {
/// - arguments: Optional statement arguments.
/// - returns: An optional value.
@warn_unused_result
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
let sequence = statement.fetchSequence(arguments: arguments) {
fromDatabaseValue(DatabaseValue(sqliteStatement: statement.sqliteStatement, index: 0))
}
if let value = sequence.generate().next() {
if let value = sequence.makeIterator().next() {
return value
}
return nil
@@ -132,8 +132,8 @@ public extension DatabaseValueConvertible {
/// - arguments: Optional statement arguments.
/// - returns: A sequence.
@warn_unused_result
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
return fetch(try! db.makeSelectStatement(sql), arguments: arguments)
}
/// Returns an array of values fetched from an SQL query.
@@ -146,8 +146,8 @@ public extension DatabaseValueConvertible {
/// - arguments: Optional statement arguments.
/// - returns: An array.
@warn_unused_result
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] {
return fetchAll(try! db.makeSelectStatement(sql), arguments: arguments)
}
/// Returns a single value fetched from an SQL query.
@@ -163,8 +163,8 @@ public extension DatabaseValueConvertible {
/// - arguments: Optional statement arguments.
/// - returns: An optional value.
@warn_unused_result
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments)
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? {
return fetchOne(try! db.makeSelectStatement(sql), arguments: arguments)
}
}
@@ -175,7 +175,7 @@ public extension DatabaseValueConvertible {
/// Optional<String>.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String?>
/// Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// Optional<String>.fetch(statement, arguments:...) // DatabaseSequence<String?>
/// Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
@@ -187,7 +187,7 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns a sequence of optional values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let names = Optional<String>.fetch(statement) // DatabaseSequence<String?>
///
/// The returned sequence can be consumed several times, but it may yield
@@ -207,7 +207,7 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// - arguments: Optional statement arguments.
/// - returns: A sequence of optional values.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Wrapped?> {
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Wrapped?> {
let sqliteStatement = statement.sqliteStatement
return statement.fetchSequence(arguments: arguments) {
Wrapped.fromDatabaseValue(DatabaseValue(sqliteStatement: sqliteStatement, index: 0))
@@ -216,7 +216,7 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let names = Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
@@ -224,7 +224,7 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// - arguments: Optional statement arguments.
/// - returns: An array of optional values.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Wrapped?] {
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil) -> [Wrapped?] {
return Array(fetch(statement, arguments: arguments))
}
@@ -253,8 +253,8 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// - arguments: Optional statement arguments.
/// - returns: A sequence of optional values.
@warn_unused_result
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Wrapped?> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Wrapped?> {
return fetch(try! db.makeSelectStatement(sql), arguments: arguments)
}
/// Returns an array of optional values fetched from an SQL query.
@@ -267,7 +267,7 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of optional values.
@warn_unused_result
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Wrapped?] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Wrapped?] {
return fetchAll(try! db.makeSelectStatement(sql), arguments: arguments)
}
}
+7 -7
View File
@@ -22,7 +22,7 @@ public protocol DatabaseWriter : DatabaseReader {
///
/// The *block* argument is completely isolated. Eventual concurrent
/// database updates are postponed until the block has executed.
func write<T>(block: (db: Database) throws -> T) rethrows -> T
func write<T>(_ block: (db: Database) throws -> T) rethrows -> T
// MARK: - Reading from Database
@@ -54,10 +54,10 @@ public protocol DatabaseWriter : DatabaseReader {
/// DatabaseQueue.readFromWrite simply runs *block* synchronously, and
/// returns when the block has completed. In the example above, the
/// insertion is run after the select.
func readFromWrite(block: (db: Database) -> Void)
func readFromWrite(_ block: (db: Database) -> Void)
}
extension DatabaseWriter {
extension DatabaseWriter {
// MARK: - Transaction Observers
@@ -66,16 +66,16 @@ extension DatabaseWriter {
///
/// The transaction observer is weakly referenced: it is not retained, and
/// stops getting notifications after it is deallocated.
public func addTransactionObserver(transactionObserver: TransactionObserverType) {
public func add(transactionObserver: TransactionObserver) {
write { db in
db.addTransactionObserver(transactionObserver)
db.add(transactionObserver: transactionObserver)
}
}
/// Remove a transaction observer.
public func removeTransactionObserver(transactionObserver: TransactionObserverType) {
public func remove(transactionObserver: TransactionObserver) {
write { db in
db.removeTransactionObserver(transactionObserver)
db.remove(transactionObserver: transactionObserver)
}
}
}
+145 -124
View File
@@ -53,7 +53,7 @@ public final class Row {
///
/// The statementRef is released in deinit.
let statementRef: Unmanaged<SelectStatement>?
let sqliteStatement: SQLiteStatement
let sqliteStatement: SQLiteStatement?
deinit {
statementRef?.release()
@@ -111,8 +111,8 @@ extension Row {
/// Returns true if and only if the row has that column.
///
/// This method is case-insensitive.
public func hasColumn(columnName: String) -> Bool {
return impl.indexOfColumn(named: columnName) != nil
public func hasColumn(_ columnName: String) -> Bool {
return impl.index(ofColumn: columnName) != nil
}
}
@@ -128,7 +128,7 @@ extension Row {
@warn_unused_result
public func value(atIndex index: Int) -> DatabaseValueConvertible? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).value()
}
/// Returns the value at given index, converted to the requested type.
@@ -142,7 +142,7 @@ extension Row {
@warn_unused_result
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).value()
}
/// Returns the value at given index, converted to the requested type.
@@ -160,7 +160,10 @@ extension Row {
@warn_unused_result
public func value<Value: protocol<DatabaseValueConvertible, StatementColumnConvertible>>(atIndex index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return fastValue(atUncheckedIndex: index)
guard let sqliteStatement = sqliteStatement else {
return impl.databaseValue(atUncheckedIndex: index).value()
}
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
}
/// Returns the value at given index, converted to the requested type.
@@ -173,7 +176,7 @@ extension Row {
@warn_unused_result
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).value()
}
/// Returns the value at given index, converted to the requested type.
@@ -190,7 +193,10 @@ extension Row {
@warn_unused_result
public func value<Value: protocol<DatabaseValueConvertible, StatementColumnConvertible>>(atIndex index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return fastValue(atUncheckedIndex: index)
guard let sqliteStatement = sqliteStatement else {
return impl.databaseValue(atUncheckedIndex: index).value()
}
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
}
/// Returns Int64, Double, String, NSData or nil, depending on the value
@@ -209,10 +215,10 @@ extension Row {
// if row.value(named: "foo") != nil { ... }
//
// Without this method, the code above would not compile.
guard let index = impl.indexOfColumn(named: columnName) else {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.databaseValue(atIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).value()
}
/// Returns the value at given column, converted to the requested type.
@@ -225,10 +231,10 @@ extension Row {
/// `Value`. Should this conversion fail, a fatal error is raised.
@warn_unused_result
public func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value? {
guard let index = impl.indexOfColumn(named: columnName) else {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.databaseValue(atIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).value()
}
/// Returns the value at given column, converted to the requested type.
@@ -245,10 +251,13 @@ extension Row {
/// (see https://www.sqlite.org/datatype3.html).
@warn_unused_result
public func value<Value: protocol<DatabaseValueConvertible, StatementColumnConvertible>>(named columnName: String) -> Value? {
guard let index = impl.indexOfColumn(named: columnName) else {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return fastValue(atUncheckedIndex: index)
guard let sqliteStatement = sqliteStatement else {
return impl.databaseValue(atUncheckedIndex: index).value()
}
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
}
/// Returns the value at given column, converted to the requested type.
@@ -262,10 +271,10 @@ extension Row {
/// SQLite value can not be converted to `Value`.
@warn_unused_result
public func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value {
guard let index = impl.indexOfColumn(named: columnName) else {
guard let index = impl.index(ofColumn: columnName) else {
fatalError("no such column: \(columnName)")
}
return impl.databaseValue(atIndex: index).value()
return impl.databaseValue(atUncheckedIndex: index).value()
}
/// Returns the value at given column, converted to the requested type.
@@ -283,10 +292,13 @@ extension Row {
/// (see https://www.sqlite.org/datatype3.html).
@warn_unused_result
public func value<Value: protocol<DatabaseValueConvertible, StatementColumnConvertible>>(named columnName: String) -> Value {
guard let index = impl.indexOfColumn(named: columnName) else {
guard let index = impl.index(ofColumn: columnName) else {
fatalError("no such column: \(columnName)")
}
return fastValue(atUncheckedIndex: index)
guard let sqliteStatement = sqliteStatement else {
return impl.databaseValue(atUncheckedIndex: index).value()
}
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
}
/// Returns the optional `NSData` at given index.
@@ -302,7 +314,7 @@ extension Row {
@warn_unused_result
public func dataNoCopy(atIndex index: Int) -> NSData? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.dataNoCopy(atIndex: index)
return impl.dataNoCopy(atUncheckedIndex: index)
}
/// Returns the optional `NSData` at given column.
@@ -318,10 +330,10 @@ extension Row {
/// than the row's lifetime.
@warn_unused_result
public func dataNoCopy(named columnName: String) -> NSData? {
guard let index = impl.indexOfColumn(named: columnName) else {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.dataNoCopy(atIndex: index)
return impl.dataNoCopy(atUncheckedIndex: index)
}
}
@@ -344,7 +356,7 @@ extension Row {
@warn_unused_result
public func databaseValue(atIndex index: Int) -> DatabaseValue {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atIndex: index)
return impl.databaseValue(atUncheckedIndex: index)
}
/// Returns the `DatabaseValue` at given column.
@@ -355,10 +367,10 @@ extension Row {
/// The result is nil if the row does not contain the column.
@warn_unused_result
public func databaseValue(named columnName: String) -> DatabaseValue? {
guard let index = impl.indexOfColumn(named: columnName) else {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.databaseValue(atIndex: index)
return impl.databaseValue(atUncheckedIndex: index)
}
}
@@ -367,11 +379,7 @@ extension Row {
// MARK: - Helpers
@warn_unused_result
private func fastValue<Value: protocol<DatabaseValueConvertible, StatementColumnConvertible>>(atUncheckedIndex index: Int) -> Value? {
let sqliteStatement = self.sqliteStatement
guard sqliteStatement != nil else {
return impl.databaseValue(atIndex: index).value()
}
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int, in sqliteStatement: SQLiteStatement) -> Value? {
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
return nil
}
@@ -379,11 +387,7 @@ extension Row {
}
@warn_unused_result
private func fastValue<Value: protocol<DatabaseValueConvertible, StatementColumnConvertible>>(atUncheckedIndex index: Int) -> Value {
let sqliteStatement = self.sqliteStatement
guard sqliteStatement != nil else {
return impl.databaseValue(atIndex: index).value()
}
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int, in sqliteStatement: SQLiteStatement) -> Value {
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
fatalError("could not convert NULL to \(Value.self).")
}
@@ -406,7 +410,7 @@ extension Row {
/// Returns a sequence of rows fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT ...")
/// let statement = db.makeSelectStatement("SELECT ...")
/// for row in Row.fetch(statement) {
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
@@ -439,7 +443,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A sequence of rows.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Row> {
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Row> {
// Metal rows can be reused. And reusing them yields better performance.
let row = try! Row(statement: statement).adaptedRow(adapter: adapter, statement: statement)
return statement.fetchSequence(arguments: arguments) {
@@ -449,7 +453,7 @@ extension Row {
/// Returns an array of rows fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT ...")
/// let statement = db.makeSelectStatement("SELECT ...")
/// let rows = Row.fetchAll(statement)
///
/// - parameters:
@@ -458,7 +462,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> [Row] {
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> [Row] {
let sqliteStatement = statement.sqliteStatement
let columnNames = statement.columnNames
let sequence: DatabaseSequence<Row>
@@ -477,7 +481,7 @@ extension Row {
/// Returns a single row fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT ...")
/// let statement = db.makeSelectStatement("SELECT ...")
/// let row = Row.fetchOne(statement)
///
/// - parameters:
@@ -486,13 +490,13 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
@warn_unused_result
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Row? {
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Row? {
let sqliteStatement = statement.sqliteStatement
let columnNames = statement.columnNames
let sequence = statement.fetchSequence(arguments: arguments) {
Row(copiedFromSQLiteStatement: sqliteStatement, columnNames: columnNames)
}
guard let row = sequence.generate().next() else {
guard let row = sequence.makeIterator().next() else {
return nil
}
return try! row.adaptedRow(adapter: adapter, statement: statement)
@@ -537,8 +541,8 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A sequence of rows.
@warn_unused_result
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Row> {
return fetch(try! db.selectStatement(sql), arguments: arguments, adapter: adapter)
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Row> {
return fetch(try! db.makeSelectStatement(sql), arguments: arguments, adapter: adapter)
}
/// Returns an array of rows fetched from an SQL query.
@@ -552,8 +556,8 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
@warn_unused_result
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> [Row] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments, adapter: adapter)
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> [Row] {
return fetchAll(try! db.makeSelectStatement(sql), arguments: arguments, adapter: adapter)
}
/// Returns a single row fetched from an SQL query.
@@ -567,29 +571,23 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
@warn_unused_result
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Row? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments, adapter: adapter)
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Row? {
return fetchOne(try! db.makeSelectStatement(sql), arguments: arguments, adapter: adapter)
}
}
extension Row : CollectionType {
extension Row : Collection {
// MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs
/// The number of columns in the row.
public var count: Int {
let sqliteStatement = self.sqliteStatement
guard sqliteStatement != nil else {
return impl.count
}
return Int(sqlite3_column_count(sqliteStatement))
}
/// Returns a *generator* over (ColumnName, DatabaseValue) pairs, from left
/// to right.
public func generate() -> IndexingGenerator<Row> {
return IndexingGenerator(self)
}
// TODO
// /// The number of columns in the row.
// public var count: Int {
// guard let sqliteStatement = sqliteStatement else {
// return impl.count
// }
// return Int(sqlite3_column_count(sqliteStatement))
// }
/// The index of the first (ColumnName, DatabaseValue) pair.
public var startIndex: RowIndex {
@@ -602,14 +600,44 @@ extension Row : CollectionType {
return Index(impl.count)
}
/// Returns the (ColumnName, DatabaseValue) pair at given index.
public subscript(index: RowIndex) -> (String, DatabaseValue) {
/// Accesses the (ColumnName, DatabaseValue) pair at given index.
public subscript(position: RowIndex) -> (String, DatabaseValue) {
let index = position.index
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return (
impl.columnName(atIndex: index.index),
impl.databaseValue(atIndex: index.index))
impl.columnName(atUncheckedIndex: index),
impl.databaseValue(atUncheckedIndex: index))
}
/// Returns the position immediately after `i`.
///
/// - Precondition: `(startIndex..<endIndex).contains(i)`
public func index(after i: RowIndex) -> RowIndex {
return RowIndex(i.index + 1)
}
/// Replaces `i` with its successor.
public func formIndex(after i: inout RowIndex) {
i = RowIndex(i.index + 1)
}
}
// TODO
//extension Row : BidirectionalCollection {
//
// /// Returns the position immediately preceding `i`.
// ///
// /// - Precondition: `i > startIndex && i <= endIndex`
// public func index(before i: RowIndex) -> RowIndex {
// return RowIndex(i.index - 1)
// }
//}
//
// TODO
//extension Row : RandomAccessCollection {
//
//}
extension Row : Equatable { }
/// Returns true if and only if both rows have the same columns and values, in
@@ -623,10 +651,10 @@ public func ==(lhs: Row, rhs: Row) -> Bool {
return false
}
var lgen = lhs.generate()
var rgen = rhs.generate()
var liter = lhs.makeIterator()
var riter = rhs.makeIterator()
while let (lcol, lval) = lgen.next(), let (rcol, rval) = rgen.next() {
while let (lcol, lval) = liter.next(), let (rcol, rval) = riter.next() {
guard lcol == rcol else {
return false
}
@@ -659,7 +687,7 @@ extension Row: CustomStringConvertible {
return "<Row"
+ map { (column, dbv) in
" \(column):\(dbv)"
}.joinWithSeparator("")
}.joined(separator: "")
+ ">"
}
}
@@ -668,22 +696,9 @@ extension Row: CustomStringConvertible {
// MARK: - RowIndex
/// Indexes to (columnName, databaseValue) pairs in a database row.
public struct RowIndex: ForwardIndexType, BidirectionalIndexType, RandomAccessIndexType {
public struct RowIndex : Comparable {
let index: Int
init(_ index: Int) { self.index = index }
/// The index of the next (ColumnName, DatabaseValue) pair in a row.
public func successor() -> RowIndex { return RowIndex(index + 1) }
/// The index of the previous (ColumnName, DatabaseValue) pair in a row.
public func predecessor() -> RowIndex { return RowIndex(index - 1) }
/// The number of columns between two (ColumnName, DatabaseValue) pairs in
/// a row.
public func distanceTo(other: RowIndex) -> Int { return other.index - index }
/// Return `self` offset by `n` steps.
public func advancedBy(n: Int) -> RowIndex { return RowIndex(index + n) }
}
/// Equatable implementation for RowIndex
@@ -691,26 +706,30 @@ public func ==(lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index == rhs.index
}
public func <(lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index < rhs.index
}
// MARK: - RowImpl
// The protocol for Row underlying implementation
protocol RowImpl {
var count: Int { get }
func databaseValue(atIndex index: Int) -> DatabaseValue
func dataNoCopy(atIndex index:Int) -> NSData?
func columnName(atIndex index: Int) -> String
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
func dataNoCopy(atUncheckedIndex index:Int) -> NSData?
func columnName(atUncheckedIndex index: Int) -> String
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func indexOfColumn(named name: String) -> Int?
func index(ofColumn name: String) -> Int?
func subrow(named name: String) -> Row?
var subrowNames: Set<String> { get }
// row.impl is guaranteed to be self.
func copy(row: Row) -> Row
func copy(_ row: Row) -> Row
}
@@ -726,26 +745,28 @@ private struct DictionaryRowImpl : RowImpl {
return dictionary.count
}
func dataNoCopy(atIndex index:Int) -> NSData? {
return databaseValue(atIndex: index).value()
func dataNoCopy(atUncheckedIndex index:Int) -> NSData? {
return databaseValue(atUncheckedIndex: index).value()
}
func databaseValue(atIndex index: Int) -> DatabaseValue {
return dictionary[dictionary.startIndex.advancedBy(index)].1?.databaseValue ?? .Null
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
let i = dictionary.index(dictionary.startIndex, offsetBy: index)
return dictionary[i].1?.databaseValue ?? .null
}
func columnName(atIndex index: Int) -> String {
return dictionary[dictionary.startIndex.advancedBy(index)].0
func columnName(atUncheckedIndex index: Int) -> String {
let i = dictionary.index(dictionary.startIndex, offsetBy: index)
return dictionary[i].0
}
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func indexOfColumn(named name: String) -> Int? {
let lowercaseName = name.lowercaseString
guard let index = dictionary.indexOf({ (column, value) in column.lowercaseString == lowercaseName }) else {
func index(ofColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
guard let index = dictionary.index(where: { (column, value) in column.lowercased() == lowercaseName }) else {
return nil
}
return dictionary.startIndex.distanceTo(index)
return dictionary.distance(from: dictionary.startIndex, to: index)
}
func subrow(named name: String) -> Row? {
@@ -756,7 +777,7 @@ private struct DictionaryRowImpl : RowImpl {
return []
}
func copy(row: Row) -> Row {
func copy(_ row: Row) -> Row {
return row
}
}
@@ -768,7 +789,6 @@ private struct StatementCopyRowImpl : RowImpl {
let columnNames: [String]
init(sqliteStatement: SQLiteStatement, columnNames: [String]) {
assert(sqliteStatement != nil)
let sqliteStatement = sqliteStatement
self.databaseValues = ContiguousArray((0..<sqlite3_column_count(sqliteStatement)).lazy.map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) })
self.columnNames = columnNames
@@ -778,23 +798,23 @@ private struct StatementCopyRowImpl : RowImpl {
return columnNames.count
}
func dataNoCopy(atIndex index:Int) -> NSData? {
return databaseValue(atIndex: index).value()
func dataNoCopy(atUncheckedIndex index:Int) -> NSData? {
return databaseValue(atUncheckedIndex: index).value()
}
func databaseValue(atIndex index: Int) -> DatabaseValue {
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return databaseValues[index]
}
func columnName(atIndex index: Int) -> String {
func columnName(atUncheckedIndex index: Int) -> String {
return columnNames[index]
}
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func indexOfColumn(named name: String) -> Int? {
let lowercaseName = name.lowercaseString
return columnNames.indexOf { $0.lowercaseString == lowercaseName }
func index(ofColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columnNames.index { $0.lowercased() == lowercaseName }
}
func subrow(named name: String) -> Row? {
@@ -805,7 +825,7 @@ private struct StatementCopyRowImpl : RowImpl {
return []
}
func copy(row: Row) -> Row {
func copy(_ row: Row) -> Row {
return row
}
}
@@ -818,42 +838,43 @@ private struct StatementRowImpl : RowImpl {
let lowercaseColumnIndexes: [String: Int]
init(sqliteStatement: SQLiteStatement, statementRef: Unmanaged<SelectStatement>) {
assert(sqliteStatement != nil)
self.statementRef = statementRef
self.sqliteStatement = sqliteStatement
// Optimize row.value(named: "...")
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement)).map { String.fromCString(sqlite3_column_name(sqliteStatement, Int32($0)))!.lowercaseString }
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: lowercaseColumnNames.enumerate().map { ($1, $0) }.reverse())
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement)).map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: lowercaseColumnNames.enumerated().map { ($1, $0) }.reversed())
}
var count: Int {
return Int(sqlite3_column_count(sqliteStatement))
}
func dataNoCopy(atIndex index:Int) -> NSData? {
func dataNoCopy(atUncheckedIndex index:Int) -> NSData? {
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
return nil
}
let bytes = sqlite3_column_blob(sqliteStatement, Int32(index))
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
return nil
}
let length = sqlite3_column_bytes(sqliteStatement, Int32(index))
return NSData(bytesNoCopy: UnsafeMutablePointer(bytes), length: Int(length), freeWhenDone: false)
}
func databaseValue(atIndex index: Int) -> DatabaseValue {
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
}
func columnName(atIndex index: Int) -> String {
func columnName(atUncheckedIndex index: Int) -> String {
return statementRef.takeUnretainedValue().columnNames[index]
}
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func indexOfColumn(named name: String) -> Int? {
func index(ofColumn name: String) -> Int? {
if let index = lowercaseColumnIndexes[name] {
return index
}
return lowercaseColumnIndexes[name.lowercaseString]
return lowercaseColumnIndexes[name.lowercased()]
}
func subrow(named name: String) -> Row? {
@@ -864,7 +885,7 @@ private struct StatementRowImpl : RowImpl {
return []
}
func copy(row: Row) -> Row {
func copy(_ row: Row) -> Row {
return Row(copiedFromSQLiteStatement: sqliteStatement, statementRef: statementRef)
}
}
@@ -874,19 +895,19 @@ private struct StatementRowImpl : RowImpl {
private struct EmptyRowImpl : RowImpl {
var count: Int { return 0 }
func databaseValue(atIndex index: Int) -> DatabaseValue {
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
fatalError("row index out of range")
}
func dataNoCopy(atIndex index:Int) -> NSData? {
func dataNoCopy(atUncheckedIndex index:Int) -> NSData? {
fatalError("row index out of range")
}
func columnName(atIndex index: Int) -> String {
func columnName(atUncheckedIndex index: Int) -> String {
fatalError("row index out of range")
}
func indexOfColumn(named name: String) -> Int? {
func index(ofColumn name: String) -> Int? {
return nil
}
@@ -898,7 +919,7 @@ private struct EmptyRowImpl : RowImpl {
return []
}
func copy(row: Row) -> Row {
func copy(_ row: Row) -> Row {
return row
}
}
+22 -22
View File
@@ -150,7 +150,7 @@ public struct RowAdapter {
}
// Return an array [(baseRowIndex, mappedColumn), ...] ordered like the statement columns.
private func columnBaseIndexes(statement statement: SelectStatement) throws -> [(Int, String)] {
private func columnBaseIndexes(statement: SelectStatement) throws -> [(Int, String)] {
return try impl.columnBaseIndexes(statement: statement)
}
}
@@ -163,10 +163,10 @@ extension RowAdapter : DictionaryLiteralConvertible {
private protocol RowAdapterImpl {
// Return an array [(baseRowIndex, mappedColumn), ...] ordered like the statement columns.
func columnBaseIndexes(statement statement: SelectStatement) throws -> [(Int, String)]
func columnBaseIndexes(statement: SelectStatement) throws -> [(Int, String)]
// Bindings for subrows
func subBindings(statement statement: SelectStatement) throws -> [String: AdapterRowImpl.Binding]
func subBindings(statement: SelectStatement) throws -> [String: AdapterRowImpl.Binding]
}
extension RowAdapterImpl {
@@ -178,29 +178,29 @@ extension RowAdapterImpl {
}
// default implementation
func subBindings(statement statement: SelectStatement) throws -> [String: AdapterRowImpl.Binding] {
func subBindings(statement: SelectStatement) throws -> [String: AdapterRowImpl.Binding] {
return [:]
}
}
private struct IdentityRowAdapterImpl: RowAdapterImpl {
func columnBaseIndexes(statement statement: SelectStatement) throws -> [(Int, String)] {
return Array(statement.columnNames.enumerate())
func columnBaseIndexes(statement: SelectStatement) throws -> [(Int, String)] {
return Array(statement.columnNames.enumerated().map { ($0.offset, $0.element) })
}
}
private struct DictionaryRowAdapterImpl: RowAdapterImpl {
let dictionary: [String: String]
func columnBaseIndexes(statement statement: SelectStatement) throws -> [(Int, String)] {
func columnBaseIndexes(statement: SelectStatement) throws -> [(Int, String)] {
return try dictionary
.map { (mappedColumn, baseColumn) -> (Int, String) in
guard let index = statement.indexOfColumn(named: baseColumn) else {
throw DatabaseError(code: SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(statement.columnNames.joinWithSeparator(", ")).")
guard let index = statement.index(ofColumn: baseColumn) else {
throw DatabaseError(code: SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(statement.columnNames.joined(separator: ", ")).")
}
return (index, mappedColumn)
}
.sort { return $0.0 < $1.0 }
.sorted { return $0.0 < $1.0 }
}
}
@@ -208,11 +208,11 @@ private struct NestedRowAdapterImpl: RowAdapterImpl {
let mainRowAdapter: RowAdapter
let subRowAdapters: [String: RowAdapter]
func columnBaseIndexes(statement statement: SelectStatement) throws -> [(Int, String)] {
func columnBaseIndexes(statement: SelectStatement) throws -> [(Int, String)] {
return try mainRowAdapter.columnBaseIndexes(statement: statement)
}
func subBindings(statement statement: SelectStatement) throws -> [String: AdapterRowImpl.Binding] {
func subBindings(statement: SelectStatement) throws -> [String: AdapterRowImpl.Binding] {
let subBindings = try subRowAdapters.map { (identifier: String, adapter: RowAdapter) -> (String, AdapterRowImpl.Binding) in
let subrowAdapter = try AdapterRowImpl.Binding(
columnsAdapter: ColumnsAdapter(columnBaseIndexes: adapter.columnBaseIndexes(statement: statement)),
@@ -229,7 +229,7 @@ struct ColumnsAdapter {
init(columnBaseIndexes: [(Int, String)]) {
self.columnBaseIndexes = columnBaseIndexes
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: columnBaseIndexes.enumerate().map { ($1.1.lowercaseString, $0) })
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: columnBaseIndexes.enumerated().map { ($1.1.lowercased(), $0) })
}
var count: Int {
@@ -244,11 +244,11 @@ struct ColumnsAdapter {
return columnBaseIndexes[index].1
}
func adaptedIndexOfColumn(named name: String) -> Int? {
func adaptedIndex(ofColumn name: String) -> Int? {
if let index = lowercaseColumnIndexes[name] {
return index
}
return lowercaseColumnIndexes[name.lowercaseString]
return lowercaseColumnIndexes[name.lowercased()]
}
}
@@ -259,7 +259,7 @@ extension Row {
}
/// Returns self if adapter is nil
func adaptedRow(adapter adapter: RowAdapter?, statement: SelectStatement) throws -> Row {
func adaptedRow(adapter: RowAdapter?, statement: SelectStatement) throws -> Row {
guard let adapter = adapter else {
return self
}
@@ -288,20 +288,20 @@ struct AdapterRowImpl : RowImpl {
return columnsAdapter.count
}
func databaseValue(atIndex index: Int) -> DatabaseValue {
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return baseRow.databaseValue(atIndex: columnsAdapter.baseColumIndex(adaptedIndex: index))
}
func dataNoCopy(atIndex index:Int) -> NSData? {
func dataNoCopy(atUncheckedIndex index:Int) -> NSData? {
return baseRow.dataNoCopy(atIndex: columnsAdapter.baseColumIndex(adaptedIndex: index))
}
func columnName(atIndex index: Int) -> String {
func columnName(atUncheckedIndex index: Int) -> String {
return columnsAdapter.columnName(adaptedIndex: index)
}
func indexOfColumn(named name: String) -> Int? {
return columnsAdapter.adaptedIndexOfColumn(named: name)
func index(ofColumn name: String) -> Int? {
return columnsAdapter.adaptedIndex(ofColumn: name)
}
func subrow(named name: String) -> Row? {
@@ -315,7 +315,7 @@ struct AdapterRowImpl : RowImpl {
return Set(binding.subBindings.keys)
}
func copy(row: Row) -> Row {
func copy(_ row: Row) -> Row {
return Row(baseRow: baseRow.copy(), adapterBinding: binding)
}
}
+6 -6
View File
@@ -13,7 +13,7 @@ final class SerializedDatabase {
/// The dispatch queue
private let queue: dispatch_queue_t
init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCacheType) throws {
init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache) throws {
// According to https://www.sqlite.org/threadsafe.html
//
// > SQLite support three different threading modes:
@@ -32,7 +32,7 @@ final class SerializedDatabase {
// Since our database connection is only used via our serial dispatch
// queue, there is no purpose using the default serialized mode.
var config = configuration
config.threadingMode = .MultiThread
config.threadingMode = .multiThread
db = try Database(path: path, configuration: config, schemaCache: schemaCache)
queue = DatabaseScheduler.makeSerializedQueueAllowing(database: db)
@@ -51,12 +51,12 @@ final class SerializedDatabase {
/// its result.
///
/// This method is *not* reentrant.
func performSync<T>(block: (db: Database) throws -> T) rethrows -> T {
func performSync<T>(_ block: (db: Database) throws -> T) rethrows -> T {
return try DatabaseScheduler.dispatchSync(queue, database: db, block: block)
}
/// Asynchronously executes a block in the serialized dispatch queue.
func performAsync(block: (db: Database) -> Void) {
func performAsync(_ block: (db: Database) -> Void) {
dispatch_async(queue) {
block(db: self.db)
}
@@ -65,13 +65,13 @@ final class SerializedDatabase {
/// Executes the block in the current queue.
///
/// - precondition: the current dispatch queue is valid.
func perform<T>(block: (db: Database) throws -> T) rethrows -> T {
func perform<T>(_ block: (db: Database) throws -> T) rethrows -> T {
preconditionValidQueue()
return try block(db: db)
}
/// Fatal error if current dispatch queue is not valid.
func preconditionValidQueue(@autoclosure message: () -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
DatabaseScheduler.preconditionValidQueue(db, message, file: file, line: line)
}
}
+108 -107
View File
@@ -13,7 +13,7 @@ import Foundation
#endif
/// A raw SQLite statement, suitable for the SQLite C API.
public typealias SQLiteStatement = COpaquePointer
public typealias SQLiteStatement = OpaquePointer
/// A statement represents an SQL query.
///
@@ -26,7 +26,7 @@ public class Statement {
/// The SQL query
public var sql: String {
return String.fromCString(sqlite3_sql(sqliteStatement))!
return String(cString: sqlite3_sql(sqliteStatement))
}
/// The database
@@ -44,27 +44,29 @@ public class Statement {
defer { observer.stop() }
let sqlCodeUnits = sql.nulTerminatedUTF8
var sqliteStatement: SQLiteStatement = nil
var sqliteStatement: SQLiteStatement? = nil
var code: Int32 = 0
var remainingSQL = ""
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)
var sqlEnd: UnsafePointer<Int8> = nil
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var sqlEnd: UnsafePointer<Int8>? = nil
code = sqlite3_prepare_v2(database.sqliteConnection, sqlStart, -1, &sqliteStatement, &sqlEnd)
let remainingData = NSData(bytesNoCopy: UnsafeMutablePointer<Void>(sqlEnd), length: sqlStart + sqlCodeUnits.count - sqlEnd - 1, freeWhenDone: false)
remainingSQL = String(data: remainingData, encoding: NSUTF8StringEncoding)!.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
let remainingData = NSData(bytesNoCopy: UnsafeMutablePointer<Void>(sqlEnd!), length: sqlStart + sqlCodeUnits.count - sqlEnd! - 1, freeWhenDone: false)
remainingSQL = String(data: remainingData, encoding: NSUTF8StringEncoding)!.trimmingCharacters(in: .whitespacesAndNewlines())
}
self.database = database
self.sqliteStatement = sqliteStatement
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql)
}
guard remainingSQL.isEmpty else {
sqlite3_finalize(sqliteStatement)
throw DatabaseError(code: SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
}
self.database = database
self.sqliteStatement = sqliteStatement!
}
deinit {
@@ -91,10 +93,10 @@ public class Statement {
// Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
private lazy var sqliteArgumentNames: [String?] = {
return (0..<self.sqliteArgumentCount).map {
guard let name = String.fromCString(sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1))) else {
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1)) else {
return nil
}
return String(name.characters.dropFirst()) // Drop initial ":"
return String(String(cString: cString).characters.dropFirst()) // Drop initial ":"
}
}()
@@ -106,12 +108,12 @@ public class Statement {
/// Throws a DatabaseError of code SQLITE_ERROR if arguments don't fill all
/// statement arguments.
public func validateArguments(arguments: StatementArguments) throws {
public func validate(arguments: StatementArguments) throws {
_ = try validatedBindings(arguments)
}
/// Set arguments without any validation. Trades safety for performance.
public func unsafeSetArguments(arguments: StatementArguments) {
public func unsafeSetArguments(_ arguments: StatementArguments) {
_arguments = arguments
argumentsNeedValidation = false
@@ -120,21 +122,21 @@ public class Statement {
try! clearBindings()
switch arguments.kind {
case .Values(let values):
for (index, value) in values.enumerate() {
try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1))
case .values(let values):
for (index, value) in values.enumerated() {
try! bind(databaseValue: value?.databaseValue ?? .null, at: Int32(index + 1))
}
break
case .NamedValues(let namedValues):
for (index, argumentName) in sqliteArgumentNames.enumerate() {
case .namedValues(let namedValues):
for (index, argumentName) in sqliteArgumentNames.enumerated() {
if let argumentName = argumentName, let value = namedValues[argumentName] {
try! bindDatabaseValue(value?.databaseValue ?? .Null, atIndex: Int32(index + 1))
try! bind(databaseValue: value?.databaseValue ?? .null, at: Int32(index + 1))
}
}
}
}
func setArgumentsWithValidation(arguments: StatementArguments) throws {
func setArgumentsWithValidation(_ arguments: StatementArguments) throws {
// Validate
let bindings = try validatedBindings(arguments)
_arguments = arguments
@@ -143,23 +145,23 @@ public class Statement {
// Apply
try! reset()
try! clearBindings()
for (index, databaseValue) in bindings.enumerate() {
try bindDatabaseValue(databaseValue, atIndex: Int32(index + 1))
for (index, databaseValue) in bindings.enumerated() {
try bind(databaseValue: databaseValue, at: Int32(index + 1))
}
}
private func bindDatabaseValue(databaseValue: DatabaseValue, atIndex index: Int32) throws {
private func bind(databaseValue: DatabaseValue, at index: Int32) throws {
let code: Int32
switch databaseValue.storage {
case .Null:
case .null:
code = sqlite3_bind_null(sqliteStatement, index)
case .Int64(let int64):
case .int64(let int64):
code = sqlite3_bind_int64(sqliteStatement, index, int64)
case .Double(let double):
case .double(let double):
code = sqlite3_bind_double(sqliteStatement, index, double)
case .String(let string):
case .string(let string):
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
case .Blob(let data):
case .blob(let data):
code = sqlite3_bind_blob(sqliteStatement, index, data.bytes, Int32(data.length), SQLITE_TRANSIENT)
}
@@ -171,7 +173,7 @@ public class Statement {
// 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] {
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.
@@ -185,35 +187,35 @@ public class Statement {
// If one of the values is nil, then we have a missing argument.
let keyValueBindings: [(String?, DatabaseValue?)] = {
switch arguments.kind {
case .Values(let values):
case .values(let values):
var keyValueBindings: [(String?, DatabaseValue?)] = []
var argumentNameGen = sqliteArgumentNames.generate()
var valuesGen = values.map { $0?.databaseValue ?? .Null }.generate()
var argumentNameOpt = argumentNameGen.next()
var valueOpt = valuesGen.next()
var argumentNameIter = sqliteArgumentNames.makeIterator()
var valuesIter = values.map { $0?.databaseValue ?? .null }.makeIterator()
var argumentNameOpt = argumentNameIter.next()
var valueOpt = valuesIter.next()
outer: while true {
switch (argumentNameOpt, valueOpt) {
case (let argumentName?, let value?):
keyValueBindings.append((argumentName, value))
argumentNameOpt = argumentNameGen.next()
valueOpt = valuesGen.next()
argumentNameOpt = argumentNameIter.next()
valueOpt = valuesIter.next()
case (nil, let value?):
keyValueBindings.append((nil, value))
valueOpt = valuesGen.next()
valueOpt = valuesIter.next()
case (let argumentName?, nil):
keyValueBindings.append((argumentName, nil))
argumentNameOpt = argumentNameGen.next()
argumentNameOpt = argumentNameIter.next()
case (nil, nil):
break outer
}
}
return keyValueBindings
case .NamedValues(let namedValues):
case .namedValues(let namedValues):
return sqliteArgumentNames.map { argumentName in
if let argumentName = argumentName {
if let value = namedValues[argumentName] {
return (argumentName, value?.databaseValue ?? .Null)
return (argumentName, value?.databaseValue ?? .null)
} else {
return (argumentName, nil)
}
@@ -231,13 +233,13 @@ public class Statement {
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] {
func caseInsensitiveSort(_ strings: [String]) -> [String] {
return strings
.map { ($0.lowercaseString, $0) }
.sort { $0.0 < $1.0 }
.map { ($0.lowercased(), $0) }
.sorted { $0.0 < $1.0 }
.map { $0.1 }
}
throw DatabaseError(code: SQLITE_MISUSE, message: "missing statement argument(s): \(caseInsensitiveSort(namedMissingKeys).joinWithSeparator(", "))", sql: sql, arguments: nil)
throw DatabaseError(code: SQLITE_MISUSE, message: "missing statement argument(s): \(caseInsensitiveSort(namedMissingKeys).joined(separator: ", "))", sql: sql, arguments: nil)
} else {
throw DatabaseError(code: SQLITE_MISUSE, message: "wrong number of statement arguments: \(sqliteArgumentCount - missingKeys.count)", sql: sql, arguments: nil)
}
@@ -254,11 +256,11 @@ public class Statement {
}
}
private func prepareWithArguments(arguments: StatementArguments?) throws {
private func prepare(withArguments arguments: StatementArguments?) throws {
if let arguments = arguments {
try setArgumentsWithValidation(arguments)
} else if argumentsNeedValidation {
try validateArguments(self.arguments)
try validate(arguments: self.arguments)
}
}
}
@@ -268,10 +270,10 @@ public class Statement {
/// A subclass of Statement that fetches database rows.
///
/// You create SelectStatement with the Database.selectStatement() method:
/// You create SelectStatement with the Database.makeSelectStatement() method:
///
/// dbQueue.inDatabase { db in
/// let statement = db.selectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
/// let statement = db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
/// let moreThanTwentyCount = Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])!
/// }
@@ -296,44 +298,44 @@ public final class SelectStatement : Statement {
/// The column names, ordered from left to right.
public lazy var columnNames: [String] = {
let sqliteStatement = self.sqliteStatement
return (0..<self.columnCount).map { String.fromCString(sqlite3_column_name(sqliteStatement, Int32($0)))! }
return (0..<self.columnCount).map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))) }
}()
/// Cache for indexOfColumn(). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
return Dictionary(keyValueSequence: self.columnNames.enumerate().map { ($1.lowercaseString, $0) }.reverse())
return Dictionary(keyValueSequence: self.columnNames.enumerated().map { ($1.lowercased(), $0) }.reversed())
}()
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func indexOfColumn(named name: String) -> Int? {
return columnIndexes[name.lowercaseString]
func index(ofColumn name: String) -> Int? {
return columnIndexes[name.lowercased()]
}
/// Creates a DatabaseSequence
@warn_unused_result
func fetchSequence<Element>(arguments arguments: StatementArguments?, element: () -> Element) -> DatabaseSequence<Element> {
func fetchSequence<Element>(arguments: StatementArguments?, element: () -> Element) -> DatabaseSequence<Element> {
// Force arguments validity. See UpdateStatement.execute(), and Database.execute()
try! prepareWithArguments(arguments)
try! prepare(withArguments: arguments)
return DatabaseSequence(statement: self, element: element)
}
}
/// A sequence of elements fetched from the database.
public struct DatabaseSequence<Element>: SequenceType {
private let generateImpl: () throws -> DatabaseGenerator<Element>
public struct DatabaseSequence<Element>: Sequence {
private let makeIteratorImpl: () throws -> DatabaseIterator<Element>
// Statement sequence
private init(statement: SelectStatement, element: () -> Element) {
self.generateImpl = {
// Check that generator is built on a valid queue.
self.makeIteratorImpl = {
// Check that iterator is built on a valid queue.
DatabaseScheduler.preconditionValidQueue(statement.database, "Database was not used on the correct thread. Iterate sequences in a protected dispatch queue, or consider using an array returned by fetchAll() instead.")
// Support multiple sequence iterations
try statement.reset()
let statementRef = Unmanaged.passRetained(statement)
return DatabaseGenerator(statementRef: statementRef) { (sqliteStatement, statementRef) in
return DatabaseIterator(statementRef: statementRef) { (sqliteStatement, statementRef) in
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
return nil
@@ -349,34 +351,34 @@ public struct DatabaseSequence<Element>: SequenceType {
}
// Empty sequence
static func emptySequence(database: Database) -> DatabaseSequence {
static func makeEmptySequence(inDatabase database: Database) -> DatabaseSequence {
// Empty sequence is just as strict as statement sequence, and requires
// to be used on the database queue.
return DatabaseSequence() {
// Check that generator is built on a valid queue.
// Check that iterator is built on a valid queue.
DatabaseScheduler.preconditionValidQueue(database, "Database was not used on the correct thread. Iterate sequences in a protected dispatch queue, or consider using an array returned by fetchAll() instead.")
return DatabaseGenerator()
return DatabaseIterator()
}
}
private init(generateImpl: () throws -> DatabaseGenerator<Element>) {
self.generateImpl = generateImpl
private init(_ makeIteratorImpl: () throws -> DatabaseIterator<Element>) {
self.makeIteratorImpl = makeIteratorImpl
}
/// Return a *generator* over the elements of this *sequence*.
/// Return a *iterator* over the elements of this *sequence*.
@warn_unused_result
public func generate() -> DatabaseGenerator<Element> {
return try! generateImpl()
public func makeIterator() -> DatabaseIterator<Element> {
return try! makeIteratorImpl()
}
}
/// A generator of elements fetched from the database.
public class DatabaseGenerator<Element>: GeneratorType {
/// A iterator of elements fetched from the database.
public final class DatabaseIterator<Element>: IteratorProtocol {
private let statementRef: Unmanaged<SelectStatement>?
private let sqliteStatement: SQLiteStatement
private let sqliteStatement: SQLiteStatement?
private let element: ((SQLiteStatement, Unmanaged<SelectStatement>) -> Element?)?
// Generator takes ownership of statementRef
// Iterator takes ownership of statementRef
init(statementRef: Unmanaged<SelectStatement>, element: (SQLiteStatement, Unmanaged<SelectStatement>) -> Element?) {
self.statementRef = statementRef
self.sqliteStatement = statementRef.takeUnretainedValue().sqliteStatement
@@ -398,8 +400,7 @@ public class DatabaseGenerator<Element>: GeneratorType {
guard let element = element else {
return nil
}
// TODO: use unsafeUnWrap(statementRef)
return element(sqliteStatement, statementRef!)
return element(sqliteStatement.unsafelyUnwrapped, statementRef.unsafelyUnwrapped)
}
}
@@ -408,13 +409,13 @@ public class DatabaseGenerator<Element>: GeneratorType {
/// A subclass of Statement that executes SQL queries.
///
/// You create UpdateStatement with the Database.updateStatement() method:
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
///
/// try dbQueue.inTransaction { db in
/// let statement = try db.updateStatement("INSERT INTO persons (name) VALUES (?)")
/// let statement = try db.makeUpdateStatement("INSERT INTO persons (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// return .Commit
/// return .commit
/// }
public final class UpdateStatement : Statement {
/// If true, the database schema cache gets invalidated after this statement
@@ -441,11 +442,11 @@ public final class UpdateStatement : Statement {
///
/// - parameter arguments: Statement arguments.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(arguments arguments: StatementArguments? = nil) throws {
public func execute(arguments: StatementArguments? = nil) throws {
DatabaseScheduler.preconditionValidQueue(database)
// Force arguments validity. See SelectStatement.fetchSequence(), and Database.execute()
try! prepareWithArguments(arguments)
try! prepare(withArguments: arguments)
try! reset()
switch sqlite3_step(sqliteStatement) {
@@ -514,9 +515,9 @@ public struct StatementArguments {
public var isEmpty: Bool {
switch kind {
case .Values(let values):
case .values(let values):
return values.isEmpty
case .NamedValues(let namedValues):
case .namedValues(let namedValues):
return namedValues.isEmpty
}
}
@@ -531,8 +532,8 @@ public struct StatementArguments {
///
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
/// - returns: A StatementArguments.
public init<Sequence: SequenceType where Sequence.Generator.Element == DatabaseValueConvertible?>(_ sequence: Sequence) {
kind = .Values(Array(sequence))
public init<Sequence: Swift.Sequence where Sequence.Iterator.Element == DatabaseValueConvertible?>(_ sequence: Sequence) {
kind = .values(Array(sequence))
}
/// Initializes arguments from a sequence of optional values.
@@ -542,13 +543,25 @@ public struct StatementArguments {
///
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
/// - returns: A StatementArguments.
public init<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(_ sequence: Sequence) {
kind = .Values(sequence.map { $0 })
public init<Sequence: Swift.Sequence where Sequence.Iterator.Element: DatabaseValueConvertible>(_ sequence: Sequence) {
kind = .values(sequence.map { $0 })
}
// MARK: Named Arguments
/// Initializes arguments from a sequence of (key, value) dictionary, such as
/// a dictionary.
///
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
kind = .namedValues(dictionary)
}
/// Initializes arguments from a sequence of (key, value) pairs, such as
/// a dictionary.
///
@@ -557,20 +570,8 @@ public struct StatementArguments {
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
public init<Sequence: SequenceType where Sequence.Generator.Element == (String, DatabaseValueConvertible?)>(_ sequence: Sequence) {
kind = .NamedValues(Dictionary(keyValueSequence: sequence))
}
/// Initializes arguments from a sequence of (key, value) pairs, such as
/// a dictionary.
///
/// let values: [String: String] = ["firstName": "Arthur", "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
public init<Sequence: SequenceType, Value: DatabaseValueConvertible where Sequence.Generator.Element == (String, Value)>(_ sequence: Sequence) {
kind = .NamedValues(Dictionary(keyValueSequence: sequence.map { (key, value) in return (key, value as DatabaseValueConvertible?) }))
public init<Sequence: Swift.Sequence where Sequence.Iterator.Element == (String, DatabaseValueConvertible?)>(_ sequence: Sequence) {
kind = .namedValues(Dictionary(keyValueSequence: sequence))
}
@@ -579,16 +580,16 @@ public struct StatementArguments {
/// Returns a double optional
func value(named name: String) -> DatabaseValueConvertible?? {
switch kind {
case .Values:
case .values:
return nil
case .NamedValues(let dictionary):
case .namedValues(let dictionary):
return dictionary[name]
}
}
enum Kind {
case Values([DatabaseValueConvertible?])
case NamedValues(Dictionary<String, DatabaseValueConvertible?>)
case values([DatabaseValueConvertible?])
case namedValues(Dictionary<String, DatabaseValueConvertible?>)
}
let kind: Kind
@@ -616,7 +617,7 @@ extension StatementArguments : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch kind {
case .Values(let values):
case .values(let values):
return "["
+ values
.map { value in
@@ -626,10 +627,10 @@ extension StatementArguments : CustomStringConvertible {
return "nil"
}
}
.joinWithSeparator(", ")
.joined(separator: ", ")
+ "]"
case .NamedValues(let namedValues):
case .namedValues(let namedValues):
return "["
+ namedValues.map { (key, value) in
if let value = value {
@@ -638,7 +639,7 @@ extension StatementArguments : CustomStringConvertible {
return "\(key):nil"
}
}
.joinWithSeparator(", ")
.joined(separator: ", ")
+ "]"
}
}
+13 -13
View File
@@ -48,7 +48,7 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
/// Returns a sequence of values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let names = String.fetch(statement) // DatabaseSequence<String>
///
/// The returned sequence can be consumed several times, but it may yield
@@ -68,7 +68,7 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
/// - arguments: Optional statement arguments.
/// - returns: A sequence of values.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
let sqliteStatement = statement.sqliteStatement
return statement.fetchSequence(arguments: arguments) {
guard sqlite3_column_type(sqliteStatement, 0) != SQLITE_NULL else {
@@ -80,7 +80,7 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let names = String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -88,13 +88,13 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
/// - arguments: Optional statement arguments.
/// - returns: An array of values.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
return Array(fetch(statement, arguments: arguments))
}
/// Returns a single value fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let statement = db.makeSelectStatement("SELECT name FROM ...")
/// let name = String.fetchOne(statement) // String?
///
/// - parameters:
@@ -102,14 +102,14 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
/// - arguments: Optional statement arguments.
/// - returns: An optional value.
@warn_unused_result
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
let sqliteStatement = statement.sqliteStatement
let sequence = statement.fetchSequence(arguments: arguments) {
(sqlite3_column_type(sqliteStatement, 0) == SQLITE_NULL) ?
(nil as Self?) :
Self.init(sqliteStatement: sqliteStatement, index: 0)
}
if let value = sequence.generate().next() {
if let value = sequence.makeIterator().next() {
return value
}
return nil
@@ -140,8 +140,8 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
/// - arguments: Optional statement arguments.
/// - returns: A sequence of values.
@warn_unused_result
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
return fetch(try! db.makeSelectStatement(sql), arguments: arguments)
}
/// Returns an array of values fetched from an SQL query.
@@ -154,8 +154,8 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
/// - arguments: Optional statement arguments.
/// - returns: An array of values.
@warn_unused_result
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Self] {
return fetchAll(try! db.makeSelectStatement(sql), arguments: arguments)
}
/// Returns a single value fetched from an SQL query.
@@ -168,7 +168,7 @@ public extension DatabaseValueConvertible where Self: StatementColumnConvertible
/// - arguments: Optional statement arguments.
/// - returns: An optional value.
@warn_unused_result
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments)
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Self? {
return fetchOne(try! db.makeSelectStatement(sql), arguments: arguments)
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ extension CGFloat : DatabaseValueConvertible {
}
/// Returns a CGFloat initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> CGFloat? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> CGFloat? {
guard let double = Double.fromDatabaseValue(databaseValue) else {
return nil
}
@@ -19,14 +19,14 @@ public struct DatabaseCoder: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return NSKeyedArchiver.archivedDataWithRootObject(object).databaseValue
return NSKeyedArchiver.archivedData(withRootObject: object).databaseValue
}
/// Returns a DatabaseCoder if *databaseValue* contains an archived object.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseCoder? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseCoder? {
guard let data = NSData.fromDatabaseValue(databaseValue) else {
return nil
}
return DatabaseCoder(NSKeyedUnarchiver.unarchiveObjectWithData(data))
return DatabaseCoder(NSKeyedUnarchiver.unarchiveObject(with: data))
}
}
@@ -105,12 +105,12 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
timeString = nil
}
return [dateString, timeString].flatMap { $0 }.joinWithSeparator(" ").databaseValue
return [dateString, timeString].flatMap { $0 }.joined(separator: " ").databaseValue
}
/// Returns a DatabaseDateComponents if *databaseValue* contains a
/// valid date.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseDateComponents? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseDateComponents? {
// https://www.sqlite.org/lang_datefunc.html
//
// Supported formats are:
@@ -139,7 +139,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
// YYYY or HH
var initialNumber: Int = 0
if !scanner.scanInteger(&initialNumber) {
if !scanner.scanInt(&initialNumber) {
return nil
}
switch scanner.scanLocation {
@@ -166,44 +166,44 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
}
// -
if !scanner.scanString("-", intoString: nil) {
if !scanner.scanString("-", into: nil) {
return nil
}
// MM
var month: Int = 0
if scanner.scanInteger(&month) && month >= 1 && month <= 12 {
if scanner.scanInt(&month) && month >= 1 && month <= 12 {
dateComponents.month = month
} else {
return nil
}
// -
if !scanner.scanString("-", intoString: nil) {
if !scanner.scanString("-", into: nil) {
return nil
}
// DD
var day: Int = 0
if scanner.scanInteger(&day) && day >= 1 && day <= 31 {
if scanner.scanInt(&day) && day >= 1 && day <= 31 {
dateComponents.day = day
} else {
return nil
}
// YYYY-MM-DD
if scanner.atEnd {
if scanner.isAtEnd {
return DatabaseDateComponents(dateComponents, format: .YMD)
}
// T/space
if !scanner.scanString("T", intoString: nil) && !scanner.scanString(" ", intoString: nil) {
if !scanner.scanString("T", into: nil) && !scanner.scanString(" ", into: nil) {
return nil
}
// HH
var hour: Int = 0
if scanner.scanInteger(&hour) && hour >= 0 && hour <= 23 {
if scanner.scanInt(&hour) && hour >= 0 && hour <= 23 {
dateComponents.hour = hour
} else {
return nil
@@ -214,20 +214,20 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
}
// :
if !scanner.scanString(":", intoString: nil) {
if !scanner.scanString(":", into: nil) {
return nil
}
// MM
var minute: Int = 0
if scanner.scanInteger(&minute) && minute >= 0 && minute <= 59 {
if scanner.scanInt(&minute) && minute >= 0 && minute <= 59 {
dateComponents.minute = minute
} else {
return nil
}
// [YYYY-MM-DD] HH:MM
if scanner.atEnd {
if scanner.isAtEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HM)
} else {
@@ -236,20 +236,20 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
}
// :
if !scanner.scanString(":", intoString: nil) {
if !scanner.scanString(":", into: nil) {
return nil
}
// SS
var second: Int = 0
if scanner.scanInteger(&second) && second >= 0 && second <= 59 {
if scanner.scanInt(&second) && second >= 0 && second <= 59 {
dateComponents.second = second
} else {
return nil
}
// [YYYY-MM-DD] HH:MM:SS
if scanner.atEnd {
if scanner.isAtEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HMS)
} else {
@@ -258,15 +258,15 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
}
// .
if !scanner.scanString(".", intoString: nil) {
if !scanner.scanString(".", into: nil) {
return nil
}
// SSS
var millisecondDigits: NSString? = nil
if scanner.scanCharactersFromSet(NSCharacterSet.decimalDigitCharacterSet(), intoString: &millisecondDigits), var millisecondDigits = millisecondDigits {
if scanner.scanCharacters(from: .decimalDigits(), into: &millisecondDigits), var millisecondDigits = millisecondDigits {
if millisecondDigits.length > 3 {
millisecondDigits = millisecondDigits.substringToIndex(3)
millisecondDigits = NSString(string: millisecondDigits.substring(to: 3))
}
dateComponents.nanosecond = millisecondDigits.integerValue * 1_000_000
} else {
@@ -274,7 +274,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
}
// [YYYY-MM-DD] HH:MM:SS.SSS
if scanner.atEnd {
if scanner.isAtEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HMSS)
} else {
@@ -11,7 +11,7 @@ extension DatabaseValue {
guard let convertible = object as? DatabaseValueConvertible else {
return nil
}
self.init(storage: convertible.databaseValue.storage)
self = convertible.databaseValue
}
/// Converts a DatabaseValue to AnyObject.
@@ -19,15 +19,15 @@ extension DatabaseValue {
/// - returns: NSNull, NSNumber, NSString, or NSData.
public func toAnyObject() -> AnyObject {
switch storage {
case .Null:
case .null:
return NSNull()
case .Int64(let int64):
return NSNumber(longLong: int64)
case .Double(let double):
return NSNumber(double: double)
case .String(let string):
case .int64(let int64):
return NSNumber(value: int64)
case .double(let double):
return NSNumber(value: double)
case .string(let string):
return string as NSString
case .Blob(let data):
case .blob(let data):
return data
}
}
+4 -4
View File
@@ -6,16 +6,16 @@ extension NSData : DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
// SQLite cant' store zero-length blobs.
guard length > 0 else {
return .Null
return .null
}
return DatabaseValue(storage: .Blob(self))
return DatabaseValue(storage: .blob(self))
}
/// Returns an NSData initialized from *databaseValue*, if it contains
/// a Blob.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
switch databaseValue.storage {
case .Blob(let data):
case .blob(let data):
return self.init(data: data)
default:
return nil
+9 -9
View File
@@ -6,21 +6,21 @@ extension NSDate : DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return storageDateFormatter.stringFromDate(self).databaseValue
return storageDateFormatter.string(from: self).databaseValue
}
/// Returns an NSDate initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(databaseValue) {
return fromDatabaseDateComponents(databaseDateComponents)
}
if let julianDayNumber = Double.fromDatabaseValue(databaseValue) {
return fromJulienDayNumber(julianDayNumber)
return fromJulianDayNumber(julianDayNumber)
}
return nil
}
private static func fromJulienDayNumber(julianDayNumber: Double) -> Self? {
private static func fromJulianDayNumber(_ julianDayNumber: Double) -> Self? {
// Conversion uses the same algorithm as SQLite: https://www.sqlite.org/src/artifact/8ec787fed4929d8c
let JD = Int64(julianDayNumber * 86400000)
let Z = Int(((JD + 43200000)/86400000))
@@ -52,17 +52,17 @@ extension NSDate : DatabaseValueConvertible {
dateComponents.second = Int(second)
dateComponents.nanosecond = Int((second - Double(Int(second))) * 1.0e9)
let date = UTCCalendar.dateFromComponents(dateComponents)!
return self.init(timeInterval: 0, sinceDate: date)
let date = UTCCalendar.date(from: dateComponents)!
return self.init(timeInterval: 0, since: date)
}
private static func fromDatabaseDateComponents(databaseDateComponents: DatabaseDateComponents) -> Self? {
private static func fromDatabaseDateComponents(_ databaseDateComponents: DatabaseDateComponents) -> Self? {
guard databaseDateComponents.format.hasYMDComponents else {
// Refuse to turn hours without any date information into NSDate:
return nil
}
let date = UTCCalendar.dateFromComponents(databaseDateComponents.dateComponents)!
return self.init(timeInterval: 0, sinceDate: date)
let date = UTCCalendar.date(from: databaseDateComponents.dateComponents)!
return self.init(timeInterval: 0, since: date)
}
}
+3 -3
View File
@@ -3,13 +3,13 @@ import Foundation
/// NSNull adopts DatabaseValueConvertible
extension NSNull: DatabaseValueConvertible {
/// Returns DatabaseValue.Null.
/// Returns DatabaseValue.null.
public var databaseValue: DatabaseValue {
return .Null
return .null
}
/// Returns nil.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
return nil
}
}
+19 -29
View File
@@ -5,30 +5,20 @@ extension NSNumber: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
switch String.fromCString(objCType)! {
case "c":
return Int64(charValue).databaseValue
case "C":
return Int64(unsignedCharValue).databaseValue
case "s":
return Int64(shortValue).databaseValue
case "S":
return Int64(unsignedShortValue).databaseValue
case "i":
return Int64(intValue).databaseValue
case "I":
return Int64(unsignedIntValue).databaseValue
case "l":
return Int64(longValue).databaseValue
case "L":
return Int64(unsignedLongValue).databaseValue
case "q":
return Int64(longLongValue).databaseValue
case "Q":
return Int64(unsignedLongLongValue).databaseValue
case "f":
return Double(floatValue).databaseValue
case "d":
switch String(cString: objCType) {
case "c",
"C",
"s",
"S",
"i",
"I",
"l",
"L",
"q",
"Q":
return int64Value.databaseValue
case "f",
"d":
return doubleValue.databaseValue
case "B":
return boolValue.databaseValue
@@ -38,12 +28,12 @@ extension NSNumber: DatabaseValueConvertible {
}
/// Returns an NSNumber initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
switch databaseValue.storage {
case .Int64(let int64):
return self.init(longLong: int64)
case .Double(let double):
return self.init(double: double)
case .int64(let int64):
return self.init(value: int64)
case .double(let double):
return self.init(value: double)
default:
return nil
}
+1 -1
View File
@@ -9,7 +9,7 @@ extension NSString: DatabaseValueConvertible {
}
/// Returns an NSString initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
guard let string = String.fromDatabaseValue(databaseValue) else {
return nil
}
+1 -1
View File
@@ -10,7 +10,7 @@ extension NSURL : DatabaseValueConvertible {
}
/// Returns an NSURL initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
guard let string = String.fromDatabaseValue(databaseValue) else {
return nil
}
@@ -31,8 +31,8 @@ extension Row {
public func toNSDictionary() -> NSDictionary {
let dictionary = NSMutableDictionary(capacity: count)
// Reverse so that the result dictionary contains values for the leftmost columns.
for (columnName, databaseValue) in reverse() {
dictionary[columnName] = databaseValue.toAnyObject()
for (columnName, databaseValue) in reversed() {
dictionary[NSString(string: columnName)] = databaseValue.toAnyObject()
}
return dictionary
}
@@ -19,7 +19,7 @@ extension StatementArguments {
//
// This initializer is required for the following code to compile:
//
// let statement = try db.updateStatement("INSERT INTO persons (name, age) VALUES (?, ?)")
// let statement = try db.makeUpdateStatement("INSERT INTO persons (name, age) VALUES (?, ?)")
// let persons = [ // NSArray of NSArray, actually
// ["Arthur", 41],
// ["Barbara", 38],
@@ -56,7 +56,7 @@ extension StatementArguments {
//
// This initializer is required for the following code to compile:
//
// let statement = try db.updateStatement("INSERT INTO persons (name, age) VALUES (:name, :age)")
// let statement = try db.makeUpdateStatement("INSERT INTO persons (name, age) VALUES (:name, :age)")
// let persons = [ // NSArray of NSDictionary, actually
// ["name": "Arthur", "age": 41],
// ["name": "Barbara", "age": 38],
@@ -2,16 +2,16 @@
/// is itself DatabaseValueConvertible:
///
/// enum Color : Int {
/// case Red
/// case White
/// case Rose
/// case red
/// case white
/// case rose
/// }
///
/// // Declare DatabaseValueConvertible adoption:
/// extension Color : DatabaseValueConvertible { }
///
/// // Gain full GRDB.swift support:
/// db.execute("INSERT INTO colors (color) VALUES (?)", [Color.Red])
/// db.execute("INSERT INTO colors (color) VALUES (?)", [Color.red])
/// let color: Color? = Color.fetchOne(db, "SELECT ...")
public extension RawRepresentable where Self: DatabaseValueConvertible, Self.RawValue: DatabaseValueConvertible {
@@ -21,7 +21,7 @@ public extension RawRepresentable where Self: DatabaseValueConvertible, Self.Raw
}
/// Returns a value initialized from *databaseValue*, if possible.
static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
guard let rawValue = RawValue.fromDatabaseValue(databaseValue) else {
return nil
}
@@ -31,7 +31,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns a Bool initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Bool? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Bool? {
// IMPLEMENTATION NOTE
//
// https://www.sqlite.org/lang_expr.html#booleanexpr
@@ -89,9 +89,9 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
// store big numbers as Real.
switch databaseValue.storage {
case .Int64(let int64):
case .int64(let int64):
return (int64 != 0)
case .Double(let double):
case .double(let double):
return (double != 0.0)
default:
return nil
@@ -117,11 +117,11 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns an Int initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Int? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Int? {
switch databaseValue.storage {
case .Int64(let int64):
case .int64(let int64):
return Int(int64)
case .Double(let double):
case .double(let double):
return Int(double)
default:
return nil
@@ -147,11 +147,11 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns an Int32 initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Int32? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Int32? {
switch databaseValue.storage {
case .Int64(let int64):
case .int64(let int64):
return Int32(int64)
case .Double(let double):
case .double(let double):
return Int32(double)
default:
return nil
@@ -173,15 +173,15 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return DatabaseValue(storage: .Int64(self))
return DatabaseValue(storage: .int64(self))
}
/// Returns an Int64 initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Int64? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Int64? {
switch databaseValue.storage {
case .Int64(let int64):
case .int64(let int64):
return int64
case .Double(let double):
case .double(let double):
return Int64(double)
default:
return nil
@@ -203,15 +203,15 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return DatabaseValue(storage: .Double(self))
return DatabaseValue(storage: .double(self))
}
/// Returns a Double initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Double? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Double? {
switch databaseValue.storage {
case .Int64(let int64):
case .int64(let int64):
return Double(int64)
case .Double(let double):
case .double(let double):
return double
default:
return nil
@@ -237,11 +237,11 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns a Float initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Float? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Float? {
switch databaseValue.storage {
case .Int64(let int64):
case .int64(let int64):
return Float(int64)
case .Double(let double):
case .double(let double):
return Float(double)
default:
return nil
@@ -259,18 +259,18 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let cString = UnsafePointer<Int8>(sqlite3_column_text(sqliteStatement, Int32(index)))
self = String.fromCString(cString)!
self = String(cString: cString!)
}
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return DatabaseValue(storage: .String(self))
return DatabaseValue(storage: .string(self))
}
/// Returns a String initialized from *databaseValue*, if possible.
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> String? {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> String? {
switch databaseValue.storage {
case .String(let string):
case .string(let string):
return string
default:
return nil
@@ -282,121 +282,121 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
// MARK: - SQL Functions
extension DatabaseFunction {
/// An SQL function that returns the Swift built-in capitalizedString
/// An SQL function that returns the Swift built-in capitalized
/// String property.
///
/// The function returns NULL for non-strings values.
///
/// This function is automatically added by GRDB to your database
/// connections. It is the function used by the query interface's
/// capitalizedString:
/// capitalized:
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.capitalizedString)
/// let request = Person.select(nameColumn.capitalized)
/// let names = String.fetchAll(dbQueue, request) // [String]
public static let capitalizedString = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { databaseValues in
public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
return nil
}
return string.capitalizedString
return string.capitalized
}
/// An SQL function that returns the Swift built-in lowercaseString
/// An SQL function that returns the Swift built-in lowercased
/// String property.
///
/// The function returns NULL for non-strings values.
///
/// This function is automatically added by GRDB to your database
/// connections. It is the function used by the query interface's
/// lowercaseString:
/// lowercased:
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.lowercaseString)
/// let request = Person.select(nameColumn.lowercased())
/// let names = String.fetchAll(dbQueue, request) // [String]
public static let lowercaseString = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { databaseValues in
public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
return nil
}
return string.lowercaseString
return string.lowercased()
}
/// An SQL function that returns the Swift built-in uppercaseString
/// An SQL function that returns the Swift built-in uppercased
/// String property.
///
/// The function returns NULL for non-strings values.
///
/// This function is automatically added by GRDB to your database
/// connections. It is the function used by the query interface's
/// uppercaseString:
/// uppercased:
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.uppercaseString)
/// let request = Person.select(nameColumn.uppercased())
/// let names = String.fetchAll(dbQueue, request) // [String]
public static let uppercaseString = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { databaseValues in
public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
return nil
}
return string.uppercaseString
return string.uppercased()
}
}
@available(iOS 9.0, OSX 10.11, *)
extension DatabaseFunction {
/// An SQL function that returns the Swift built-in
/// localizedCapitalizedString String property.
/// localizedCapitalized String property.
///
/// The function returns NULL for non-strings values.
///
/// This function is automatically added by GRDB to your database
/// connections. It is the function used by the query interface's
/// localizedCapitalizedString:
/// localizedCapitalized:
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.localizedCapitalizedString)
/// let request = Person.select(nameColumn.localizedCapitalized)
/// let names = String.fetchAll(dbQueue, request) // [String]
public static let localizedCapitalizedString = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { databaseValues in
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
return nil
}
return string.localizedCapitalizedString
return string.localizedCapitalized
}
/// An SQL function that returns the Swift built-in
/// localizedLowercaseString String property.
/// localizedLowercased String property.
///
/// The function returns NULL for non-strings values.
///
/// This function is automatically added by GRDB to your database
/// connections. It is the function used by the query interface's
/// localizedLowercaseString:
/// localizedLowercased:
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.localizedLowercaseString)
/// let request = Person.select(nameColumn.localizedLowercased)
/// let names = String.fetchAll(dbQueue, request) // [String]
public static let localizedLowercaseString = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { databaseValues in
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
return nil
}
return string.localizedLowercaseString
return string.localizedLowercase
}
/// An SQL function that returns the Swift built-in
/// localizedUppercaseString String property.
/// localizedUppercased String property.
///
/// The function returns NULL for non-strings values.
///
/// This function is automatically added by GRDB to your database
/// connections. It is the function used by the query interface's
/// localizedUppercaseString:
/// localizedUppercased:
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.localizedUppercaseString)
/// let request = Person.select(nameColumn.localizedUppercased)
/// let names = String.fetchAll(dbQueue, request) // [String]
public static let localizedUppercaseString = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { databaseValues in
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { databaseValues in
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
return nil
}
return string.localizedUppercaseString
return string.localizedUppercase
}
}
@@ -430,7 +430,7 @@ extension DatabaseCollation {
/// ")"
/// )
public static let unicodeCompare = DatabaseCollation("swiftCompare") { (lhs, rhs) in
return (lhs < rhs) ? .OrderedAscending : ((lhs == rhs) ? .OrderedSame : .OrderedDescending)
return (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending)
}
/// A collation, or SQL string comparison function, that compares strings
+33 -29
View File
@@ -29,21 +29,21 @@ extension String {
/// Return as many question marks separated with commas as the *count* argument.
///
/// databaseQuestionMarks(count: 3) // "?,?,?"
public func databaseQuestionMarks(count count: Int) -> String {
return Array(count: count, repeatedValue: "?").joinWithSeparator(",")
public func databaseQuestionMarks(count: Int) -> String {
return Array(repeating: "?", count: count).joined(separator: ",")
}
// MARK: - Internal
let SQLITE_TRANSIENT = unsafeBitCast(COpaquePointer(bitPattern: -1), sqlite3_destructor_type.self)
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
/// Custom precondition function which aims at solving
/// https://bugs.swift.org/browse/SR-905 and
/// https://github.com/groue/GRDB.swift/issues/37
///
/// TODO: remove this function when https://bugs.swift.org/browse/SR-905 is solved.
func GRDBPrecondition(@autoclosure condition: () -> Bool, @autoclosure _ message: () -> String = "", file: StaticString = #file, line: UInt = #line) {
func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) {
if !condition() {
fatalError(message, file: file, line: line)
}
@@ -51,10 +51,10 @@ func GRDBPrecondition(@autoclosure condition: () -> Bool, @autoclosure _ message
/// A function declared as rethrows that synchronously executes a throwing
/// block in a dispatch_queue.
func dispatchSync<T>(queue: dispatch_queue_t, _ block: () throws -> T) rethrows -> T {
func impl(queue: dispatch_queue_t, block: () throws -> T, onError: (ErrorType) throws -> ()) rethrows -> T {
func dispatchSync<T>(_ queue: dispatch_queue_t, _ block: () throws -> T) rethrows -> T {
func impl(_ queue: dispatch_queue_t, block: () throws -> T, onError: (ErrorProtocol) throws -> ()) rethrows -> T {
var result: T? = nil
var blockError: ErrorType? = nil
var blockError: ErrorProtocol? = nil
dispatch_sync(queue) {
do {
result = try block()
@@ -72,9 +72,9 @@ func dispatchSync<T>(queue: dispatch_queue_t, _ block: () throws -> T) rethrows
extension Array {
/// Removes the first object that matches *predicate*.
mutating func removeFirst(@noescape predicate: (Element) throws -> Bool) rethrows {
if let index = try indexOf(predicate) {
removeAtIndex(index)
mutating func removeFirst(_ predicate: @noescape(Element) throws -> Bool) rethrows {
if let index = try index(where: predicate) {
remove(at: index)
}
}
}
@@ -82,38 +82,42 @@ extension Array {
extension Dictionary {
/// Create a dictionary with the keys and values in the given sequence.
init<Sequence: SequenceType where Sequence.Generator.Element == Generator.Element>(keyValueSequence: Sequence) {
self.init(minimumCapacity: keyValueSequence.underestimateCount())
init<Sequence: Swift.Sequence where Sequence.Iterator.Element == (Key, Value)>(keyValueSequence: Sequence) {
// TODO: restore use of underestimateCount when Swift is fixed
// self.init(minimumCapacity: keyValueSequence.underestimateCount())
self.init()
for (key, value) in keyValueSequence {
self[key] = value
}
}
/// Create a dictionary from keys and a value builder.
init<Sequence: SequenceType where Sequence.Generator.Element == Key>(keys: Sequence, value: Key -> Value) {
self.init(minimumCapacity: keys.underestimateCount())
init<Sequence: Swift.Sequence where Sequence.Iterator.Element == Key>(keys: Sequence, value: (Key) -> Value) {
// TODO: restore use of underestimateCount when Swift is fixed
// self.init(minimumCapacity: keys.underestimateCount())
self.init()
for key in keys {
self[key] = value(key)
}
}
}
extension SequenceType where Generator.Element: Equatable {
extension Sequence where Iterator.Element: Equatable {
/// Filter out elements contained in *removedElements*.
func removingElementsOf<S : SequenceType where S.Generator.Element == Self.Generator.Element>(removedElements: S) -> [Self.Generator.Element] {
return filter { element in !removedElements.contains(element) }
func removing<S : Sequence where S.Iterator.Element == Self.Iterator.Element>(contentsOf elements: S) -> [Self.Iterator.Element] {
return filter { element in !elements.contains(element) }
}
}
extension SequenceType {
extension Sequence {
/// Return true if one element matches the predicate
func any(predicate: (Generator.Element -> Bool)) -> Bool {
func any(_ predicate: (Iterator.Element) -> Bool) -> Bool {
for element in self where predicate(element) { return true }
return false
}
func all(predicate: (Generator.Element -> Bool)) -> Bool {
func all(_ predicate: (Iterator.Element) -> Bool) -> Bool {
for element in self where !predicate(element) { return false }
return true
}
@@ -131,7 +135,7 @@ final class ReadWriteBox<T> {
self.queue = dispatch_queue_create("GRDB.ReadWriteBox", DISPATCH_QUEUE_CONCURRENT)
}
func read<U>(block: (T) -> U) -> U {
func read<U>(_ block: (T) -> U) -> U {
var result: U? = nil
dispatch_sync(queue) {
result = block(self._value)
@@ -139,7 +143,7 @@ final class ReadWriteBox<T> {
return result!
}
func write(block: (inout T) -> Void) {
func write(_ block: (inout T) -> Void) {
dispatch_barrier_sync(queue) {
block(&self._value)
}
@@ -195,7 +199,7 @@ final class Pool<T> {
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
self.queue = dispatch_queue_create("GRDB.Pool", nil)
self.semaphore = dispatch_semaphore_create(maximumCount)
self.semaphore = dispatch_semaphore_create(maximumCount)!
}
/// Returns a tuple (element, releaseElement())
@@ -207,7 +211,7 @@ final class Pool<T> {
/// Performs a synchronous block with an element. The element turns
/// available after the block has executed.
func get<U>(@noescape block: (T) throws -> U) rethrows -> U {
func get<U>(block: @noescape(T) throws -> U) rethrows -> U {
let (element, release) = get()
defer { release() }
return try block(element)
@@ -215,10 +219,10 @@ final class Pool<T> {
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary queue.
func forEach(block: (T) throws -> ()) rethrows {
func forEach(_ body: (T) throws -> ()) rethrows {
try dispatchSync(queue) {
for item in self.items {
try block(item.element)
try body(item.element)
}
}
}
@@ -230,7 +234,7 @@ final class Pool<T> {
/// Empty the pool. Currently used items won't be reused.
/// Eventual block is executed before any other element is dequeued.
func clear(block: () throws -> ()) rethrows {
func clear(_ block: () throws -> ()) rethrows {
try dispatchSync(queue) {
self.items = []
try block()
@@ -241,7 +245,7 @@ final class Pool<T> {
var item: PoolItem<T>! = nil
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
dispatch_sync(queue) {
if let index = self.items.indexOf({ $0.available }) {
if let index = self.items.index(where: { $0.available }) {
item = self.items[index]
item.available = false
} else {
@@ -252,7 +256,7 @@ final class Pool<T> {
return item
}
private func unlockItem(item: PoolItem<T>) {
private func unlockItem(_ item: PoolItem<T>) {
dispatch_sync(queue) {
item.available = true
}
+22 -22
View File
@@ -5,10 +5,10 @@
/// as well, and define a way to fetch values, rows, and records.
public protocol FetchRequest {
/// A prepared statement that is ready to be executed.
func selectStatement(db: Database) throws -> SelectStatement
func selectStatement(_ db: Database) throws -> SelectStatement
/// An eventual RowAdapter
func adapter(statement: SelectStatement) throws -> RowAdapter?
func adapter(_ statement: SelectStatement) throws -> RowAdapter?
}
@@ -26,15 +26,15 @@ struct SQLFetchRequest {
extension SQLFetchRequest : FetchRequest {
func selectStatement(db: Database) throws -> SelectStatement {
let statement = try db.selectStatement(sql)
func selectStatement(_ db: Database) throws -> SelectStatement {
let statement = try db.makeSelectStatement(sql)
if let arguments = arguments {
try statement.setArgumentsWithValidation(arguments)
}
return statement
}
func adapter(statement: SelectStatement) throws -> RowAdapter? {
func adapter(_ statement: SelectStatement) throws -> RowAdapter? {
return adapter
}
}
@@ -62,7 +62,7 @@ extension DatabaseValueConvertible {
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public static func fetch(db: Database, _ request: FetchRequest) -> DatabaseSequence<Self> {
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Self> {
return try! fetch(request.selectStatement(db))
}
@@ -74,7 +74,7 @@ extension DatabaseValueConvertible {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchAll(db: Database, _ request: FetchRequest) -> [Self] {
public static func fetchAll(_ db: Database, _ request: FetchRequest) -> [Self] {
return try! fetchAll(request.selectStatement(db))
}
@@ -89,7 +89,7 @@ extension DatabaseValueConvertible {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchOne(db: Database, _ request: FetchRequest) -> Self? {
public static func fetchOne(_ db: Database, _ request: FetchRequest) -> Self? {
return try! fetchOne(request.selectStatement(db))
}
}
@@ -117,7 +117,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public static func fetch(db: Database, _ request: FetchRequest) -> DatabaseSequence<Wrapped?> {
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Wrapped?> {
return try! fetch(request.selectStatement(db))
}
@@ -129,7 +129,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchAll(db: Database, _ request: FetchRequest) -> [Wrapped?] {
public static func fetchAll(_ db: Database, _ request: FetchRequest) -> [Wrapped?] {
return try! fetchAll(request.selectStatement(db))
}
}
@@ -157,7 +157,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public static func fetch(db: Database, _ request: FetchRequest) -> DatabaseSequence<Self> {
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Self> {
return try! fetch(request.selectStatement(db))
}
@@ -169,7 +169,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchAll(db: Database, _ request: FetchRequest) -> [Self] {
public static func fetchAll(_ db: Database, _ request: FetchRequest) -> [Self] {
return try! fetchAll(request.selectStatement(db))
}
@@ -184,7 +184,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchOne(db: Database, _ request: FetchRequest) -> Self? {
public static func fetchOne(_ db: Database, _ request: FetchRequest) -> Self? {
return try! fetchOne(request.selectStatement(db))
}
}
@@ -212,7 +212,7 @@ extension RowConvertible {
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public static func fetch(db: Database, _ request: FetchRequest) -> DatabaseSequence<Self> {
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Self> {
let statement = try! request.selectStatement(db)
let adapter = try! request.adapter(statement)
return fetch(statement, adapter: adapter)
@@ -226,7 +226,7 @@ extension RowConvertible {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchAll(db: Database, _ request: FetchRequest) -> [Self] {
public static func fetchAll(_ db: Database, _ request: FetchRequest) -> [Self] {
let statement = try! request.selectStatement(db)
let adapter = try! request.adapter(statement)
return fetchAll(statement, adapter: adapter)
@@ -240,7 +240,7 @@ extension RowConvertible {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchOne(db: Database, _ request: FetchRequest) -> Self? {
public static func fetchOne(_ db: Database, _ request: FetchRequest) -> Self? {
let statement = try! request.selectStatement(db)
let adapter = try! request.adapter(statement)
return fetchOne(statement, adapter: adapter)
@@ -268,7 +268,7 @@ extension RowConvertible where Self: TableMapping {
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public static func fetch(db: Database) -> DatabaseSequence<Self> {
public static func fetch(_ db: Database) -> DatabaseSequence<Self> {
return all().fetch(db)
}
@@ -278,7 +278,7 @@ extension RowConvertible where Self: TableMapping {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchAll(db: Database) -> [Self] {
public static func fetchAll(_ db: Database) -> [Self] {
return all().fetchAll(db)
}
@@ -288,7 +288,7 @@ extension RowConvertible where Self: TableMapping {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchOne(db: Database) -> Self? {
public static func fetchOne(_ db: Database) -> Self? {
return all().fetchOne(db)
}
}
@@ -328,7 +328,7 @@ extension Row {
/// If the database is modified while the sequence is iterating, the
/// remaining elements of the sequence are undefined.
@warn_unused_result
public static func fetch(db: Database, _ request: FetchRequest) -> DatabaseSequence<Row> {
public static func fetch(_ db: Database, _ request: FetchRequest) -> DatabaseSequence<Row> {
let statement = try! request.selectStatement(db)
let adapter = try! request.adapter(statement)
return fetch(statement, adapter: adapter)
@@ -343,7 +343,7 @@ extension Row {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchAll(db: Database, _ request: FetchRequest) -> [Row] {
public static func fetchAll(_ db: Database, _ request: FetchRequest) -> [Row] {
let statement = try! request.selectStatement(db)
let adapter = try! request.adapter(statement)
return fetchAll(statement, adapter: adapter)
@@ -358,7 +358,7 @@ extension Row {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchOne(db: Database, _ request: FetchRequest) -> Row? {
public static func fetchOne(_ db: Database, _ request: FetchRequest) -> Row? {
let statement = try! request.selectStatement(db)
let adapter = try! request.adapter(statement)
return fetchOne(statement, adapter: adapter)
+57 -54
View File
@@ -8,7 +8,7 @@ public struct QueryInterfaceRequest<T> {
///
/// It represents the SQL query `SELECT * FROM tableName`.
public init(tableName: String) {
self.init(query: _SQLSelectQuery(select: [_SQLResultColumn.Star(nil)], from: .Table(name: tableName, alias: nil)))
self.init(query: _SQLSelectQuery(select: [_SQLResultColumn.star(nil)], from: .table(name: tableName, alias: nil)))
}
init(query: _SQLSelectQuery) {
@@ -23,17 +23,17 @@ extension QueryInterfaceRequest : FetchRequest {
///
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
@warn_unused_result
public func selectStatement(database: Database) throws -> SelectStatement {
public func selectStatement(_ db: Database) throws -> SelectStatement {
// TODO: split statement generation from arguments building
var bindings: [DatabaseValueConvertible?] = []
let sql = try query.sql(database, &bindings)
let statement = try database.selectStatement(sql)
let sql = try query.sql(db, &bindings)
let statement = try db.makeSelectStatement(sql)
try statement.setArgumentsWithValidation(StatementArguments(bindings))
return statement
}
/// This method is part of the FetchRequest adoption; returns nil
public func adapter(statement: SelectStatement) throws -> RowAdapter? {
public func adapter(_ statement: SelectStatement) throws -> RowAdapter? {
return nil
}
}
@@ -61,7 +61,7 @@ extension QueryInterfaceRequest where T: RowConvertible {
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public func fetch(db: Database) -> DatabaseSequence<T> {
public func fetch(_ db: Database) -> DatabaseSequence<T> {
return try! T.fetch(selectStatement(db))
}
@@ -73,7 +73,7 @@ extension QueryInterfaceRequest where T: RowConvertible {
///
/// - parameter db: A database connection.
@warn_unused_result
public func fetchAll(db: Database) -> [T] {
public func fetchAll(_ db: Database) -> [T] {
return Array(fetch(db))
}
@@ -85,8 +85,8 @@ extension QueryInterfaceRequest where T: RowConvertible {
///
/// - parameter db: A database connection.
@warn_unused_result
public func fetchOne(db: Database) -> T? {
return fetch(db).generate().next()
public func fetchOne(_ db: Database) -> T? {
return fetch(db).makeIterator().next()
}
}
@@ -97,13 +97,13 @@ extension QueryInterfaceRequest {
/// Returns a new QueryInterfaceRequest with a new net of selected columns.
@warn_unused_result
public func select(selection: _SQLSelectable...) -> QueryInterfaceRequest<T> {
public func select(_ selection: _SQLSelectable...) -> QueryInterfaceRequest<T> {
return select(selection)
}
/// Returns a new QueryInterfaceRequest with a new net of selected columns.
@warn_unused_result
public func select(selection: [_SQLSelectable]) -> QueryInterfaceRequest<T> {
public func select(_ selection: [_SQLSelectable]) -> QueryInterfaceRequest<T> {
var query = self.query
query.selection = selection
return QueryInterfaceRequest(query: query)
@@ -111,24 +111,25 @@ extension QueryInterfaceRequest {
/// Returns a new QueryInterfaceRequest with a new net of selected columns.
@warn_unused_result
public func select(sql sql: String) -> QueryInterfaceRequest<T> {
public func select(sql: String) -> QueryInterfaceRequest<T> {
return select(_SQLLiteral(sql))
}
/// Returns a new QueryInterfaceRequest which returns distinct rows.
public var distinct: QueryInterfaceRequest<T> {
@warn_unused_result
public func distinct() -> QueryInterfaceRequest<T> {
var query = self.query
query.distinct = true
query.isDistinct = true
return QueryInterfaceRequest(query: query)
}
/// Returns a new QueryInterfaceRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
@warn_unused_result
public func filter(predicate: _SQLExpressionType) -> QueryInterfaceRequest<T> {
public func filter(_ predicate: _SQLExpressible) -> QueryInterfaceRequest<T> {
var query = self.query
if let whereExpression = query.whereExpression {
query.whereExpression = .InfixOperator("AND", whereExpression, predicate.sqlExpression)
query.whereExpression = .infixOperator("AND", whereExpression, predicate.sqlExpression)
} else {
query.whereExpression = predicate.sqlExpression
}
@@ -138,19 +139,19 @@ extension QueryInterfaceRequest {
/// Returns a new QueryInterfaceRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
@warn_unused_result
public func filter(sql sql: String) -> QueryInterfaceRequest<T> {
public func filter(sql: String) -> QueryInterfaceRequest<T> {
return filter(_SQLLiteral(sql))
}
/// Returns a new QueryInterfaceRequest grouped according to *expressions*.
@warn_unused_result
public func group(expressions: _SQLExpressionType...) -> QueryInterfaceRequest<T> {
public func group(_ expressions: _SQLExpressible...) -> QueryInterfaceRequest<T> {
return group(expressions)
}
/// Returns a new QueryInterfaceRequest grouped according to *expressions*.
@warn_unused_result
public func group(expressions: [_SQLExpressionType]) -> QueryInterfaceRequest<T> {
public func group(_ expressions: [_SQLExpressible]) -> QueryInterfaceRequest<T> {
var query = self.query
query.groupByExpressions = expressions.map { $0.sqlExpression }
return QueryInterfaceRequest(query: query)
@@ -158,14 +159,14 @@ extension QueryInterfaceRequest {
/// Returns a new QueryInterfaceRequest with a new grouping.
@warn_unused_result
public func group(sql sql: String) -> QueryInterfaceRequest<T> {
public func group(sql: String) -> QueryInterfaceRequest<T> {
return group(_SQLLiteral(sql))
}
/// Returns a new QueryInterfaceRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
@warn_unused_result
public func having(predicate: _SQLExpressionType) -> QueryInterfaceRequest<T> {
public func having(_ predicate: _SQLExpressible) -> QueryInterfaceRequest<T> {
var query = self.query
if let havingExpression = query.havingExpression {
query.havingExpression = (havingExpression && predicate).sqlExpression
@@ -178,45 +179,45 @@ extension QueryInterfaceRequest {
/// Returns a new QueryInterfaceRequest with the provided *sql* added to
/// the eventual set of already applied predicates.
@warn_unused_result
public func having(sql sql: String) -> QueryInterfaceRequest<T> {
public func having(sql: String) -> QueryInterfaceRequest<T> {
return having(_SQLLiteral(sql))
}
/// Returns a new QueryInterfaceRequest with the provided *sortDescriptors* added to
/// the eventual set of already applied sort descriptors.
/// Returns a new QueryInterfaceRequest with the provided *orderings* added to
/// the eventual set of already applied orderings.
@warn_unused_result
public func order(sortDescriptors: _SQLSortDescriptorType...) -> QueryInterfaceRequest<T> {
return order(sortDescriptors)
public func order(_ orderings: _SQLOrdering...) -> QueryInterfaceRequest<T> {
return order(orderings)
}
/// Returns a new QueryInterfaceRequest with the provided *sortDescriptors* added to
/// the eventual set of already applied sort descriptors.
/// Returns a new QueryInterfaceRequest with the provided *orderings* added to
/// the eventual set of already applied orderings.
@warn_unused_result
public func order(sortDescriptors: [_SQLSortDescriptorType]) -> QueryInterfaceRequest<T> {
public func order(_ orderings: [_SQLOrdering]) -> QueryInterfaceRequest<T> {
var query = self.query
query.sortDescriptors.appendContentsOf(sortDescriptors)
query.orderings.append(contentsOf: orderings)
return QueryInterfaceRequest(query: query)
}
/// Returns a new QueryInterfaceRequest with the provided *sql* added to the
/// eventual set of already applied sort descriptors.
/// eventual set of already applied orderings.
@warn_unused_result
public func order(sql sql: String) -> QueryInterfaceRequest<T> {
public func order(sql: String) -> QueryInterfaceRequest<T> {
return order([_SQLLiteral(sql)])
}
/// Returns a new QueryInterfaceRequest sorted in reversed order.
@warn_unused_result
public func reverse() -> QueryInterfaceRequest<T> {
public func reversed() -> QueryInterfaceRequest<T> {
var query = self.query
query.reversed = !query.reversed
query.isReversed = !query.isReversed
return QueryInterfaceRequest(query: query)
}
/// Returns a QueryInterfaceRequest which fetches *limit* rows, starting at
/// *offset*.
@warn_unused_result
public func limit(limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<T> {
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<T> {
var query = self.query
query.limit = _SQLLimit(limit: limit, offset: offset)
return QueryInterfaceRequest(query: query)
@@ -232,7 +233,7 @@ extension QueryInterfaceRequest {
///
/// - parameter db: A database connection.
@warn_unused_result
public func fetchCount(db: Database) -> Int {
public func fetchCount(_ db: Database) -> Int {
return Int.fetchOne(db, QueryInterfaceRequest(query: query.countQuery))!
}
}
@@ -244,14 +245,16 @@ extension QueryInterfaceRequest {
/// Returns an SQL expression that checks the inclusion of a value in
/// the results of another request.
public func contains(element: _SQLExpressionType) -> _SQLExpression {
return .InSubQuery(query, element.sqlExpression)
@warn_unused_result
public func contains(_ element: _SQLExpressible) -> _SQLExpression {
return .inSubQuery(query, element.sqlExpression)
}
/// Returns an SQL expression that checks whether the receiver, as a
/// subquery, returns any row.
public var exists: _SQLExpression {
return .Exists(query)
@warn_unused_result
public func exists() -> _SQLExpression {
return .exists(query)
}
}
@@ -268,58 +271,58 @@ extension TableMapping {
/// Returns a QueryInterfaceRequest which selects *selection*.
@warn_unused_result
public static func select(selection: _SQLSelectable...) -> QueryInterfaceRequest<Self> {
public static func select(_ selection: _SQLSelectable...) -> QueryInterfaceRequest<Self> {
return all().select(selection)
}
/// Returns a QueryInterfaceRequest which selects *selection*.
@warn_unused_result
public static func select(selection: [_SQLSelectable]) -> QueryInterfaceRequest<Self> {
public static func select(_ selection: [_SQLSelectable]) -> QueryInterfaceRequest<Self> {
return all().select(selection)
}
/// Returns a QueryInterfaceRequest which selects *sql*.
@warn_unused_result
public static func select(sql sql: String) -> QueryInterfaceRequest<Self> {
public static func select(sql: String) -> QueryInterfaceRequest<Self> {
return all().select(sql: sql)
}
/// Returns a QueryInterfaceRequest with the provided *predicate*.
@warn_unused_result
public static func filter(predicate: _SQLExpressionType) -> QueryInterfaceRequest<Self> {
public static func filter(_ predicate: _SQLExpressible) -> QueryInterfaceRequest<Self> {
return all().filter(predicate)
}
/// Returns a QueryInterfaceRequest with the provided *predicate*.
@warn_unused_result
public static func filter(sql sql: String) -> QueryInterfaceRequest<Self> {
public static func filter(sql: String) -> QueryInterfaceRequest<Self> {
return all().filter(sql: sql)
}
/// Returns a QueryInterfaceRequest sorted according to the
/// provided *sortDescriptors*.
/// provided *orderings*.
@warn_unused_result
public static func order(sortDescriptors: _SQLSortDescriptorType...) -> QueryInterfaceRequest<Self> {
return all().order(sortDescriptors)
public static func order(_ orderings: _SQLOrdering...) -> QueryInterfaceRequest<Self> {
return all().order(orderings)
}
/// Returns a QueryInterfaceRequest sorted according to the
/// provided *sortDescriptors*.
/// provided *orderings*.
@warn_unused_result
public static func order(sortDescriptors: [_SQLSortDescriptorType]) -> QueryInterfaceRequest<Self> {
return all().order(sortDescriptors)
public static func order(_ orderings: [_SQLOrdering]) -> QueryInterfaceRequest<Self> {
return all().order(orderings)
}
/// Returns a QueryInterfaceRequest sorted according to *sql*.
@warn_unused_result
public static func order(sql sql: String) -> QueryInterfaceRequest<Self> {
public static func order(sql: String) -> QueryInterfaceRequest<Self> {
return all().order(sql: sql)
}
/// Returns a QueryInterfaceRequest which fetches *limit* rows, starting at
/// *offset*.
@warn_unused_result
public static func limit(limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<Self> {
public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<Self> {
return all().limit(limit, offset: offset)
}
}
@@ -333,7 +336,7 @@ extension TableMapping {
///
/// - parameter db: A database connection.
@warn_unused_result
public static func fetchCount(db: Database) -> Int {
public static func fetchCount(_ db: Database) -> Int {
return all().fetchCount(db)
}
}
+56 -56
View File
@@ -7,57 +7,57 @@ public struct _SQLCollatedExpression {
let collationName: String
}
extension _SQLCollatedExpression : _SQLExpressionType {
extension _SQLCollatedExpression : _SQLExpressible {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var sqlExpression: _SQLExpression {
return .Collate(baseExpression, collationName)
return .collate(baseExpression, collationName)
}
}
extension _SQLCollatedExpression : _SQLSortDescriptorType {
extension _SQLCollatedExpression : _SQLOrdering {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var reversedSortDescriptor: _SQLSortDescriptor {
return .Desc(sqlExpression)
public var reversedOrdering: _SQLOrderingExpression {
return .desc(sqlExpression)
}
/// Returns a value that can be used as an argument to FetchRequest.order()
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var asc: _SQLSortDescriptor {
return .Asc(sqlExpression)
public var asc: _SQLOrderingExpression {
return .asc(sqlExpression)
}
/// Returns a value that can be used as an argument to FetchRequest.order()
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var desc: _SQLSortDescriptor {
return .Desc(sqlExpression)
public var desc: _SQLOrderingExpression {
return .desc(sqlExpression)
}
/// This method is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public func orderingSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
public func orderingSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
return try sqlExpression.orderingSQL(db, &bindings)
}
}
extension _SQLDerivedExpressionType {
extension _SpecificSQLExpressible {
/// This method is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public func collating(collationName: String) -> _SQLCollatedExpression {
public func collating(_ collationName: String) -> _SQLCollatedExpression {
return _SQLCollatedExpression(baseExpression: sqlExpression, collationName: collationName)
}
@@ -65,7 +65,7 @@ extension _SQLDerivedExpressionType {
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public func collating(collation: DatabaseCollation) -> _SQLCollatedExpression {
public func collating(_ collation: DatabaseCollation) -> _SQLCollatedExpression {
return collating(collation.name)
}
}
@@ -76,15 +76,15 @@ extension _SQLDerivedExpressionType {
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _SQLCollatedExpression, rhs: _SQLExpressionType?) -> _SQLExpression {
return .Collate(lhs.baseExpression == rhs, lhs.collationName)
public func == (lhs: _SQLCollatedExpression, rhs: _SQLExpressible?) -> _SQLExpression {
return .collate(lhs.baseExpression == rhs, lhs.collationName)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _SQLExpressionType?, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(lhs == rhs.baseExpression, rhs.collationName)
public func == (lhs: _SQLExpressible?, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .collate(lhs == rhs.baseExpression, rhs.collationName)
}
@@ -93,15 +93,15 @@ public func == (lhs: _SQLExpressionType?, rhs: _SQLCollatedExpression) -> _SQLEx
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _SQLCollatedExpression, rhs: _SQLExpressionType?) -> _SQLExpression {
return .Collate(lhs.baseExpression != rhs, lhs.collationName)
public func != (lhs: _SQLCollatedExpression, rhs: _SQLExpressible?) -> _SQLExpression {
return .collate(lhs.baseExpression != rhs, lhs.collationName)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _SQLExpressionType?, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(lhs != rhs.baseExpression, rhs.collationName)
public func != (lhs: _SQLExpressible?, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .collate(lhs != rhs.baseExpression, rhs.collationName)
}
@@ -110,15 +110,15 @@ public func != (lhs: _SQLExpressionType?, rhs: _SQLCollatedExpression) -> _SQLEx
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _SQLCollatedExpression, rhs: _SQLExpressionType) -> _SQLExpression {
return .Collate(lhs.baseExpression < rhs, lhs.collationName)
public func < (lhs: _SQLCollatedExpression, rhs: _SQLExpressible) -> _SQLExpression {
return .collate(lhs.baseExpression < rhs, lhs.collationName)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _SQLExpressionType, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(lhs < rhs.baseExpression, rhs.collationName)
public func < (lhs: _SQLExpressible, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .collate(lhs < rhs.baseExpression, rhs.collationName)
}
@@ -127,15 +127,15 @@ public func < (lhs: _SQLExpressionType, rhs: _SQLCollatedExpression) -> _SQLExpr
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _SQLCollatedExpression, rhs: _SQLExpressionType) -> _SQLExpression {
return .Collate(lhs.baseExpression <= rhs, lhs.collationName)
public func <= (lhs: _SQLCollatedExpression, rhs: _SQLExpressible) -> _SQLExpression {
return .collate(lhs.baseExpression <= rhs, lhs.collationName)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _SQLExpressionType, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(lhs <= rhs.baseExpression, rhs.collationName)
public func <= (lhs: _SQLExpressible, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .collate(lhs <= rhs.baseExpression, rhs.collationName)
}
@@ -144,15 +144,15 @@ public func <= (lhs: _SQLExpressionType, rhs: _SQLCollatedExpression) -> _SQLExp
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _SQLCollatedExpression, rhs: _SQLExpressionType) -> _SQLExpression {
return .Collate(lhs.baseExpression > rhs, lhs.collationName)
public func > (lhs: _SQLCollatedExpression, rhs: _SQLExpressible) -> _SQLExpression {
return .collate(lhs.baseExpression > rhs, lhs.collationName)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _SQLExpressionType, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(lhs > rhs.baseExpression, rhs.collationName)
public func > (lhs: _SQLExpressible, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .collate(lhs > rhs.baseExpression, rhs.collationName)
}
@@ -161,50 +161,50 @@ public func > (lhs: _SQLExpressionType, rhs: _SQLCollatedExpression) -> _SQLExpr
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _SQLCollatedExpression, rhs: _SQLExpressionType) -> _SQLExpression {
return .Collate(lhs.baseExpression >= rhs, lhs.collationName)
public func >= (lhs: _SQLCollatedExpression, rhs: _SQLExpressible) -> _SQLExpression {
return .collate(lhs.baseExpression >= rhs, lhs.collationName)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _SQLExpressionType, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(lhs >= rhs.baseExpression, rhs.collationName)
public func >= (lhs: _SQLExpressible, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .collate(lhs >= rhs.baseExpression, rhs.collationName)
}
// MARK: - Operator BETWEEN COLLATE
extension ClosedInterval where Bound: _SQLExpressionType {
extension Range where Bound: _SQLExpressible {
/// Returns an SQL expression that compares the inclusion of a value in
/// an interval.
/// a range.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(contains(element.baseExpression), element.collationName)
public func contains(_ element: _SQLCollatedExpression) -> _SQLExpression {
return (element >= lowerBound) && (element < upperBound)
}
}
extension HalfOpenInterval where Bound: _SQLExpressionType {
extension ClosedRange where Bound: _SQLExpressible {
/// Returns an SQL expression that compares the inclusion of a value in
/// an interval.
/// a range.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _SQLCollatedExpression) -> _SQLExpression {
return (element >= start) && (element < end)
public func contains(_ element: _SQLCollatedExpression) -> _SQLExpression {
return .collate(contains(element.baseExpression), element.collationName)
}
}
// MARK: - Operator IN COLLATE
extension SequenceType where Self.Generator.Element: _SQLExpressionType {
extension Sequence where Self.Iterator.Element: _SQLExpressible {
/// Returns an SQL expression that compares the inclusion of a value in
/// a sequence.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(contains(element.baseExpression), element.collationName)
public func contains(_ element: _SQLCollatedExpression) -> _SQLExpression {
return .collate(contains(element.baseExpression), element.collationName)
}
}
@@ -214,15 +214,15 @@ extension SequenceType where Self.Generator.Element: _SQLExpressionType {
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _SQLCollatedExpression, rhs: _SQLExpressionType?) -> _SQLExpression {
return .Collate(lhs.baseExpression === rhs, lhs.collationName)
public func === (lhs: _SQLCollatedExpression, rhs: _SQLExpressible?) -> _SQLExpression {
return .collate(lhs.baseExpression === rhs, lhs.collationName)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _SQLExpressionType?, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(lhs == rhs.baseExpression, rhs.collationName)
public func === (lhs: _SQLExpressible?, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .collate(lhs == rhs.baseExpression, rhs.collationName)
}
@@ -231,13 +231,13 @@ public func === (lhs: _SQLExpressionType?, rhs: _SQLCollatedExpression) -> _SQLE
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _SQLCollatedExpression, rhs: _SQLExpressionType?) -> _SQLExpression {
return .Collate(lhs.baseExpression !== rhs, lhs.collationName)
public func !== (lhs: _SQLCollatedExpression, rhs: _SQLExpressible?) -> _SQLExpression {
return .collate(lhs.baseExpression !== rhs, lhs.collationName)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _SQLExpressionType?, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .Collate(lhs !== rhs.baseExpression, rhs.collationName)
public func !== (lhs: _SQLExpressible?, rhs: _SQLCollatedExpression) -> _SQLExpression {
return .collate(lhs !== rhs.baseExpression, rhs.collationName)
}
+46 -46
View File
@@ -4,8 +4,8 @@ extension DatabaseFunction {
/// Returns an SQL expression that applies the function.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func apply(arguments: _SQLExpressionType...) -> _SQLExpression {
return .Function(name, arguments.map { $0.sqlExpression })
public func apply(_ arguments: _SQLExpressible...) -> _SQLExpression {
return .function(name, arguments.map { $0.sqlExpression })
}
}
@@ -15,8 +15,8 @@ extension DatabaseFunction {
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func abs(value: _SQLDerivedExpressionType) -> _SQLExpression {
return .Function("ABS", [value.sqlExpression])
public func abs(_ value: _SpecificSQLExpressible) -> _SQLExpression {
return .function("ABS", [value.sqlExpression])
}
@@ -25,8 +25,8 @@ public func abs(value: _SQLDerivedExpressionType) -> _SQLExpression {
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func average(value: _SQLDerivedExpressionType) -> _SQLExpression {
return .Function("AVG", [value.sqlExpression])
public func average(_ value: _SpecificSQLExpressible) -> _SQLExpression {
return .function("AVG", [value.sqlExpression])
}
@@ -35,8 +35,8 @@ public func average(value: _SQLDerivedExpressionType) -> _SQLExpression {
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func count(counted: _SQLDerivedExpressionType) -> _SQLExpression {
return .Count(counted)
public func count(_ counted: _SpecificSQLExpressible) -> _SQLExpression {
return .count(counted)
}
@@ -45,8 +45,8 @@ public func count(counted: _SQLDerivedExpressionType) -> _SQLExpression {
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func count(distinct value: _SQLDerivedExpressionType) -> _SQLExpression {
return .CountDistinct(value.sqlExpression)
public func count(distinct value: _SpecificSQLExpressible) -> _SQLExpression {
return .countDistinct(value.sqlExpression)
}
@@ -55,16 +55,16 @@ public func count(distinct value: _SQLDerivedExpressionType) -> _SQLExpression {
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func ?? (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .Function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression])
public func ?? (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression])
}
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func ?? (lhs: _SQLExpressionType?, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
public func ?? (lhs: _SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression {
if let lhs = lhs {
return .Function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression])
return .function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression])
} else {
return rhs.sqlExpression
}
@@ -76,8 +76,8 @@ public func ?? (lhs: _SQLExpressionType?, rhs: _SQLDerivedExpressionType) -> _SQ
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func max(value: _SQLDerivedExpressionType) -> _SQLExpression {
return .Function("MAX", [value.sqlExpression])
public func max(_ value: _SpecificSQLExpressible) -> _SQLExpression {
return .function("MAX", [value.sqlExpression])
}
@@ -86,8 +86,8 @@ public func max(value: _SQLDerivedExpressionType) -> _SQLExpression {
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func min(value: _SQLDerivedExpressionType) -> _SQLExpression {
return .Function("MIN", [value.sqlExpression])
public func min(_ value: _SpecificSQLExpressible) -> _SQLExpression {
return .function("MIN", [value.sqlExpression])
}
@@ -96,74 +96,74 @@ public func min(value: _SQLDerivedExpressionType) -> _SQLExpression {
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func sum(value: _SQLDerivedExpressionType) -> _SQLExpression {
return .Function("SUM", [value.sqlExpression])
public func sum(_ value: _SpecificSQLExpressible) -> _SQLExpression {
return .function("SUM", [value.sqlExpression])
}
// MARK: - Swift String functions
extension _SQLDerivedExpressionType {
extension _SpecificSQLExpressible {
/// Returns an SQL expression that applies the Swift's built-in
/// capitalizedString String property. It is NULL for non-String arguments.
/// capitalized String property. It is NULL for non-String arguments.
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.capitalizedString)
/// let request = Person.select(nameColumn.capitalized)
/// let names = String.fetchAll(dbQueue, request) // [String]
public var capitalizedString: _SQLExpression {
return DatabaseFunction.capitalizedString.apply(sqlExpression)
public var capitalized: _SQLExpression {
return DatabaseFunction.capitalize.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// lowercaseString String property. It is NULL for non-String arguments.
/// lowercased String property. It is NULL for non-String arguments.
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.lowercaseString)
/// let request = Person.select(nameColumn.lowercased())
/// let names = String.fetchAll(dbQueue, request) // [String]
public var lowercaseString: _SQLExpression {
return DatabaseFunction.lowercaseString.apply(sqlExpression)
public var lowercased: _SQLExpression {
return DatabaseFunction.lowercase.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// uppercaseString String property. It is NULL for non-String arguments.
/// uppercased String property. It is NULL for non-String arguments.
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.uppercaseString)
/// let request = Person.select(nameColumn.uppercased())
/// let names = String.fetchAll(dbQueue, request) // [String]
public var uppercaseString: _SQLExpression {
return DatabaseFunction.uppercaseString.apply(sqlExpression)
public var uppercased: _SQLExpression {
return DatabaseFunction.uppercase.apply(sqlExpression)
}
}
@available(iOS 9.0, OSX 10.11, *)
extension _SQLDerivedExpressionType {
extension _SpecificSQLExpressible {
/// Returns an SQL expression that applies the Swift's built-in
/// localizedCapitalizedString String property. It is NULL for non-String arguments.
/// localizedCapitalized String property. It is NULL for non-String arguments.
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.localizedCapitalizedString)
/// let request = Person.select(nameColumn.localizedCapitalized)
/// let names = String.fetchAll(dbQueue, request) // [String]
public var localizedCapitalizedString: _SQLExpression {
return DatabaseFunction.localizedCapitalizedString.apply(sqlExpression)
public var localizedCapitalized: _SQLExpression {
return DatabaseFunction.localizedCapitalize.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// localizedLowercaseString String property. It is NULL for non-String arguments.
/// localizedLowercased String property. It is NULL for non-String arguments.
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.localizedLowercaseString)
/// let request = Person.select(nameColumn.localizedLowercased)
/// let names = String.fetchAll(dbQueue, request) // [String]
public var localizedLowercaseString: _SQLExpression {
return DatabaseFunction.localizedLowercaseString.apply(sqlExpression)
public var localizedLowercased: _SQLExpression {
return DatabaseFunction.localizedLowercase.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// localizedUppercaseString String property. It is NULL for non-String arguments.
/// localizedUppercased String property. It is NULL for non-String arguments.
///
/// let nameColumn = SQLColumn("name")
/// let request = Person.select(nameColumn.localizedUppercaseString)
/// let request = Person.select(nameColumn.localizedUppercased)
/// let names = String.fetchAll(dbQueue, request) // [String]
public var localizedUppercaseString: _SQLExpression {
return DatabaseFunction.localizedUppercaseString.apply(sqlExpression)
public var localizedUppercased: _SQLExpression {
return DatabaseFunction.localizedUppercase.apply(sqlExpression)
}
}
+127 -117
View File
@@ -3,52 +3,52 @@
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType?) -> _SQLExpression {
return .Equal(lhs.sqlExpression, rhs?.sqlExpression ?? .Value(nil))
public func == (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible?) -> _SQLExpression {
return .equalOperator(lhs.sqlExpression, rhs?.sqlExpression ?? .value(nil))
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _SQLDerivedExpressionType, rhs: protocol<_SQLExpressionType, BooleanType>?) -> _SQLExpression {
public func == (lhs: _SpecificSQLExpressible, rhs: protocol<_SQLExpressible, Boolean>?) -> _SQLExpression {
if let rhs = rhs {
if rhs.boolValue {
return lhs.sqlExpression
} else {
return .Not(lhs.sqlExpression)
return .notOperator(lhs.sqlExpression)
}
} else {
return .Equal(lhs.sqlExpression, .Value(nil))
return .equalOperator(lhs.sqlExpression, .value(nil))
}
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _SQLExpressionType?, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .Equal(lhs?.sqlExpression ?? .Value(nil), rhs.sqlExpression)
public func == (lhs: _SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .equalOperator(lhs?.sqlExpression ?? .value(nil), rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: protocol<_SQLExpressionType, BooleanType>?, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
public func == (lhs: protocol<_SQLExpressible, Boolean>?, rhs: _SpecificSQLExpressible) -> _SQLExpression {
if let lhs = lhs {
if lhs.boolValue {
return rhs.sqlExpression
} else {
return .Not(rhs.sqlExpression)
return .notOperator(rhs.sqlExpression)
}
} else {
return .Equal(.Value(nil), rhs.sqlExpression)
return .equalOperator(.value(nil), rhs.sqlExpression)
}
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .Equal(lhs.sqlExpression, rhs.sqlExpression)
public func == (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .equalOperator(lhs.sqlExpression, rhs.sqlExpression)
}
@@ -57,52 +57,52 @@ public func == (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType)
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType?) -> _SQLExpression {
return .NotEqual(lhs.sqlExpression, rhs?.sqlExpression ?? .Value(nil))
public func != (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible?) -> _SQLExpression {
return .notEqualOperator(lhs.sqlExpression, rhs?.sqlExpression ?? .value(nil))
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _SQLDerivedExpressionType, rhs: protocol<_SQLExpressionType, BooleanType>?) -> _SQLExpression {
public func != (lhs: _SpecificSQLExpressible, rhs: protocol<_SQLExpressible, Boolean>?) -> _SQLExpression {
if let rhs = rhs {
if rhs.boolValue {
return .Not(lhs.sqlExpression)
return .notOperator(lhs.sqlExpression)
} else {
return lhs.sqlExpression
}
} else {
return .NotEqual(lhs.sqlExpression, .Value(nil))
return .notEqualOperator(lhs.sqlExpression, .value(nil))
}
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _SQLExpressionType?, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .NotEqual(lhs?.sqlExpression ?? .Value(nil), rhs.sqlExpression)
public func != (lhs: _SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .notEqualOperator(lhs?.sqlExpression ?? .value(nil), rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: protocol<_SQLExpressionType, BooleanType>?, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
public func != (lhs: protocol<_SQLExpressible, Boolean>?, rhs: _SpecificSQLExpressible) -> _SQLExpression {
if let lhs = lhs {
if lhs.boolValue {
return .Not(rhs.sqlExpression)
return .notOperator(rhs.sqlExpression)
} else {
return rhs.sqlExpression
}
} else {
return .NotEqual(.Value(nil), rhs.sqlExpression)
return .notEqualOperator(.value(nil), rhs.sqlExpression)
}
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .NotEqual(lhs.sqlExpression, rhs.sqlExpression)
public func != (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .notEqualOperator(lhs.sqlExpression, rhs.sqlExpression)
}
@@ -111,22 +111,22 @@ public func != (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType)
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("<", lhs.sqlExpression, rhs.sqlExpression)
public func < (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator("<", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("<", lhs.sqlExpression, rhs.sqlExpression)
public func < (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("<", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("<", lhs.sqlExpression, rhs.sqlExpression)
public func < (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("<", lhs.sqlExpression, rhs.sqlExpression)
}
@@ -135,22 +135,22 @@ public func < (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("<=", lhs.sqlExpression, rhs.sqlExpression)
public func <= (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator("<=", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("<=", lhs.sqlExpression, rhs.sqlExpression)
public func <= (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("<=", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("<=", lhs.sqlExpression, rhs.sqlExpression)
public func <= (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("<=", lhs.sqlExpression, rhs.sqlExpression)
}
@@ -159,22 +159,22 @@ public func <= (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType)
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator(">", lhs.sqlExpression, rhs.sqlExpression)
public func > (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator(">", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator(">", lhs.sqlExpression, rhs.sqlExpression)
public func > (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator(">", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator(">", lhs.sqlExpression, rhs.sqlExpression)
public func > (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator(">", lhs.sqlExpression, rhs.sqlExpression)
}
@@ -183,22 +183,22 @@ public func > (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator(">=", lhs.sqlExpression, rhs.sqlExpression)
public func >= (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator(">=", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator(">=", lhs.sqlExpression, rhs.sqlExpression)
public func >= (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator(">=", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator(">=", lhs.sqlExpression, rhs.sqlExpression)
public func >= (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator(">=", lhs.sqlExpression, rhs.sqlExpression)
}
@@ -207,22 +207,22 @@ public func >= (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType)
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func * (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("*", lhs.sqlExpression, rhs.sqlExpression)
public func * (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator("*", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func * (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("*", lhs.sqlExpression, rhs.sqlExpression)
public func * (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("*", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func * (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("*", lhs.sqlExpression, rhs.sqlExpression)
public func * (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("*", lhs.sqlExpression, rhs.sqlExpression)
}
@@ -231,22 +231,22 @@ public func * (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func / (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("/", lhs.sqlExpression, rhs.sqlExpression)
public func / (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator("/", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func / (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("/", lhs.sqlExpression, rhs.sqlExpression)
public func / (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("/", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func / (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("/", lhs.sqlExpression, rhs.sqlExpression)
public func / (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("/", lhs.sqlExpression, rhs.sqlExpression)
}
@@ -255,22 +255,22 @@ public func / (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func + (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("+", lhs.sqlExpression, rhs.sqlExpression)
public func + (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator("+", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func + (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("+", lhs.sqlExpression, rhs.sqlExpression)
public func + (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("+", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func + (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("+", lhs.sqlExpression, rhs.sqlExpression)
public func + (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("+", lhs.sqlExpression, rhs.sqlExpression)
}
@@ -279,8 +279,8 @@ public func + (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public prefix func - (value: _SQLDerivedExpressionType) -> _SQLExpression {
return .PrefixOperator("-", value.sqlExpression)
public prefix func - (value: _SpecificSQLExpressible) -> _SQLExpression {
return .prefixOperator("-", value.sqlExpression)
}
@@ -289,22 +289,22 @@ public prefix func - (value: _SQLDerivedExpressionType) -> _SQLExpression {
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func - (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("-", lhs.sqlExpression, rhs.sqlExpression)
public func - (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator("-", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func - (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("-", lhs.sqlExpression, rhs.sqlExpression)
public func - (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("-", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func - (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("-", lhs.sqlExpression, rhs.sqlExpression)
public func - (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("-", lhs.sqlExpression, rhs.sqlExpression)
}
@@ -313,67 +313,77 @@ public func - (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -
/// Returns an SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func && (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("AND", lhs.sqlExpression, rhs.sqlExpression)
public func && (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator("AND", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func && (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("AND", lhs.sqlExpression, rhs.sqlExpression)
public func && (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("AND", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func && (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("AND", lhs.sqlExpression, rhs.sqlExpression)
public func && (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("AND", lhs.sqlExpression, rhs.sqlExpression)
}
// MARK: - Operator BETWEEN
extension Range where Element: protocol<_SQLExpressionType, BidirectionalIndexType> {
/// Returns an SQL expression that checks the inclusion of a value in
extension Range where Bound: _SQLExpressible {
/// Returns an SQL expression that compares the inclusion of a value in
/// a range.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _SQLDerivedExpressionType) -> _SQLExpression {
return .Between(value: element.sqlExpression, min: startIndex.sqlExpression, max: endIndex.predecessor().sqlExpression)
public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression {
return (element >= lowerBound) && (element < upperBound)
}
}
extension ClosedInterval where Bound: _SQLExpressionType {
/// Returns an SQL expression that checks the inclusion of a value in
/// an interval.
extension ClosedRange where Bound: _SQLExpressible {
/// Returns an SQL expression that compares the inclusion of a value in
/// a range.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _SQLDerivedExpressionType) -> _SQLExpression {
return .Between(value: element.sqlExpression, min: start.sqlExpression, max: end.sqlExpression)
public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression {
return .between(value: element.sqlExpression, min: lowerBound.sqlExpression, max: upperBound.sqlExpression)
}
}
extension HalfOpenInterval where Bound: _SQLExpressionType {
/// Returns an SQL expression that checks the inclusion of a value in
/// an interval.
extension CountableRange where Bound: _SQLExpressible {
/// Returns an SQL expression that compares the inclusion of a value in
/// a range.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _SQLDerivedExpressionType) -> _SQLExpression {
return (element >= start) && (element < end)
public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression {
return .between(value: element.sqlExpression, min: lowerBound.sqlExpression, max: upperBound.advanced(by: -1).sqlExpression)
}
}
extension CountableClosedRange where Bound: _SQLExpressible {
/// Returns an SQL expression that compares the inclusion of a value in
/// a range.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression {
return .between(value: element.sqlExpression, min: lowerBound.sqlExpression, max: upperBound.sqlExpression)
}
}
// MARK: - Operator IN
extension SequenceType where Self.Generator.Element: _SQLExpressionType {
extension Sequence where Self.Iterator.Element: _SQLExpressible {
/// Returns an SQL expression that checks the inclusion of a value in
/// a sequence.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _SQLDerivedExpressionType) -> _SQLExpression {
return .In(map { $0.sqlExpression }, element.sqlExpression)
public func contains(_ element: _SpecificSQLExpressible) -> _SQLExpression {
return .inOperator(map { $0.sqlExpression }, element.sqlExpression)
}
}
@@ -383,22 +393,22 @@ extension SequenceType where Self.Generator.Element: _SQLExpressionType {
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType?) -> _SQLExpression {
return .Is(lhs.sqlExpression, rhs?.sqlExpression ?? .Value(nil))
public func === (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible?) -> _SQLExpression {
return .isOperator(lhs.sqlExpression, rhs?.sqlExpression ?? .value(nil))
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _SQLExpressionType?, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .Is(lhs?.sqlExpression ?? .Value(nil), rhs.sqlExpression)
public func === (lhs: _SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .isOperator(lhs?.sqlExpression ?? .value(nil), rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .Is(lhs.sqlExpression, rhs.sqlExpression)
public func === (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .isOperator(lhs.sqlExpression, rhs.sqlExpression)
}
@@ -407,22 +417,22 @@ public func === (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType)
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType?) -> _SQLExpression {
return .IsNot(lhs.sqlExpression, rhs?.sqlExpression ?? .Value(nil))
public func !== (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible?) -> _SQLExpression {
return .isNotOperator(lhs.sqlExpression, rhs?.sqlExpression ?? .value(nil))
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _SQLExpressionType?, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .IsNot(lhs?.sqlExpression ?? .Value(nil), rhs.sqlExpression)
public func !== (lhs: _SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .isNotOperator(lhs?.sqlExpression ?? .value(nil), rhs.sqlExpression)
}
/// Returns an SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .IsNot(lhs.sqlExpression, rhs.sqlExpression)
public func !== (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .isNotOperator(lhs.sqlExpression, rhs.sqlExpression)
}
@@ -431,22 +441,22 @@ public func !== (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType)
/// Returns an SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func || (lhs: _SQLDerivedExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("OR", lhs.sqlExpression, rhs.sqlExpression)
public func || (lhs: _SpecificSQLExpressible, rhs: _SQLExpressible) -> _SQLExpression {
return .infixOperator("OR", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func || (lhs: _SQLExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("OR", lhs.sqlExpression, rhs.sqlExpression)
public func || (lhs: _SQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("OR", lhs.sqlExpression, rhs.sqlExpression)
}
/// Returns an SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func || (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType) -> _SQLExpression {
return .InfixOperator("OR", lhs.sqlExpression, rhs.sqlExpression)
public func || (lhs: _SpecificSQLExpressible, rhs: _SpecificSQLExpressible) -> _SQLExpression {
return .infixOperator("OR", lhs.sqlExpression, rhs.sqlExpression)
}
@@ -455,6 +465,6 @@ public func || (lhs: _SQLDerivedExpressionType, rhs: _SQLDerivedExpressionType)
/// Returns an SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public prefix func ! (value: _SQLDerivedExpressionType) -> _SQLExpression {
return .Not(value.sqlExpression)
public prefix func ! (value: _SpecificSQLExpressible) -> _SQLExpression {
return .notOperator(value.sqlExpression)
}
+160 -160
View File
@@ -8,46 +8,46 @@
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public struct _SQLSelectQuery {
var selection: [_SQLSelectable]
var distinct: Bool
var isDistinct: Bool
var source: _SQLSource?
var whereExpression: _SQLExpression?
var groupByExpressions: [_SQLExpression]
var sortDescriptors: [_SQLSortDescriptorType]
var reversed: Bool
var orderings: [_SQLOrdering]
var isReversed: Bool
var havingExpression: _SQLExpression?
var limit: _SQLLimit?
init(
select selection: [_SQLSelectable],
distinct: Bool = false,
isDistinct: Bool = false,
from source: _SQLSource? = nil,
filter whereExpression: _SQLExpression? = nil,
groupBy groupByExpressions: [_SQLExpression] = [],
orderBy sortDescriptors: [_SQLSortDescriptorType] = [],
reversed: Bool = false,
orderBy orderings: [_SQLOrdering] = [],
isReversed: Bool = false,
having havingExpression: _SQLExpression? = nil,
limit: _SQLLimit? = nil)
{
self.selection = selection
self.distinct = distinct
self.isDistinct = isDistinct
self.source = source
self.whereExpression = whereExpression
self.groupByExpressions = groupByExpressions
self.sortDescriptors = sortDescriptors
self.reversed = reversed
self.orderings = orderings
self.isReversed = isReversed
self.havingExpression = havingExpression
self.limit = limit
}
func sql(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
func sql(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
var sql = "SELECT"
if distinct {
if isDistinct {
sql += " DISTINCT"
}
assert(!selection.isEmpty)
sql += try " " + selection.map { try $0.resultColumnSQL(db, &bindings) }.joinWithSeparator(", ")
sql += try " " + selection.map { try $0.resultColumnSQL(db, &bindings) }.joined(separator: ", ")
if let source = source {
sql += try " FROM " + source.sql(db, &bindings)
@@ -58,16 +58,16 @@ public struct _SQLSelectQuery {
}
if !groupByExpressions.isEmpty {
sql += try " GROUP BY " + groupByExpressions.map { try $0.sql(db, &bindings) }.joinWithSeparator(", ")
sql += try " GROUP BY " + groupByExpressions.map { try $0.sql(db, &bindings) }.joined(separator: ", ")
}
if let havingExpression = havingExpression {
sql += try " HAVING " + havingExpression.sql(db, &bindings)
}
var sortDescriptors = self.sortDescriptors
if reversed {
if sortDescriptors.isEmpty {
var orderings = self.orderings
if isReversed {
if orderings.isEmpty {
// https://www.sqlite.org/lang_createtable.html#rowid
//
// > The rowid value can be accessed using one of the special
@@ -80,13 +80,13 @@ public struct _SQLSelectQuery {
// Here we assume that _rowid_ is not a custom column.
// TODO: support for user-defined _rowid_ column.
// TODO: support for WITHOUT ROWID tables.
sortDescriptors = [SQLColumn("_rowid_").desc]
orderings = [SQLColumn("_rowid_").desc]
} else {
sortDescriptors = sortDescriptors.map { $0.reversedSortDescriptor }
orderings = orderings.map { $0.reversedOrdering }
}
}
if !sortDescriptors.isEmpty {
sql += try " ORDER BY " + sortDescriptors.map { try $0.orderingSQL(db, &bindings) }.joinWithSeparator(", ")
if !orderings.isEmpty {
sql += try " ORDER BY " + orderings.map { try $0.orderingSQL(db, &bindings) }.joined(separator: ", ")
}
if let limit = limit {
@@ -104,7 +104,7 @@ public struct _SQLSelectQuery {
return trivialCountQuery
}
guard let source = source, case .Table(name: let tableName, alias: let alias) = source else {
guard let source = source, case .table(name: let tableName, alias: let alias) = source else {
// SELECT ... FROM (something which is not a table)
return trivialCountQuery
}
@@ -113,8 +113,8 @@ public struct _SQLSelectQuery {
if selection.count == 1 {
let selectable = self.selection[0]
switch selectable.sqlSelectableKind {
case .Star(sourceName: let sourceName):
guard !distinct else {
case .star(sourceName: let sourceName):
guard !isDistinct else {
return trivialCountQuery
}
@@ -128,32 +128,32 @@ public struct _SQLSelectQuery {
// ->
// SELECT COUNT(*) FROM tableName ...
var countQuery = unorderedQuery
countQuery.selection = [_SQLExpression.Count(selectable)]
countQuery.selection = [_SQLExpression.count(selectable)]
return countQuery
case .Expression(let expression):
case .expression(let expression):
// SELECT [DISTINCT] expr FROM tableName ...
if distinct {
if isDistinct {
// SELECT DISTINCT expr FROM tableName ...
// ->
// SELECT COUNT(DISTINCT expr) FROM tableName ...
var countQuery = unorderedQuery
countQuery.distinct = false
countQuery.selection = [_SQLExpression.CountDistinct(expression)]
countQuery.isDistinct = false
countQuery.selection = [_SQLExpression.countDistinct(expression)]
return countQuery
} else {
// SELECT expr FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
var countQuery = unorderedQuery
countQuery.selection = [_SQLExpression.Count(_SQLResultColumn.Star(nil))]
countQuery.selection = [_SQLExpression.count(_SQLResultColumn.star(nil))]
return countQuery
}
}
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
guard !distinct else {
guard !isDistinct else {
return trivialCountQuery
}
@@ -161,7 +161,7 @@ public struct _SQLSelectQuery {
// ->
// SELECT COUNT(*) FROM tableName ...
var countQuery = unorderedQuery
countQuery.selection = [_SQLExpression.Count(_SQLResultColumn.Star(nil))]
countQuery.selection = [_SQLExpression.count(_SQLResultColumn.star(nil))]
return countQuery
}
}
@@ -169,15 +169,15 @@ public struct _SQLSelectQuery {
// SELECT COUNT(*) FROM (self)
private var trivialCountQuery: _SQLSelectQuery {
return _SQLSelectQuery(
select: [_SQLExpression.Count(_SQLResultColumn.Star(nil))],
from: .Query(query: unorderedQuery, alias: nil))
select: [_SQLExpression.count(_SQLResultColumn.star(nil))],
from: .query(query: unorderedQuery, alias: nil))
}
/// Remove ordering
private var unorderedQuery: _SQLSelectQuery {
var query = self
query.reversed = false
query.sortDescriptors = []
query.isReversed = false
query.orderings = []
return query
}
}
@@ -186,18 +186,18 @@ public struct _SQLSelectQuery {
// MARK: - _SQLSource
indirect enum _SQLSource {
case Table(name: String, alias: String?)
case Query(query: _SQLSelectQuery, alias: String?)
case table(name: String, alias: String?)
case query(query: _SQLSelectQuery, alias: String?)
func sql(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
func sql(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
switch self {
case .Table(let table, let alias):
case .table(let table, let alias):
if let alias = alias {
return table.quotedDatabaseIdentifier + " AS " + alias.quotedDatabaseIdentifier
} else {
return table.quotedDatabaseIdentifier
}
case .Query(let query, let alias):
case .query(let query, let alias):
if let alias = alias {
return try "(" + query.sql(db, &bindings) + ") AS " + alias.quotedDatabaseIdentifier
} else {
@@ -208,38 +208,38 @@ indirect enum _SQLSource {
}
// MARK: - _SQLSortDescriptorType
// MARK: - _SQLOrdering
/// This protocol is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public protocol _SQLSortDescriptorType {
var reversedSortDescriptor: _SQLSortDescriptor { get }
func orderingSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String
public protocol _SQLOrdering {
var reversedOrdering: _SQLOrderingExpression { get }
func orderingSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String
}
/// This type is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public enum _SQLSortDescriptor {
case Asc(_SQLExpression)
case Desc(_SQLExpression)
public enum _SQLOrderingExpression {
case asc(_SQLExpression)
case desc(_SQLExpression)
}
extension _SQLSortDescriptor : _SQLSortDescriptorType {
extension _SQLOrderingExpression : _SQLOrdering {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var reversedSortDescriptor: _SQLSortDescriptor {
public var reversedOrdering: _SQLOrderingExpression {
switch self {
case .Asc(let expression):
return .Desc(expression)
case .Desc(let expression):
return .Asc(expression)
case .asc(let expression):
return .desc(expression)
case .desc(let expression):
return .asc(expression)
}
}
@@ -247,11 +247,11 @@ extension _SQLSortDescriptor : _SQLSortDescriptorType {
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public func orderingSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
public func orderingSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
switch self {
case .Asc(let expression):
case .asc(let expression):
return try expression.sql(db, &bindings) + " ASC"
case .Desc(let expression):
case .desc(let expression):
return try expression.sql(db, &bindings) + " DESC"
}
}
@@ -274,9 +274,9 @@ struct _SQLLimit {
}
// MARK: - _SQLExpressionType
// MARK: - _SQLExpressible
public protocol _SQLExpressionType {
public protocol _SQLExpressible {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
@@ -285,7 +285,7 @@ public protocol _SQLExpressionType {
var sqlExpression: _SQLExpression { get }
}
// Conformance to _SQLExpressionType
// Conformance to _SQLExpressible
extension DatabaseValueConvertible {
/// This property is an implementation detail of the query interface.
@@ -293,7 +293,7 @@ extension DatabaseValueConvertible {
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var sqlExpression: _SQLExpression {
return .Value(self)
return .value(self)
}
}
@@ -301,37 +301,37 @@ extension DatabaseValueConvertible {
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public protocol _SQLDerivedExpressionType : _SQLExpressionType, _SQLSortDescriptorType, _SQLSelectable {
public protocol _SpecificSQLExpressible : _SQLExpressible, _SQLOrdering, _SQLSelectable {
}
// Conformance to _SQLSortDescriptorType
extension _SQLDerivedExpressionType {
// Conformance to _SQLOrdering
extension _SpecificSQLExpressible {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var reversedSortDescriptor: _SQLSortDescriptor {
return .Desc(sqlExpression)
public var reversedOrdering: _SQLOrderingExpression {
return .desc(sqlExpression)
}
/// This method is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public func orderingSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
public func orderingSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
return try sqlExpression.sql(db, &bindings)
}
}
// Conformance to _SQLSelectable
extension _SQLDerivedExpressionType {
extension _SpecificSQLExpressible {
/// This method is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public func resultColumnSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
public func resultColumnSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
return try sqlExpression.sql(db, &bindings)
}
@@ -339,7 +339,7 @@ extension _SQLDerivedExpressionType {
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public func countedSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
public func countedSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
return try sqlExpression.sql(db, &bindings)
}
@@ -348,31 +348,31 @@ extension _SQLDerivedExpressionType {
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var sqlSelectableKind: _SQLSelectableKind {
return .Expression(sqlExpression)
return .expression(sqlExpression)
}
}
extension _SQLDerivedExpressionType {
extension _SpecificSQLExpressible {
/// Returns a value that can be used as an argument to FetchRequest.order()
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var asc: _SQLSortDescriptor {
return .Asc(sqlExpression)
public var asc: _SQLOrderingExpression {
return .asc(sqlExpression)
}
/// Returns a value that can be used as an argument to FetchRequest.order()
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var desc: _SQLSortDescriptor {
return .Desc(sqlExpression)
public var desc: _SQLOrderingExpression {
return .desc(sqlExpression)
}
/// Returns a value that can be used as an argument to FetchRequest.select()
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public func aliased(alias: String) -> _SQLSelectable {
return _SQLResultColumn.Expression(expression: sqlExpression, alias: alias)
public func aliased(_ alias: String) -> _SQLSelectable {
return _SQLResultColumn.expression(expression: sqlExpression, alias: alias)
}
}
@@ -383,205 +383,205 @@ extension _SQLDerivedExpressionType {
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public indirect enum _SQLExpression {
/// For example: `name || 'rrr' AS pirateName`
case Literal(String)
case SQLLiteral(String)
/// For example: `1` or `'foo'`
case Value(DatabaseValueConvertible?)
case value(DatabaseValueConvertible?)
/// For example: `name`, `table.name`
case Identifier(identifier: String, sourceName: String?)
case identifier(identifier: String, sourceName: String?)
/// For example: `name = 'foo' COLLATE NOCASE`
case Collate(_SQLExpression, String)
case collate(_SQLExpression, String)
/// For example: `NOT condition`
case Not(_SQLExpression)
case notOperator(_SQLExpression)
/// For example: `name = 'foo'`
case Equal(_SQLExpression, _SQLExpression)
case equalOperator(_SQLExpression, _SQLExpression)
/// For example: `name <> 'foo'`
case NotEqual(_SQLExpression, _SQLExpression)
case notEqualOperator(_SQLExpression, _SQLExpression)
/// For example: `name IS NULL`
case Is(_SQLExpression, _SQLExpression)
case isOperator(_SQLExpression, _SQLExpression)
/// For example: `name IS NOT NULL`
case IsNot(_SQLExpression, _SQLExpression)
case isNotOperator(_SQLExpression, _SQLExpression)
/// For example: `-value`
case PrefixOperator(String, _SQLExpression)
case prefixOperator(String, _SQLExpression)
/// For example: `age + 1`
case InfixOperator(String, _SQLExpression, _SQLExpression)
case infixOperator(String, _SQLExpression, _SQLExpression)
/// For example: `id IN (1,2,3)`
case In([_SQLExpression], _SQLExpression)
case inOperator([_SQLExpression], _SQLExpression)
/// For example `id IN (SELECT ...)`
case InSubQuery(_SQLSelectQuery, _SQLExpression)
case inSubQuery(_SQLSelectQuery, _SQLExpression)
/// For example `EXISTS (SELECT ...)`
case Exists(_SQLSelectQuery)
case exists(_SQLSelectQuery)
/// For example: `age BETWEEN 1 AND 2`
case Between(value: _SQLExpression, min: _SQLExpression, max: _SQLExpression)
case between(value: _SQLExpression, min: _SQLExpression, max: _SQLExpression)
/// For example: `LOWER(name)`
case Function(String, [_SQLExpression])
case function(String, [_SQLExpression])
/// For example: `COUNT(*)`
case Count(_SQLSelectable)
case count(_SQLSelectable)
/// For example: `COUNT(DISTINCT name)`
case CountDistinct(_SQLExpression)
case countDistinct(_SQLExpression)
///
func sql(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
func sql(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
// TODO: this method is slow to compile
// https://medium.com/swift-programming/speeding-up-slow-swift-build-times-922feeba5780#.s77wmh4h0
// 10746.4ms /Users/groue/Documents/git/groue/GRDB.swift/GRDB/FetchRequest/SQLSelectQuery.swift:439:10 func sql(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String
// 10746.4ms /Users/groue/Documents/git/groue/GRDB.swift/GRDB/FetchRequest/SQLSelectQuery.swift:439:10 func sql(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String
switch self {
case .Literal(let sql):
case .SQLLiteral(let sql):
return sql
case .Value(let value):
case .value(let value):
guard let value = value else {
return "NULL"
}
bindings.append(value)
return "?"
case .Identifier(let identifier, let sourceName):
case .identifier(let identifier, let sourceName):
if let sourceName = sourceName {
return sourceName.quotedDatabaseIdentifier + "." + identifier.quotedDatabaseIdentifier
} else {
return identifier.quotedDatabaseIdentifier
}
case .Collate(let expression, let collation):
case .collate(let expression, let collation):
let sql = try expression.sql(db, &bindings)
let chars = sql.characters
if chars.last! == ")" {
return String(chars.prefixUpTo(chars.endIndex.predecessor())) + " COLLATE " + collation + ")"
return String(chars.prefix(upTo: chars.index(chars.endIndex, offsetBy: -1))) + " COLLATE " + collation + ")"
} else {
return sql + " COLLATE " + collation
}
case .Not(let condition):
case .notOperator(let condition):
switch condition {
case .Not(let expression):
case .notOperator(let expression):
return try expression.sql(db, &bindings)
case .In(let expressions, let expression):
case .inOperator(let expressions, let expression):
if expressions.isEmpty {
return "1"
} else {
return try "(" + expression.sql(db, &bindings) + " NOT IN (" + expressions.map { try $0.sql(db, &bindings) }.joinWithSeparator(", ") + "))"
return try "(" + expression.sql(db, &bindings) + " NOT IN (" + expressions.map { try $0.sql(db, &bindings) }.joined(separator: ", ") + "))"
}
case .InSubQuery(let subQuery, let expression):
case .inSubQuery(let subQuery, let expression):
return try "(" + expression.sql(db, &bindings) + " NOT IN (" + subQuery.sql(db, &bindings) + "))"
case .Exists(let subQuery):
case .exists(let subQuery):
return try "(NOT EXISTS (" + subQuery.sql(db, &bindings) + "))"
case .Equal(let lhs, let rhs):
return try _SQLExpression.NotEqual(lhs, rhs).sql(db, &bindings)
case .equalOperator(let lhs, let rhs):
return try _SQLExpression.notEqualOperator(lhs, rhs).sql(db, &bindings)
case .NotEqual(let lhs, let rhs):
return try _SQLExpression.Equal(lhs, rhs).sql(db, &bindings)
case .notEqualOperator(let lhs, let rhs):
return try _SQLExpression.equalOperator(lhs, rhs).sql(db, &bindings)
case .Is(let lhs, let rhs):
return try _SQLExpression.IsNot(lhs, rhs).sql(db, &bindings)
case .isOperator(let lhs, let rhs):
return try _SQLExpression.isNotOperator(lhs, rhs).sql(db, &bindings)
case .IsNot(let lhs, let rhs):
return try _SQLExpression.Is(lhs, rhs).sql(db, &bindings)
case .isNotOperator(let lhs, let rhs):
return try _SQLExpression.isOperator(lhs, rhs).sql(db, &bindings)
default:
return try "(NOT " + condition.sql(db, &bindings) + ")"
}
case .Equal(let lhs, let rhs):
case .equalOperator(let lhs, let rhs):
switch (lhs, rhs) {
case (let lhs, .Value(let rhs)) where rhs == nil:
case (let lhs, .value(let rhs)) where rhs == nil:
// Swiftism!
// Turn `filter(a == nil)` into `a IS NULL` since the intention is obviously to check for NULL. `a = NULL` would evaluate to NULL.
return try "(" + lhs.sql(db, &bindings) + " IS NULL)"
case (.Value(let lhs), let rhs) where lhs == nil:
case (.value(let lhs), let rhs) where lhs == nil:
// Swiftism!
return try "(" + rhs.sql(db, &bindings) + " IS NULL)"
default:
return try "(" + lhs.sql(db, &bindings) + " = " + rhs.sql(db, &bindings) + ")"
}
case .NotEqual(let lhs, let rhs):
case .notEqualOperator(let lhs, let rhs):
switch (lhs, rhs) {
case (let lhs, .Value(let rhs)) where rhs == nil:
case (let lhs, .value(let rhs)) where rhs == nil:
// Swiftism!
// Turn `filter(a != nil)` into `a IS NOT NULL` since the intention is obviously to check for NULL. `a <> NULL` would evaluate to NULL.
return try "(" + lhs.sql(db, &bindings) + " IS NOT NULL)"
case (.Value(let lhs), let rhs) where lhs == nil:
case (.value(let lhs), let rhs) where lhs == nil:
// Swiftism!
return try "(" + rhs.sql(db, &bindings) + " IS NOT NULL)"
default:
return try "(" + lhs.sql(db, &bindings) + " <> " + rhs.sql(db, &bindings) + ")"
}
case .Is(let lhs, let rhs):
case .isOperator(let lhs, let rhs):
switch (lhs, rhs) {
case (let lhs, .Value(let rhs)) where rhs == nil:
case (let lhs, .value(let rhs)) where rhs == nil:
return try "(" + lhs.sql(db, &bindings) + " IS NULL)"
case (.Value(let lhs), let rhs) where lhs == nil:
case (.value(let lhs), let rhs) where lhs == nil:
return try "(" + rhs.sql(db, &bindings) + " IS NULL)"
default:
return try "(" + lhs.sql(db, &bindings) + " IS " + rhs.sql(db, &bindings) + ")"
}
case .IsNot(let lhs, let rhs):
case .isNotOperator(let lhs, let rhs):
switch (lhs, rhs) {
case (let lhs, .Value(let rhs)) where rhs == nil:
case (let lhs, .value(let rhs)) where rhs == nil:
return try "(" + lhs.sql(db, &bindings) + " IS NOT NULL)"
case (.Value(let lhs), let rhs) where lhs == nil:
case (.value(let lhs), let rhs) where lhs == nil:
return try "(" + rhs.sql(db, &bindings) + " IS NOT NULL)"
default:
return try "(" + lhs.sql(db, &bindings) + " IS NOT " + rhs.sql(db, &bindings) + ")"
}
case .PrefixOperator(let SQLOperator, let value):
case .prefixOperator(let SQLOperator, let value):
return try SQLOperator + value.sql(db, &bindings)
case .InfixOperator(let SQLOperator, let lhs, let rhs):
case .infixOperator(let SQLOperator, let lhs, let rhs):
return try "(" + lhs.sql(db, &bindings) + " \(SQLOperator) " + rhs.sql(db, &bindings) + ")"
case .In(let expressions, let expression):
case .inOperator(let expressions, let expression):
guard !expressions.isEmpty else {
return "0"
}
return try "(" + expression.sql(db, &bindings) + " IN (" + expressions.map { try $0.sql(db, &bindings) }.joinWithSeparator(", ") + "))"
return try "(" + expression.sql(db, &bindings) + " IN (" + expressions.map { try $0.sql(db, &bindings) }.joined(separator: ", ") + "))"
case .InSubQuery(let subQuery, let expression):
case .inSubQuery(let subQuery, let expression):
return try "(" + expression.sql(db, &bindings) + " IN (" + subQuery.sql(db, &bindings) + "))"
case .Exists(let subQuery):
case .exists(let subQuery):
return try "(EXISTS (" + subQuery.sql(db, &bindings) + "))"
case .Between(value: let value, min: let min, max: let max):
case .between(value: let value, min: let min, max: let max):
return try "(" + value.sql(db, &bindings) + " BETWEEN " + min.sql(db, &bindings) + " AND " + max.sql(db, &bindings) + ")"
case .Function(let functionName, let functionArguments):
return try functionName + "(" + functionArguments.map { try $0.sql(db, &bindings) }.joinWithSeparator(", ") + ")"
case .function(let functionName, let functionArguments):
return try functionName + "(" + functionArguments.map { try $0.sql(db, &bindings) }.joined(separator: ", ") + ")"
case .Count(let counted):
case .count(let counted):
return try "COUNT(" + counted.countedSQL(db, &bindings) + ")"
case .CountDistinct(let expression):
case .countDistinct(let expression):
return try "COUNT(DISTINCT " + expression.sql(db, &bindings) + ")"
}
}
}
extension _SQLExpression : _SQLDerivedExpressionType {
extension _SQLExpression : _SpecificSQLExpressible {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
@@ -600,8 +600,8 @@ extension _SQLExpression : _SQLDerivedExpressionType {
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public protocol _SQLSelectable {
func resultColumnSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String
func countedSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String
func resultColumnSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String
func countedSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String
var sqlSelectableKind: _SQLSelectableKind { get }
}
@@ -610,45 +610,45 @@ public protocol _SQLSelectable {
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public enum _SQLSelectableKind {
case Expression(_SQLExpression)
case Star(sourceName: String?)
case expression(_SQLExpression)
case star(sourceName: String?)
}
enum _SQLResultColumn {
case Star(String?)
case Expression(expression: _SQLExpression, alias: String)
case star(String?)
case expression(expression: _SQLExpression, alias: String)
}
extension _SQLResultColumn : _SQLSelectable {
func resultColumnSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
func resultColumnSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
switch self {
case .Star(let sourceName):
case .star(let sourceName):
if let sourceName = sourceName {
return sourceName.quotedDatabaseIdentifier + ".*"
} else {
return "*"
}
case .Expression(expression: let expression, alias: let alias):
case .expression(expression: let expression, alias: let alias):
return try expression.sql(db, &bindings) + " AS " + alias.quotedDatabaseIdentifier
}
}
func countedSQL(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
func countedSQL(_ db: Database, _ bindings: inout [DatabaseValueConvertible?]) throws -> String {
switch self {
case .Star:
case .star:
return "*"
case .Expression(expression: let expression, alias: _):
case .expression(expression: let expression, alias: _):
return try expression.sql(db, &bindings)
}
}
var sqlSelectableKind: _SQLSelectableKind {
switch self {
case .Star(let sourceName):
return .Star(sourceName: sourceName)
case .Expression(expression: let expression, alias: _):
return .Expression(expression)
case .star(let sourceName):
return .star(sourceName: sourceName)
case .expression(expression: let expression, alias: _):
return .expression(expression)
}
}
}
@@ -663,9 +663,9 @@ struct _SQLLiteral {
}
}
extension _SQLLiteral : _SQLDerivedExpressionType {
extension _SQLLiteral : _SpecificSQLExpressible {
var sqlExpression: _SQLExpression {
return .Literal(sql)
return .SQLLiteral(sql)
}
}
@@ -693,14 +693,14 @@ public struct SQLColumn {
}
}
extension SQLColumn : _SQLDerivedExpressionType {
extension SQLColumn : _SpecificSQLExpressible {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var sqlExpression: _SQLExpression {
return .Identifier(identifier: name, sourceName: sourceName)
return .identifier(identifier: name, sourceName: sourceName)
}
}
+6 -6
View File
@@ -57,7 +57,7 @@ public struct DatabaseMigrator {
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigration(identifier: String, migrate: (Database) throws -> Void) {
public mutating func registerMigration(_ identifier: String, migrate: (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, migrate: migrate))
}
@@ -81,7 +81,7 @@ public struct DatabaseMigrator {
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (Database) throws -> Void) {
public mutating func registerMigrationWithDisabledForeignKeyChecks(_ identifier: String, migrate: (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
@@ -92,7 +92,7 @@ public struct DatabaseMigrator {
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
/// migrations should apply.
/// - throws: An eventual error thrown by the registered migration blocks.
public func migrate(db: DatabaseWriter) throws {
public func migrate(_ db: DatabaseWriter) throws {
try db.write { db in
try self.setupMigrations(db)
try self.runMigrations(db)
@@ -104,16 +104,16 @@ public struct DatabaseMigrator {
private var migrations: [Migration] = []
private mutating func registerMigration(migration: Migration) {
private mutating func registerMigration(_ migration: Migration) {
GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \"\(migration.identifier)\"")
migrations.append(migration)
}
private func setupMigrations(db: Database) throws {
private func setupMigrations(_ db: Database) throws {
try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
}
private func runMigrations(db: Database) throws {
private func runMigrations(_ db: Database) throws {
let appliedIdentifiers = String.fetchAll(db, "SELECT identifier FROM grdb_migrations")
for migration in migrations where !appliedIdentifiers.contains(migration.identifier) {
try migration.run(db)
+8 -8
View File
@@ -31,7 +31,7 @@ struct Migration {
self.migrate = migrate
}
func run(db: Database) throws {
func run(_ db: Database) throws {
if #available(iOS 8.2, OSX 10.10, *) {
if disabledForeignKeyChecks && Bool.fetchOne(db, "PRAGMA foreign_keys")! {
try runWithDisabledForeignKeys(db)
@@ -44,16 +44,16 @@ struct Migration {
}
private func runWithoutDisabledForeignKeys(db: Database) throws {
try db.inTransaction(.Immediate) {
private func runWithoutDisabledForeignKeys(_ db: Database) throws {
try db.inTransaction(.immediate) {
try self.migrate(db: db)
try self.insertAppliedIdentifier(db)
return .Commit
return .commit
}
}
@available(iOS 8.2, OSX 10.10, *)
private func runWithDisabledForeignKeys(db: Database) throws {
private func runWithDisabledForeignKeys(_ db: Database) throws {
// Support for database alterations described at
// https://www.sqlite.org/lang_altertable.html#otheralter
//
@@ -67,7 +67,7 @@ struct Migration {
}
// > 2. Start a transaction.
try db.inTransaction(.Immediate) {
try db.inTransaction(.immediate) {
try self.migrate(db: db)
try self.insertAppliedIdentifier(db)
@@ -86,11 +86,11 @@ struct Migration {
}
// > 11. Commit the transaction started in step 2.
return .Commit
return .commit
}
}
private func insertAppliedIdentifier(db: Database) throws {
private func insertAppliedIdentifier(_ db: Database) throws {
try db.execute("INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
}
}
+87 -87
View File
@@ -16,7 +16,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
/// let controller = FetchedRecordsController<Wine>(
/// dbQueue,
/// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
/// arguments: [Color.Red],
/// arguments: [Color.red],
/// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
///
/// - parameters:
@@ -106,7 +106,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
observedTables: statement.sourceTables,
isSameItem: self.isSameItem)
self.observer = observer
db.addTransactionObserver(observer)
db.add(transactionObserver: observer)
}
}
}
@@ -128,7 +128,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
/// Updates the fetch request, and notifies the delegate of changes in the
/// fetched records if delegate is not nil, and performFetch() has been
/// called.
public func setRequest(request: FetchRequest) {
public func setRequest(_ request: FetchRequest) {
// We don't provide a setter for the request property because we need a
// non-optional request.
self.request = request
@@ -137,12 +137,12 @@ public final class FetchedRecordsController<Record: RowConvertible> {
/// Updates the fetch request, and notifies the delegate of changes in the
/// fetched records if delegate is not nil, and performFetch() has been
/// called.
public func setRequest(sql sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) {
public func setRequest(sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) {
setRequest(SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter))
}
public typealias WillChangeCallback = FetchedRecordsController<Record> -> ()
public typealias DidChangeCallback = FetchedRecordsController<Record> -> ()
public typealias WillChangeCallback = (FetchedRecordsController<Record>) -> ()
public typealias DidChangeCallback = (FetchedRecordsController<Record>) -> ()
private var willChangeCallback: WillChangeCallback?
private var didChangeCallback: DidChangeCallback?
@@ -200,8 +200,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
observedTables: statement.sourceTables,
isSameItem: self.isSameItemFactory(db))
self.observer = observer
db.addTransactionObserver(observer)
observer.checkForChangesInDatabase(db)
db.add(transactionObserver: observer)
observer.checkForChanges(in: db)
}
}
}
@@ -245,7 +245,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
didSet {
guard let observer = observer else { return }
databaseWriter.write { db in
observer.checkForChangesInDatabase(db)
observer.checkForChanges(in: db)
}
}
}
@@ -274,7 +274,7 @@ extension FetchedRecordsController where Record: TableMapping {
/// let controller = FetchedRecordsController<Wine>(
/// dbQueue,
/// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
/// arguments: [Color.Red],
/// arguments: [Color.red],
/// compareRecordsByPrimaryKey: true)
///
/// - parameters:
@@ -332,9 +332,9 @@ extension FetchedRecordsController where Record: TableMapping {
// MARK: - FetchedRecordsObserver
/// FetchedRecordsController adopts TransactionObserverType so that it can
/// FetchedRecordsController adopts TransactionObserver so that it can
/// monitor changes to its fetched records.
private final class FetchedRecordsObserver<Record: RowConvertible> : TransactionObserverType {
private final class FetchedRecordsObserver<Record: RowConvertible> : TransactionObserver {
weak var controller: FetchedRecordsController<Record>? // If nil, self is invalidated.
let observedTables: Set<String>
let isSameItem: (Item<Record>, Item<Record>) -> Bool
@@ -355,23 +355,23 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
controller = nil
}
/// Part of the TransactionObserverType protocol
func databaseDidChangeWithEvent(event: DatabaseEvent) {
/// Part of the TransactionObserver protocol
func databaseDidChange(with event: DatabaseEvent) {
if !needsComputeChanges && observedTables.contains(event.tableName) {
needsComputeChanges = true
}
}
/// Part of the TransactionObserverType protocol
/// Part of the TransactionObserver protocol
func databaseWillCommit() throws { }
/// Part of the TransactionObserverType protocol
func databaseDidRollback(db: Database) {
/// Part of the TransactionObserver protocol
func databaseDidRollback(_ db: Database) {
needsComputeChanges = false
}
/// Part of the TransactionObserverType protocol
func databaseDidCommit(db: Database) {
/// Part of the TransactionObserver protocol
func databaseDidCommit(_ db: Database) {
// The databaseDidCommit callback is called in the database writer
// dispatch queue, which is serialized: it is guaranteed to process the
// last database transaction.
@@ -380,12 +380,12 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
guard needsComputeChanges else { return }
needsComputeChanges = false
checkForChangesInDatabase(db)
checkForChanges(in: db)
}
// Precondition: this method must be called from the database writer's
// serialized dispatch queue.
func checkForChangesInDatabase(db: Database) {
func checkForChanges(in db: Database) {
// Invalidated?
guard let controller = self.controller else { return }
@@ -410,7 +410,7 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
// fetch: let's immediately dispatch the processing task in our
// serialized FIFO queue, but have it wait for our fetch to complete,
// with a semaphore:
let semaphore = dispatch_semaphore_create(0)
let semaphore = dispatch_semaphore_create(0)!
var fetchedItems: [Item<Record>]! = nil
controller.databaseWriter.readFromWrite { db in
@@ -495,11 +495,11 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
///
/// If indexPath does not describe a valid index path in the fetched
/// records, a fatal error is raised.
public func recordAtIndexPath(indexPath: NSIndexPath) -> Record {
public func record(at indexPath: NSIndexPath) -> Record {
guard let fetchedItems = fetchedItems else {
fatalError("performFetch() has not been called.")
}
return fetchedItems[indexPath.indexAtPosition(1)].record
return fetchedItems[indexPath.index(atPosition: 1)].record
}
@@ -521,9 +521,9 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
///
/// - returns: The index path of *record* in the fetched records, or nil
/// if record could not be found.
public func indexPathForRecord(record: Record) -> NSIndexPath? {
let item = Item<Record>(Row(record.persistentDictionary))
guard let fetchedItems = fetchedItems, let index = fetchedItems.indexOf({ isSameItem($0, item) }) else {
public func indexPath(for record: Record) -> NSIndexPath? {
let item = Item<Record>(row: Row(record.persistentDictionary))
guard let fetchedItems = fetchedItems, let index = fetchedItems.index(where: { isSameItem($0, item) }) else {
return nil
}
return makeIndexPath(forRow: index, inSection: 0)
@@ -538,18 +538,18 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
// Fill first row and column of insertions and deletions.
var d: [[[TableViewChange<Record>]]] = Array(count: m + 1, repeatedValue: Array(count: n + 1, repeatedValue: []))
var d: [[[TableViewChange<Record>]]] = Array(repeating: Array(repeating: [], count: n + 1), count: m + 1)
var changes = [TableViewChange<Record>]()
for (row, item) in s.enumerate() {
let deletion = TableViewChange.Deletion(item: item, indexPath: makeIndexPath(forRow: row, inSection: 0))
for (row, item) in s.enumerated() {
let deletion = TableViewChange.deletion(item: item, indexPath: makeIndexPath(forRow: row, inSection: 0))
changes.append(deletion)
d[row + 1][0] = changes
}
changes.removeAll()
for (col, item) in t.enumerate() {
let insertion = TableViewChange.Insertion(item: item, indexPath: makeIndexPath(forRow: col, inSection: 0))
for (col, item) in t.enumerated() {
let insertion = TableViewChange.insertion(item: item, indexPath: makeIndexPath(forRow: col, inSection: 0))
changes.append(insertion)
d[0][col + 1] = changes
}
@@ -572,16 +572,16 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
// Record operation.
let minimumCount = min(del.count, ins.count, sub.count)
if del.count == minimumCount {
let deletion = TableViewChange.Deletion(item: s[sx], indexPath: makeIndexPath(forRow: sx, inSection: 0))
let deletion = TableViewChange.deletion(item: s[sx], indexPath: makeIndexPath(forRow: sx, inSection: 0))
del.append(deletion)
d[sx+1][tx+1] = del
} else if ins.count == minimumCount {
let insertion = TableViewChange.Insertion(item: t[tx], indexPath: makeIndexPath(forRow: tx, inSection: 0))
let insertion = TableViewChange.insertion(item: t[tx], indexPath: makeIndexPath(forRow: tx, inSection: 0))
ins.append(insertion)
d[sx+1][tx+1] = ins
} else {
let deletion = TableViewChange.Deletion(item: s[sx], indexPath: makeIndexPath(forRow: sx, inSection: 0))
let insertion = TableViewChange.Insertion(item: t[tx], indexPath: makeIndexPath(forRow: tx, inSection: 0))
let deletion = TableViewChange.deletion(item: s[sx], indexPath: makeIndexPath(forRow: sx, inSection: 0))
let insertion = TableViewChange.insertion(item: t[tx], indexPath: makeIndexPath(forRow: tx, inSection: 0))
sub.append(deletion)
sub.append(insertion)
d[sx+1][tx+1] = sub
@@ -590,14 +590,14 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
}
}
/// Returns an array where deletion/insertion pairs of the same element are replaced by `.Move` change.
func standardizeChanges(changes: [TableViewChange<Record>]) -> [TableViewChange<Record>] {
/// Returns an array where deletion/insertion pairs of the same element are replaced by `.move` change.
func standardize(changes: [TableViewChange<Record>]) -> [TableViewChange<Record>] {
/// Returns a potential .Move or .Update if *change* has a matching change in *changes*:
/// Returns a potential .move or .update if *change* has a matching change in *changes*:
/// If *change* is a deletion or an insertion, and there is a matching inverse
/// insertion/deletion with the same value in *changes*, a corresponding .Move or .Update is returned.
/// insertion/deletion with the same value in *changes*, a corresponding .move or .update is returned.
/// As a convenience, the index of the matched change is returned as well.
func mergedChange(change: TableViewChange<Record>, inChanges changes: [TableViewChange<Record>]) -> (mergedChange: TableViewChange<Record>, mergedIndex: Int)? {
func merge(change: TableViewChange<Record>, in changes: [TableViewChange<Record>]) -> (mergedChange: TableViewChange<Record>, mergedIndex: Int)? {
/// Returns the changes between two rows: a dictionary [key: oldValue]
/// Precondition: both rows have the same columns
@@ -613,30 +613,30 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
}
switch change {
case .Insertion(let newItem, let newIndexPath):
case .insertion(let newItem, let newIndexPath):
// Look for a matching deletion
for (index, otherChange) in changes.enumerate() {
guard case .Deletion(let oldItem, let oldIndexPath) = otherChange else { continue }
for (index, otherChange) in changes.enumerated() {
guard case .deletion(let oldItem, let oldIndexPath) = otherChange else { continue }
guard isSameItem(oldItem, newItem) else { continue }
let rowChanges = changedValues(from: oldItem.row, to: newItem.row)
if oldIndexPath == newIndexPath {
return (TableViewChange.Update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index)
return (TableViewChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index)
} else {
return (TableViewChange.Move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index)
return (TableViewChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index)
}
}
return nil
case .Deletion(let oldItem, let oldIndexPath):
case .deletion(let oldItem, let oldIndexPath):
// Look for a matching insertion
for (index, otherChange) in changes.enumerate() {
guard case .Insertion(let newItem, let newIndexPath) = otherChange else { continue }
for (index, otherChange) in changes.enumerated() {
guard case .insertion(let newItem, let newIndexPath) = otherChange else { continue }
guard isSameItem(oldItem, newItem) else { continue }
let rowChanges = changedValues(from: oldItem.row, to: newItem.row)
if oldIndexPath == newIndexPath {
return (TableViewChange.Update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index)
return (TableViewChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index)
} else {
return (TableViewChange.Move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index)
return (TableViewChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index)
}
}
return nil
@@ -650,10 +650,10 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
var mergedChanges: [TableViewChange<Record>] = []
var updateChanges: [TableViewChange<Record>] = []
for change in changes {
if let (mergedChange, mergedIndex) = mergedChange(change, inChanges: mergedChanges) {
mergedChanges.removeAtIndex(mergedIndex)
if let (mergedChange, mergedIndex) = merge(change: change, in: mergedChanges) {
mergedChanges.remove(at: mergedIndex)
switch mergedChange {
case .Update:
case .update:
updateChanges.append(mergedChange)
default:
mergedChanges.append(mergedChange)
@@ -665,41 +665,41 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
return mergedChanges + updateChanges
}
return standardizeChanges(d[m][n])
return standardize(changes: d[m][n])
}
}
private enum TableViewChange<T: RowConvertible> {
case Insertion(item: Item<T>, indexPath: NSIndexPath)
case Deletion(item: Item<T>, indexPath: NSIndexPath)
case Move(item: Item<T>, indexPath: NSIndexPath, newIndexPath: NSIndexPath, changes: [String: DatabaseValue])
case Update(item: Item<T>, indexPath: NSIndexPath, changes: [String: DatabaseValue])
case insertion(item: Item<T>, indexPath: NSIndexPath)
case deletion(item: Item<T>, indexPath: NSIndexPath)
case move(item: Item<T>, indexPath: NSIndexPath, newIndexPath: NSIndexPath, changes: [String: DatabaseValue])
case update(item: Item<T>, indexPath: NSIndexPath, changes: [String: DatabaseValue])
}
extension TableViewChange {
var record: T {
switch self {
case .Insertion(item: let item, indexPath: _):
case .insertion(item: let item, indexPath: _):
return item.record
case .Deletion(item: let item, indexPath: _):
case .deletion(item: let item, indexPath: _):
return item.record
case .Move(item: let item, indexPath: _, newIndexPath: _, changes: _):
case .move(item: let item, indexPath: _, newIndexPath: _, changes: _):
return item.record
case .Update(item: let item, indexPath: _, changes: _):
case .update(item: let item, indexPath: _, changes: _):
return item.record
}
}
var event: TableViewEvent {
switch self {
case .Insertion(item: _, indexPath: let indexPath):
return .Insertion(indexPath: indexPath)
case .Deletion(item: _, indexPath: let indexPath):
return .Deletion(indexPath: indexPath)
case .Move(item: _, indexPath: let indexPath, newIndexPath: let newIndexPath, changes: let changes):
return .Move(indexPath: indexPath, newIndexPath: newIndexPath, changes: changes)
case .Update(item: _, indexPath: let indexPath, changes: let changes):
return .Update(indexPath: indexPath, changes: changes)
case .insertion(item: _, indexPath: let indexPath):
return .insertion(indexPath: indexPath)
case .deletion(item: _, indexPath: let indexPath):
return .deletion(indexPath: indexPath)
case .move(item: _, indexPath: let indexPath, newIndexPath: let newIndexPath, changes: let changes):
return .move(indexPath: indexPath, newIndexPath: newIndexPath, changes: changes)
case .update(item: _, indexPath: let indexPath, changes: let changes):
return .update(indexPath: indexPath, changes: changes)
}
}
}
@@ -707,16 +707,16 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
extension TableViewChange: CustomStringConvertible {
var description: String {
switch self {
case .Insertion(let item, let indexPath):
case .insertion(let item, let indexPath):
return "Insert \(item) at \(indexPath)"
case .Deletion(let item, let indexPath):
case .deletion(let item, let indexPath):
return "Delete \(item) from \(indexPath)"
case .Move(let item, let indexPath, let newIndexPath, changes: let changes):
case .move(let item, let indexPath, let newIndexPath, changes: let changes):
return "Move \(item) from \(indexPath) to \(newIndexPath) with changes: \(changes)"
case .Update(let item, let indexPath, let changes):
case .update(let item, let indexPath, let changes):
return "Update \(item) at \(indexPath) with changes: \(changes)"
}
}
@@ -729,20 +729,20 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
public enum TableViewEvent {
/// An insertion event, at given indexPath.
case Insertion(indexPath: NSIndexPath)
case insertion(indexPath: NSIndexPath)
/// A deletion event, at given indexPath.
case Deletion(indexPath: NSIndexPath)
case deletion(indexPath: NSIndexPath)
/// A move event, from indexPath to newIndexPath. The *changes* are a
/// dictionary whose keys are column names, and values the old values that
/// have been changed.
case Move(indexPath: NSIndexPath, newIndexPath: NSIndexPath, changes: [String: DatabaseValue])
case move(indexPath: NSIndexPath, newIndexPath: NSIndexPath, changes: [String: DatabaseValue])
/// An update event, at given indexPath. The *changes* are a dictionary
/// whose keys are column names, and values the old values that have
/// been changed.
case Update(indexPath: NSIndexPath, changes: [String: DatabaseValue])
case update(indexPath: NSIndexPath, changes: [String: DatabaseValue])
}
extension TableViewEvent: CustomStringConvertible {
@@ -750,16 +750,16 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
/// A textual representation of `self`.
public var description: String {
switch self {
case .Insertion(let indexPath):
case .insertion(let indexPath):
return "Insertion at \(indexPath)"
case .Deletion(let indexPath):
case .deletion(let indexPath):
return "Deletion from \(indexPath)"
case .Move(let indexPath, let newIndexPath, changes: let changes):
case .move(let indexPath, let newIndexPath, changes: let changes):
return "Move from \(indexPath) to \(newIndexPath) with changes: \(changes)"
case .Update(let indexPath, let changes):
case .update(let indexPath, let changes):
return "Update at \(indexPath) with changes: \(changes)"
}
}
@@ -791,12 +791,12 @@ private final class Item<T: RowConvertible> : RowConvertible, Equatable {
// TODO: Is is a good idea to lazily load records?
lazy var record: T = {
var record = T(self.row)
var record = T(row: self.row)
record.awakeFromFetch(row: self.row)
return record
}()
init(_ row: Row) {
init(row: Row) {
self.row = row.copy()
}
}
@@ -822,7 +822,7 @@ private func makeIndexPath(forRow row:Int, inSection section: Int) -> NSIndexPat
/// primaryKey(row) // ["id": 1]
///
/// - throws: A DatabaseError if table does not exist.
func makePrimaryKeyFunction(db: Database, tableName: String) throws -> (Row) -> [String: DatabaseValue] {
func makePrimaryKeyFunction(_ db: Database, tableName: String) throws -> (Row) -> [String: DatabaseValue] {
let columns = try db.primaryKey(tableName)?.columns ?? []
return { row in
return Dictionary<String, DatabaseValue>(keys: columns) { row.databaseValue(named: $0)! }
@@ -845,7 +845,7 @@ func makePrimaryKeyFunction(db: Database, tableName: String) throws -> (Row) ->
/// }
///
/// - throws: A DatabaseError if table does not exist.
func makePrimaryKeyComparator(db: Database, tableName: String) throws -> (Row, Row) -> Bool {
func makePrimaryKeyComparator(_ db: Database, tableName: String) throws -> (Row, Row) -> Bool {
let primaryKey = try makePrimaryKeyFunction(db, tableName: tableName)
return { (lhs, rhs) in
let (lhs, rhs) = (primaryKey(lhs), primaryKey(rhs))
+61 -61
View File
@@ -1,36 +1,36 @@
// MARK: - PersistenceError
/// An error thrown by a type that adopts Persistable.
public enum PersistenceError: ErrorType {
public enum PersistenceError: ErrorProtocol {
/// Thrown by MutablePersistable.update() when no matching row could be
/// found in the database.
case NotFound(MutablePersistable)
case recordNotFound(MutablePersistable)
}
extension PersistenceError : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch self {
case .NotFound(let persistable):
case .recordNotFound(let persistable):
return "Not found: \(persistable)"
}
}
}
private func databaseValue(forColumn column: String, inDictionary dictionary: [String: DatabaseValueConvertible?]) -> DatabaseValue {
private func databaseValue(for column: String, inDictionary dictionary: [String: DatabaseValueConvertible?]) -> DatabaseValue {
if let value = dictionary[column] {
return value?.databaseValue ?? .Null
return value?.databaseValue ?? .null
}
let column = column.lowercaseString
for (key, value) in dictionary where key.lowercaseString == column {
return value?.databaseValue ?? .Null
let column = column.lowercased()
for (key, value) in dictionary where key.lowercased() == column {
return value?.databaseValue ?? .null
}
return .Null
return .null
}
private func databaseValues(forColumns columns: [String], inDictionary dictionary: [String: DatabaseValueConvertible?]) -> [DatabaseValue] {
return columns.map { databaseValue(forColumn: $0, inDictionary: dictionary) }
private func databaseValues(for columns: [String], inDictionary dictionary: [String: DatabaseValueConvertible?]) -> [DatabaseValue] {
return columns.map { databaseValue(for: $0, inDictionary: dictionary) }
}
@@ -40,7 +40,7 @@ private func databaseValues(forColumns columns: [String], inDictionary dictionar
///
/// This protocol is intented for types that have an INTEGER PRIMARY KEY, and
/// are interested in the inserted RowID: they can mutate themselves upon
/// successful insertion with the didInsertWithRowID(_:forColumn:) method.
/// successful insertion with the didInsert(with:for:) method.
///
/// The insert() and save() methods are mutating methods.
public protocol MutablePersistable : TableMapping {
@@ -74,7 +74,7 @@ public protocol MutablePersistable : TableMapping {
/// var id: Int64?
/// var name: String?
///
/// mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
/// mutating func didInsert(with rowID: Int64, for column: String?) {
/// self.id = rowID
/// }
/// }
@@ -82,7 +82,7 @@ public protocol MutablePersistable : TableMapping {
/// - parameters:
/// - rowID: The inserted rowID.
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?)
mutating func didInsert(with rowID: Int64, for column: String?)
// MARK: - CRUD
@@ -92,7 +92,7 @@ public protocol MutablePersistable : TableMapping {
/// This method is guaranteed to have inserted a row in the database if it
/// returns without error.
///
/// Upon successful insertion, the didInsertWithRowID(:forColumn:) method
/// Upon successful insertion, the didInsert(with:for:) method
/// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY
/// column name.
///
@@ -103,7 +103,7 @@ public protocol MutablePersistable : TableMapping {
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs.
mutating func insert(db: Database) throws
mutating func insert(_ db: Database) throws
/// Executes an UPDATE statement.
///
@@ -117,9 +117,9 @@ public protocol MutablePersistable : TableMapping {
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.NotFound is thrown if the primary key does not
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database.
func update(db: Database) throws
func update(_ db: Database) throws
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
@@ -140,7 +140,7 @@ public protocol MutablePersistable : TableMapping {
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs, or errors
/// thrown by update().
mutating func save(db: Database) throws
mutating func save(_ db: Database) throws
/// Executes a DELETE statement.
///
@@ -152,7 +152,7 @@ public protocol MutablePersistable : TableMapping {
/// - parameter db: A database connection.
/// - returns: Whether a database row was deleted.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
func delete(db: Database) throws -> Bool
func delete(_ db: Database) throws -> Bool
/// Returns true if and only if the primary key matches a row in
/// the database.
@@ -164,7 +164,7 @@ public protocol MutablePersistable : TableMapping {
///
/// - parameter db: A database connection.
/// - returns: Whether the primary key matches a row in the database.
func exists(db: Database) -> Bool
func exists(_ db: Database) -> Bool
}
public extension MutablePersistable {
@@ -172,7 +172,7 @@ public extension MutablePersistable {
/// Notifies the record that it was succesfully inserted.
///
/// The default implementation does nothing.
mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
mutating func didInsert(with rowID: Int64, for column: String?) {
}
@@ -181,14 +181,14 @@ public extension MutablePersistable {
/// Executes an INSERT statement.
///
/// The default implementation for insert() invokes performInsert().
mutating func insert(db: Database) throws {
mutating func insert(_ db: Database) throws {
try performInsert(db)
}
/// Executes an UPDATE statement.
///
/// The default implementation for update() invokes performUpdate().
func update(db: Database) throws {
func update(_ db: Database) throws {
try performUpdate(db)
}
@@ -196,14 +196,14 @@ public extension MutablePersistable {
/// the database.
///
/// The default implementation for save() invokes performSave().
mutating func save(db: Database) throws {
mutating func save(_ db: Database) throws {
try performSave(db)
}
/// Executes a DELETE statement.
///
/// The default implementation for delete() invokes performDelete().
func delete(db: Database) throws -> Bool {
func delete(_ db: Database) throws -> Bool {
return try performDelete(db)
}
@@ -211,14 +211,14 @@ public extension MutablePersistable {
/// the database.
///
/// The default implementation for exists() invokes performExists().
func exists(db: Database) -> Bool {
func exists(_ db: Database) -> Bool {
return performExists(db)
}
// MARK: - CRUD Internals
private func canUpdateInDatabase(db: Database) -> Bool {
private func canUpdate(_ db: Database) -> Bool {
// Fail early if database table does not exist.
let databaseTableName = self.dynamicType.databaseTableName()
guard let primaryKey = try! db.primaryKey(databaseTableName) else {
@@ -226,7 +226,7 @@ public extension MutablePersistable {
}
let persistentDictionary = self.persistentDictionary
for column in primaryKey.columns where !databaseValue(forColumn: column, inDictionary: persistentDictionary).isNull {
for column in primaryKey.columns where !databaseValue(for: column, inDictionary: persistentDictionary).isNull {
return true
}
return false
@@ -239,10 +239,10 @@ public extension MutablePersistable {
/// that adopt MutablePersistable can invoke performInsert() in their
/// implementation of insert(). They should not provide their own
/// implementation of performInsert().
mutating func performInsert(db: Database) throws {
mutating func performInsert(_ db: Database) throws {
let dataMapper = DataMapper(db, self)
try dataMapper.insertStatement().execute()
didInsertWithRowID(db.lastInsertedRowID, forColumn: dataMapper.primaryKey?.rowIDColumn)
didInsert(with: db.lastInsertedRowID, for: dataMapper.primaryKey?.rowIDColumn)
}
/// Don't invoke this method directly: it is an internal method for types
@@ -252,10 +252,10 @@ public extension MutablePersistable {
/// that adopt MutablePersistable can invoke performUpdate() in their
/// implementation of update(). They should not provide their own
/// implementation of performUpdate().
func performUpdate(db: Database) throws {
func performUpdate(_ db: Database) throws {
try DataMapper(db, self).updateStatement().execute()
if db.changesCount == 0 {
throw PersistenceError.NotFound(self)
throw PersistenceError.recordNotFound(self)
}
}
@@ -268,15 +268,15 @@ public extension MutablePersistable {
/// implementation of performSave().
///
/// This default implementation forwards the job to `update` or `insert`.
mutating func performSave(db: Database) throws {
mutating func performSave(_ db: Database) throws {
// Make sure we call self.insert and self.update so that classes
// that override insert or save have opportunity to perform their
// custom job.
if self.canUpdateInDatabase(db) {
if self.canUpdate(db) {
do {
try update(db)
} catch PersistenceError.NotFound {
} catch PersistenceError.recordNotFound {
// TODO: check that the not persisted objet is self
//
// Why? Adopting types could override update() and update
@@ -295,7 +295,7 @@ public extension MutablePersistable {
/// that adopt MutablePersistable can invoke performDelete() in
/// their implementation of delete(). They should not provide their own
/// implementation of performDelete().
func performDelete(db: Database) throws -> Bool {
func performDelete(_ db: Database) throws -> Bool {
try DataMapper(db, self).deleteStatement().execute()
return db.changesCount > 0
}
@@ -307,7 +307,7 @@ public extension MutablePersistable {
/// that adopt MutablePersistable can invoke performExists() in
/// their implementation of exists(). They should not provide their own
/// implementation of performExists().
func performExists(db: Database) -> Bool {
func performExists(_ db: Database) -> Bool {
return (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil)
}
@@ -338,14 +338,14 @@ public protocol Persistable : MutablePersistable {
/// - parameters:
/// - rowID: The inserted rowID.
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
func didInsertWithRowID(rowID: Int64, forColumn column: String?)
func didInsert(with rowID: Int64, for column: String?)
/// Executes an INSERT statement.
///
/// This method is guaranteed to have inserted a row in the database if it
/// returns without error.
///
/// Upon successful insertion, the didInsertWithRowID(:forColumn:) method
/// Upon successful insertion, the didInsert(with:for:) method
/// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY
/// column name.
///
@@ -356,7 +356,7 @@ public protocol Persistable : MutablePersistable {
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs.
func insert(db: Database) throws
func insert(_ db: Database) throws
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
@@ -377,7 +377,7 @@ public protocol Persistable : MutablePersistable {
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs, or errors
/// thrown by update().
func save(db: Database) throws
func save(_ db: Database) throws
}
public extension Persistable {
@@ -385,7 +385,7 @@ public extension Persistable {
/// Notifies the record that it was succesfully inserted.
///
/// The default implementation does nothing.
func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
func didInsert(with rowID: Int64, for column: String?) {
}
// MARK: - Immutable CRUD
@@ -393,7 +393,7 @@ public extension Persistable {
/// Executes an INSERT statement.
///
/// The default implementation for insert() invokes performInsert().
func insert(db: Database) throws {
func insert(_ db: Database) throws {
try performInsert(db)
}
@@ -401,7 +401,7 @@ public extension Persistable {
/// the database.
///
/// The default implementation for save() invokes performSave().
func save(db: Database) throws {
func save(_ db: Database) throws {
try performSave(db)
}
@@ -415,10 +415,10 @@ public extension Persistable {
/// that adopt Persistable can invoke performInsert() in their
/// implementation of insert(). They should not provide their own
/// implementation of performInsert().
func performInsert(db: Database) throws {
func performInsert(_ db: Database) throws {
let dataMapper = DataMapper(db, self)
try dataMapper.insertStatement().execute()
didInsertWithRowID(db.lastInsertedRowID, forColumn: dataMapper.primaryKey?.rowIDColumn)
didInsert(with: db.lastInsertedRowID, for: dataMapper.primaryKey?.rowIDColumn)
}
/// Don't invoke this method directly: it is an internal method for types
@@ -430,14 +430,14 @@ public extension Persistable {
/// implementation of performSave().
///
/// This default implementation forwards the job to `update` or `insert`.
func performSave(db: Database) throws {
func performSave(_ db: Database) throws {
// Make sure we call self.insert and self.update so that classes that
// override insert or save have opportunity to perform their custom job.
if canUpdateInDatabase(db) {
if canUpdate(db) {
do {
try update(db)
} catch PersistenceError.NotFound {
} catch PersistenceError.recordNotFound {
// TODO: check that the not persisted objet is self
//
// Why? Adopting types could override update() and update another
@@ -502,23 +502,23 @@ final class DataMapper {
func updateStatement() -> UpdateStatement {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey?.columns ?? []
let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary)
let primaryKeyValues = databaseValues(for: primaryKeyColumns, inDictionary: persistentDictionary)
GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "invalid primary key in \(persistable)")
// Update everything but primary key
var updatedColumns = persistentDictionary.keys.removingElementsOf(primaryKeyColumns)
var updatedColumns = persistentDictionary.keys.removing(contentsOf: primaryKeyColumns)
if updatedColumns.isEmpty {
// IMPLEMENTATION NOTE
//
// It is important to update something, so that
// TransactionObserverType can observe a change even though this
// TransactionObserver can observe a change even though this
// change is useless.
//
// The goal is to be able to write tests with minimal tables,
// including tables made of a single primary key column.
updatedColumns = primaryKeyColumns
}
let updatedValues = databaseValues(forColumns: updatedColumns, inDictionary: persistentDictionary)
let updatedValues = databaseValues(for: updatedColumns, inDictionary: persistentDictionary)
let query = UpdateQuery(
tableName: databaseTableName,
@@ -532,7 +532,7 @@ final class DataMapper {
func deleteStatement() -> UpdateStatement {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey?.columns ?? []
let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary)
let primaryKeyValues = databaseValues(for: primaryKeyColumns, inDictionary: persistentDictionary)
GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "invalid primary key in \(persistable)")
let query = DeleteQuery(
@@ -546,7 +546,7 @@ final class DataMapper {
func existsStatement() -> SelectStatement {
// Fail early if primary key does not resolve to a database row.
let primaryKeyColumns = primaryKey?.columns ?? []
let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary)
let primaryKeyValues = databaseValues(for: primaryKeyColumns, inDictionary: persistentDictionary)
GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "invalid primary key in \(persistable)")
let query = ExistsQuery(
@@ -581,7 +581,7 @@ extension InsertQuery {
if let sql = InsertQuery.sqlCache.read({ $0[self] }) {
return sql
}
let columnsSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joinWithSeparator(",")
let columnsSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ",")
let valuesSQL = databaseQuestionMarks(count: insertedColumns.count)
let sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))"
InsertQuery.sqlCache.write { $0[self] = sql }
@@ -614,8 +614,8 @@ extension UpdateQuery {
if let sql = UpdateQuery.sqlCache.read({ $0[self] }) {
return sql
}
let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(",")
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(" AND ")
let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ",")
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ")
let sql = "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)"
UpdateQuery.sqlCache.write { $0[self] = sql }
return sql
@@ -632,7 +632,7 @@ private struct DeleteQuery {
extension DeleteQuery {
var sql: String {
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(" AND ")
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ")
return "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)"
}
}
@@ -647,7 +647,7 @@ private struct ExistsQuery {
extension ExistsQuery {
var sql: String {
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joinWithSeparator(" AND ")
let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ")
return "SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)"
}
}
+22 -22
View File
@@ -19,7 +19,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
/// The input row may not come straight from the database. When you want to
/// complete your initialization after being fetched, override
/// awakeFromFetch(row:).
required public init(_ row: Row) {
required public init(row: Row) {
}
/// Do not call this method directly.
@@ -30,7 +30,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
/// Record subclasses have an opportunity to complete their initialization.
///
/// *Important*: subclasses must invoke super's implementation.
public func awakeFromFetch(row row: Row) {
public func awakeFromFetch(row: Row) {
// Take care of the hasPersistentChangedValues flag. If the row does not
/// contain all needed columns, the record turns edited.
//
@@ -93,7 +93,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
/// var id: Int64?
/// var name: String?
///
/// func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
/// func didInsert(with rowID: Int64, for column: String?) {
/// id = rowID
/// }
/// }
@@ -101,7 +101,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
/// - parameters:
/// - rowID: The inserted rowID.
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
public func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
public func didInsert(with rowID: Int64, for column: String?) {
}
@@ -116,7 +116,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
/// - returns: A copy of self.
@warn_unused_result
public func copy() -> Self {
let copy = self.dynamicType.init(Row(persistentDictionary))
let copy = self.dynamicType.init(row: Row(persistentDictionary))
copy.referenceRow = referenceRow
return copy
}
@@ -140,7 +140,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
/// false does not prevent it from turning true on subsequent modifications
/// of the record.
public var hasPersistentChangedValues: Bool {
get { return generatePersistentChangedValues().next() != nil }
get { return makePersistentChangedValuesIterator().next() != nil }
set { referenceRow = newValue ? nil : Row(persistentDictionary) }
}
@@ -156,21 +156,21 @@ public class Record : RowConvertible, TableMapping, Persistable {
public var persistentChangedValues: [String: DatabaseValue?] {
var persistentChangedValues: [String: DatabaseValue?] = [:]
for (key, value) in generatePersistentChangedValues() {
for (key, value) in makePersistentChangedValuesIterator() {
persistentChangedValues[key] = value
}
return persistentChangedValues
}
// A change generator that is used by both hasPersistentChangedValues and
// A change iterator that is used by both hasPersistentChangedValues and
// persistentChangedValues properties.
private func generatePersistentChangedValues() -> AnyGenerator<(column: String, old: DatabaseValue?)> {
private func makePersistentChangedValuesIterator() -> AnyIterator<(column: String, old: DatabaseValue?)> {
let oldRow = referenceRow
var newValueGenerator = persistentDictionary.generate()
return AnyGenerator {
var newValueIterator = persistentDictionary.makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueGenerator.next() {
let new = newValue?.databaseValue ?? .Null
while let (column, newValue) = newValueIterator.next() {
let new = newValue?.databaseValue ?? .null
guard let old = oldRow?.databaseValue(named: column) else {
return (column: column, old: nil)
}
@@ -203,7 +203,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func insert(db: Database) throws {
public func insert(_ db: Database) throws {
// The simplest code would be:
//
// try performInsert(db)
@@ -221,7 +221,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
try dataMapper.insertStatement().execute()
let rowID = db.lastInsertedRowID
let rowIDColumn = dataMapper.primaryKey?.rowIDColumn
didInsertWithRowID(rowID, forColumn: rowIDColumn)
didInsert(with: rowID, for: rowIDColumn)
// Update persistentDictionary with inserted id, so that we can
// set hasPersistentChangedValues to false:
@@ -229,8 +229,8 @@ public class Record : RowConvertible, TableMapping, Persistable {
if persistentDictionary[rowIDColumn] != nil {
persistentDictionary[rowIDColumn] = rowID
} else {
let rowIDColumn = rowIDColumn.lowercaseString
for column in persistentDictionary.keys where column.lowercaseString == rowIDColumn {
let rowIDColumn = rowIDColumn.lowercased()
for column in persistentDictionary.keys where column.lowercased() == rowIDColumn {
persistentDictionary[column] = rowID
break
}
@@ -251,9 +251,9 @@ public class Record : RowConvertible, TableMapping, Persistable {
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.NotFound is thrown if the primary key does not match
/// PersistenceError.recordNotFound is thrown if the primary key does not match
/// any row in the database and record could not be updated.
public func update(db: Database) throws {
public func update(_ db: Database) throws {
// The simplest code would be:
//
// try performUpdate(db)
@@ -268,7 +268,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
let dataMapper = DataMapper(db, self)
try dataMapper.updateStatement().execute()
if db.changesCount == 0 {
throw PersistenceError.NotFound(self)
throw PersistenceError.recordNotFound(self)
}
// Set hasPersistentChangedValues to false
@@ -292,7 +292,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs, or errors
/// thrown by update().
final public func save(db: Database) throws {
final public func save(_ db: Database) throws {
try performSave(db)
}
@@ -304,7 +304,7 @@ public class Record : RowConvertible, TableMapping, Persistable {
/// - parameter db: A database connection.
/// - returns: Whether a database row was deleted.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func delete(db: Database) throws -> Bool {
public func delete(_ db: Database) throws -> Bool {
defer {
// Future calls to update() will throw NotFound. Make the user
// a favor and make sure this error is thrown even if she checks the
+18 -18
View File
@@ -10,7 +10,7 @@
/// Person.fetchAll(db, "SELECT ...", arguments:...) // [Person]
/// Person.fetchOne(db, "SELECT ...", arguments:...) // Person?
///
/// let statement = db.selectStatement("SELECT ...")
/// let statement = db.makeSelectStatement("SELECT ...")
/// Person.fetch(statement, arguments:...) // DatabaseSequence<Person>
/// Person.fetchAll(statement, arguments:...) // [Person]
/// Person.fetchOne(statement, arguments:...) // Person?
@@ -23,7 +23,7 @@ public protocol RowConvertible {
/// For performance reasons, the row argument may be reused during the
/// iteration of a fetch query. If you want to keep the row for later use,
/// make sure to store a copy: `self.row = row.copy()`.
init(_ row: Row)
init(row: Row)
/// Do not call this method directly.
///
@@ -32,20 +32,20 @@ public protocol RowConvertible {
///
/// Types that adopt RowConvertible have an opportunity to complete their
/// initialization.
mutating func awakeFromFetch(row row: Row)
mutating func awakeFromFetch(row: Row)
}
extension RowConvertible {
/// Default implementation, which does nothing.
public func awakeFromFetch(row row: Row) { }
public func awakeFromFetch(row: Row) { }
// MARK: - Fetching From SelectStatement
/// Returns a sequence of records fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT * FROM persons")
/// let statement = db.makeSelectStatement("SELECT * FROM persons")
/// let persons = Person.fetch(statement) // DatabaseSequence<Person>
///
/// The returned sequence can be consumed several times, but it may yield
@@ -66,10 +66,10 @@ extension RowConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A sequence of records.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
let row = try! Row(statement: statement).adaptedRow(adapter: adapter, statement: statement)
return statement.fetchSequence(arguments: arguments) {
var value = self.init(row)
var value = self.init(row: row)
value.awakeFromFetch(row: row)
return value
}
@@ -77,7 +77,7 @@ extension RowConvertible {
/// Returns an array of records fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT * FROM persons")
/// let statement = db.makeSelectStatement("SELECT * FROM persons")
/// let persons = Person.fetchAll(statement) // [Person]
///
/// - parameters:
@@ -86,13 +86,13 @@ extension RowConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> [Self] {
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> [Self] {
return Array(fetch(statement, arguments: arguments, adapter: adapter))
}
/// Returns a single record fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT * FROM persons")
/// let statement = db.makeSelectStatement("SELECT * FROM persons")
/// let person = Person.fetchOne(statement) // Person?
///
/// - parameters:
@@ -101,8 +101,8 @@ extension RowConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
@warn_unused_result
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Self? {
return fetch(statement, arguments: arguments, adapter: adapter).generate().next()
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Self? {
return fetch(statement, arguments: arguments, adapter: adapter).makeIterator().next()
}
@@ -131,8 +131,8 @@ extension RowConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A sequence of records.
@warn_unused_result
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
return fetch(try! db.selectStatement(sql), arguments: arguments, adapter: adapter)
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> DatabaseSequence<Self> {
return fetch(try! db.makeSelectStatement(sql), arguments: arguments, adapter: adapter)
}
/// Returns an array of records fetched from an SQL query.
@@ -146,8 +146,8 @@ extension RowConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
@warn_unused_result
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> [Self] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments, adapter: adapter)
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> [Self] {
return fetchAll(try! db.makeSelectStatement(sql), arguments: arguments, adapter: adapter)
}
/// Returns a single record fetched from an SQL query.
@@ -161,7 +161,7 @@ extension RowConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
@warn_unused_result
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Self? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments, adapter: adapter)
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Self? {
return fetchOne(try! db.makeSelectStatement(sql), arguments: arguments, adapter: adapter)
}
}
+17 -17
View File
@@ -28,9 +28,9 @@ extension RowConvertible where Self: TableMapping {
/// - keys: A sequence of primary keys.
/// - returns: A sequence of records.
@warn_unused_result
public static func fetch<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(db: Database, keys: Sequence) -> DatabaseSequence<Self> {
public static func fetch<Sequence: Swift.Sequence where Sequence.Iterator.Element: DatabaseValueConvertible>(_ db: Database, keys: Sequence) -> DatabaseSequence<Self> {
guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else {
return DatabaseSequence.emptySequence(db)
return DatabaseSequence.makeEmptySequence(inDatabase: db)
}
return fetch(statement)
}
@@ -46,7 +46,7 @@ extension RowConvertible where Self: TableMapping {
/// - keys: A sequence of primary keys.
/// - returns: An array of records.
@warn_unused_result
public static func fetchAll<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(db: Database, keys: Sequence) -> [Self] {
public static func fetchAll<Sequence: Swift.Sequence where Sequence.Iterator.Element: DatabaseValueConvertible>(_ db: Database, keys: Sequence) -> [Self] {
guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else {
return []
}
@@ -62,7 +62,7 @@ extension RowConvertible where Self: TableMapping {
/// - key: A primary key value.
/// - returns: An optional record.
@warn_unused_result
public static func fetchOne<PrimaryKeyType: DatabaseValueConvertible>(db: Database, key: PrimaryKeyType?) -> Self? {
public static func fetchOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) -> Self? {
guard let key = key else {
return nil
}
@@ -73,7 +73,7 @@ extension RowConvertible where Self: TableMapping {
//
// Returns nil if values is empty.
@warn_unused_result
private static func fetchByPrimaryKeyStatement<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(db: Database, values: Sequence) -> SelectStatement? {
private static func fetchByPrimaryKeyStatement<Sequence: Swift.Sequence where Sequence.Iterator.Element: DatabaseValueConvertible>(_ db: Database, values: Sequence) -> SelectStatement? {
// Fail early if database table does not exist.
let databaseTableName = self.databaseTableName()
let primaryKey = try! db.primaryKey(databaseTableName)
@@ -91,14 +91,14 @@ extension RowConvertible where Self: TableMapping {
case 1:
// SELECT * FROM table WHERE id = ?
let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
let statement = try! db.selectStatement(sql)
let statement = try! db.makeSelectStatement(sql)
statement.arguments = StatementArguments(values)
return statement
case let count:
// SELECT * FROM table WHERE id IN (?,?,?)
let valuesSQL = databaseQuestionMarks(count: count)
let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(valuesSQL))"
let statement = try! db.selectStatement(sql)
let statement = try! db.makeSelectStatement(sql)
statement.arguments = StatementArguments(values)
return statement
}
@@ -118,9 +118,9 @@ extension RowConvertible where Self: TableMapping {
/// - keys: An array of key dictionaries.
/// - returns: A sequence of records.
@warn_unused_result
public static func fetch(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> DatabaseSequence<Self> {
public static func fetch(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> DatabaseSequence<Self> {
guard let statement = fetchByKeyStatement(db, keys: keys) else {
return DatabaseSequence.emptySequence(db)
return DatabaseSequence.makeEmptySequence(inDatabase: db)
}
return fetch(statement)
}
@@ -136,7 +136,7 @@ extension RowConvertible where Self: TableMapping {
/// - keys: An array of key dictionaries.
/// - returns: An array of records.
@warn_unused_result
public static func fetchAll(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> [Self] {
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> [Self] {
guard let statement = fetchByKeyStatement(db, keys: keys) else {
return []
}
@@ -152,7 +152,7 @@ extension RowConvertible where Self: TableMapping {
/// - key: A dictionary of values.
/// - returns: An optional record.
@warn_unused_result
public static func fetchOne(db: Database, key: [String: DatabaseValueConvertible?]) -> Self? {
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) -> Self? {
return fetchOne(fetchByKeyStatement(db, keys: [key])!)
}
@@ -160,10 +160,10 @@ extension RowConvertible where Self: TableMapping {
//
// Returns nil if keys is empty.
@warn_unused_result
private static func fetchByKeyStatement(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> SelectStatement? {
private static func fetchByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> SelectStatement? {
// TODO: this method is slow to compile
// https://medium.com/swift-programming/speeding-up-slow-swift-build-times-922feeba5780#.s77wmh4h0
// 586.8ms /Users/groue/Documents/git/groue/GRDB.swift/GRDB/Record/TableMapping.swift:163:25 @warn_unused_result private static func fetchByKeyStatement(db: Database, keys: [[String : DatabaseValueConvertible?]]) -> SelectStatement?
// 586.8ms /Users/groue/Documents/git/groue/GRDB.swift/GRDB/Record/TableMapping.swift:163:25 @warn_unused_result private static func fetchByKeyStatement(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) -> SelectStatement?
// Avoid performing useless SELECT
guard keys.count > 0 else {
@@ -174,14 +174,14 @@ extension RowConvertible where Self: TableMapping {
var whereClauses: [String] = []
for dictionary in keys {
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
arguments.appendContentsOf(dictionary.values)
whereClauses.append("(" + dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" }.joinWithSeparator(" AND ") + ")")
arguments.append(contentsOf: dictionary.values)
whereClauses.append("(" + dictionary.keys.map { "\($0.quotedDatabaseIdentifier) = ?" }.joined(separator: " AND ") + ")")
}
let databaseTableName = self.databaseTableName()
let whereClause = whereClauses.joinWithSeparator(" OR ")
let whereClause = whereClauses.joined(separator: " OR ")
let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
let statement = try! db.selectStatement(sql)
let statement = try! db.makeSelectStatement(sql)
statement.arguments = StatementArguments(arguments)
return statement
}
@@ -29,7 +29,7 @@ struct DatabaseTimestamp: DatabaseValueConvertible {
}
/// Returns a value initialized from *databaseValue*, if possible.
static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseTimestamp? {
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseTimestamp? {
// Double itself adopts DatabaseValueConvertible:
guard let timeInterval = Double.fromDatabaseValue(databaseValue) else {
// No Double, no NSDate!
@@ -59,4 +59,3 @@ try! dbQueue.inDatabase { db in
let date = (row.value(named: "date") as DatabaseTimestamp).date
print("timestamp: \(timestamp)")
print("date: \(date)")
}
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>
@@ -48,17 +48,17 @@ class Person : Record {
return "persons"
}
required init(_ row: Row) {
required init(row: Row) {
id = row.value(named: "id")
name = row.value(named: "name")
super.init(row)
super.init(row: row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["id": id, "name": name]
}
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
@@ -66,7 +66,7 @@ class Person : Record {
// Synchronizes the persons table with a JSON payload
func synchronizePersonsWithJSON(jsonString: String, inDatabase db: Database) throws {
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
let jsonData = jsonString.data(using: NSUTF8StringEncoding)!
let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! NSDictionary
// A support function that extracts an ID from a JSON person.
@@ -75,7 +75,7 @@ func synchronizePersonsWithJSON(jsonString: String, inDatabase db: Database) thr
}
// Sort JSON persons by id:
let jsonPersons = (json["persons"] as! [NSDictionary]).sort {
let jsonPersons = (json["persons"] as! [NSDictionary]).sorted {
return jsonPersonId($0) < jsonPersonId($1)
}
@@ -94,15 +94,15 @@ func synchronizePersonsWithJSON(jsonString: String, inDatabase db: Database) thr
rightKey: jsonPersonId) // The id of a JSON person
{
switch mergeStep {
case .Left(let person):
case .left(let person):
// Delete database person without matching JSON person:
try person.delete(db)
case .Right(let jsonPerson):
case .right(let jsonPerson):
// Insert JSON person without matching database person:
let row = Row(jsonPerson)! // Granted JSON keys are database columns
let person = Person(row)
try person.insert(db)
case .Common(let person, let jsonPerson):
case .common(let person, let jsonPerson):
// Update database person with its JSON counterpart:
person.updateFromJSON(jsonPerson)
if person.hasPersistentChangedValues {
@@ -127,7 +127,7 @@ do {
// INSERT INTO "persons" ("id","name") VALUES (2,'Barbara')
// INSERT INTO "persons" ("id","name") VALUES (3,'Craig')
try synchronizePersonsWithJSON(jsonString, inDatabase: db)
return .Commit
return .commit
}
}
@@ -146,6 +146,6 @@ do {
// UPDATE "persons" SET "name"='Barbie' WHERE "id"=2
// INSERT INTO "persons" ("id","name") VALUES (4,'Daniel')
try synchronizePersonsWithJSON(jsonString, inDatabase: db)
return .Commit
return .commit
}
}
@@ -24,11 +24,11 @@
/// rightKey: { Int($0)! })
/// {
/// switch mergeStep {
/// case .Left(let left):
/// case .left(let left):
/// print("- Left: \(left)")
/// case .Right(let right):
/// case .right(let right):
/// print("- Right: \(right)")
/// case .Common(let left, let right):
/// case .common(let left, let right):
/// print("- Common: \(left), \(right)")
/// }
/// }
@@ -39,35 +39,35 @@
/// - leftKey: A function that returns the key of a left element.
/// - rightKey: A function that returns the key of a right element.
/// - returns: A sequence of MergeStep
public func sortedMerge<LeftSequence: SequenceType, RightSequence: SequenceType, Key: Comparable>(
public func sortedMerge<LeftSequence: Sequence, RightSequence: Sequence, Key: Comparable>(
left lSeq: LeftSequence,
right rSeq: RightSequence,
leftKey: LeftSequence.Generator.Element -> Key,
rightKey: RightSequence.Generator.Element -> Key) -> AnySequence<MergeStep<LeftSequence.Generator.Element, RightSequence.Generator.Element>>
leftKey: (LeftSequence.Iterator.Element) -> Key,
rightKey: (RightSequence.Iterator.Element) -> Key) -> AnySequence<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>>
{
return AnySequence { () -> AnyGenerator<MergeStep<LeftSequence.Generator.Element, RightSequence.Generator.Element>> in
var (lGen, rGen) = (lSeq.generate(), rSeq.generate())
return AnySequence { () -> AnyIterator<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>> in
var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator())
var (lOpt, rOpt) = (lGen.next(), rGen.next())
return AnyGenerator {
return AnyIterator {
switch (lOpt, rOpt) {
case (let lElem?, let rElem?):
let (lKey, rKey) = (leftKey(lElem), rightKey(rElem))
if lKey > rKey {
rOpt = rGen.next()
return .Right(rElem)
return .right(rElem)
} else if lKey == rKey {
(lOpt, rOpt) = (lGen.next(), rGen.next())
return .Common(lElem, rElem)
return .common(lElem, rElem)
} else {
lOpt = lGen.next()
return .Left(lElem)
return .left(lElem)
}
case (nil, let rElem?):
rOpt = rGen.next()
return .Right(rElem)
return .right(rElem)
case (let lElem?, nil):
lOpt = lGen.next()
return .Left(lElem)
return .left(lElem)
case (nil, nil):
return nil
}
@@ -80,9 +80,9 @@ public func sortedMerge<LeftSequence: SequenceType, RightSequence: SequenceType,
*/
public enum MergeStep<LeftElement, RightElement> {
/// An element only found in the left sequence:
case Left(LeftElement)
case left(LeftElement)
/// An element only found in the right sequence:
case Right(RightElement)
case right(RightElement)
/// Left and right elements share a common key:
case Common(LeftElement, RightElement)
case common(LeftElement, RightElement)
}
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>
+4 -4
View File
@@ -38,7 +38,7 @@ class Person : Record {
var lastName: String?
var fullName: String {
return [firstName, lastName].flatMap { $0 }.joinWithSeparator(" ")
return [firstName, lastName].flatMap { $0 }.joined(separator: " ")
}
init(firstName: String?, lastName: String?) {
@@ -59,11 +59,11 @@ class Person : Record {
//: 2. How to build a Person from a database row:
required init(_ row: Row) {
required init(row: Row) {
id = row.value(named: "id")
firstName = row.value(named: "firstName")
lastName = row.value(named: "lastName")
super.init(row)
super.init(row: row)
}
//: 3. The dictionary of values that are stored in the database:
@@ -74,7 +74,7 @@ class Person : Record {
//: 4. When relevant, update the person's id after a database row has been inserted:
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
+2 -2
View File
@@ -65,7 +65,7 @@ struct PointOfInterest {
// Adopt RowConvertible
extension PointOfInterest : RowConvertible {
init(_ row: Row) {
init(row: Row) {
id = row.value(named: "id")
title = row.value(named: "title")
favorite = row.value(named: "favorite")
@@ -94,7 +94,7 @@ extension PointOfInterest : MutablePersistable {
]
}
mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
@@ -29,22 +29,22 @@ try! migrator.migrate(dbQueue)
/// TableChangeObserver prints on the main thread the changes database tables.
class TableChangeObserver : NSObject, TransactionObserverType {
class TableChangeObserver : NSObject, TransactionObserver {
private var changedTableNames: Set<String> = []
func databaseDidChangeWithEvent(event: DatabaseEvent) {
func databaseDidChange(with event: DatabaseEvent) {
changedTableNames.insert(event.tableName)
}
func databaseWillCommit() throws {
}
func databaseDidCommit(db: Database) {
print("Changed table(s): \(changedTableNames.joinWithSeparator(", "))")
func databaseDidCommit(_ db: Database) {
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
changedTableNames = []
}
func databaseDidRollback(db: Database) {
func databaseDidRollback(_ db: Database) {
changedTableNames = []
}
}
@@ -54,7 +54,7 @@ class TableChangeObserver : NSObject, TransactionObserverType {
// Register observer
let observer = TableChangeObserver()
dbQueue.addTransactionObserver(observer)
dbQueue.add(transactionObserver: observer)
//
@@ -71,7 +71,7 @@ print("-- Changes 2")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES ('Arthur')")
try db.execute("INSERT INTO persons (name) VALUES ('Barbara')")
return .Rollback
return .rollback
}
@@ -18,7 +18,7 @@ public class UserDefaults {
private static var registeredDefaults: [UserDefaults] = []
/// Returns the defaults for the database
public static func inDatabase(db: Database) -> UserDefaults {
public static func inDatabase(_ db: Database) -> UserDefaults {
registeredDefaults = registeredDefaults.filter { $0.db != nil }
for defaults in registeredDefaults where defaults.db === db { return defaults }
let defaults = UserDefaults(db: db)
@@ -26,7 +26,7 @@ public class UserDefaults {
return defaults
}
private init(db: Database) {
private init(_ db: Database) {
self.db = db
}
@@ -143,7 +143,7 @@ private struct UserDefaultsItem {
}
extension UserDefaultsItem: RowConvertible {
init(_ row: Row) {
init(row: Row) {
let data = row.dataNoCopy(named: "value")!
let value = try! NSPropertyListSerialization.propertyListWithData(data, options: .Immutable, format: nil)
self.key = row.value(named: "key")
+123 -127
View File
@@ -66,7 +66,7 @@ try dbQueue.inDatabase { db in
dbQueue.inDatabase { db in
for row in Row.fetch(db, "SELECT * FROM pointOfInterests") {
let title: String = row.value(named: "title")
let favorite: Bool = row.value(named: "favorite")
let isFavorite: Bool = row.value(named: "favorite")
let coordinate = CLLocationCoordinate2DMake(
row.value(named: "latitude"),
row.value(named: "longitude"))
@@ -88,7 +88,7 @@ Insert and fetch [records](#records):
struct PointOfInterest {
var id: Int64?
var title: String?
var favorite: Bool
var isFavorite: Bool
var coordinate: CLLocationCoordinate2D
}
@@ -99,13 +99,13 @@ try dbQueue.inDatabase { db in
var berlin = PointOfInterest(
id: nil,
title: "Berlin",
favorite: false,
isFavorite: false,
coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053))
try berlin.insert(dbQueue)
berlin.id // some value
berlin.favorite = true
berlin.isFavorite = true
try berlin.update(dbQueue)
// Fetch [PointOfInterest] from SQL
@@ -271,7 +271,7 @@ try dbQueue.inTransaction { db in
if let poi = PointOfInterest.fetchOne(db, key: 1) {
try poi.delete(db)
}
return .Commit
return .commit
}
// Read values:
@@ -339,7 +339,7 @@ try dbPool.writeInTransaction { db in
if let poi = PointOfInterest.fetchOne(db, key: 1) {
try poi.delete(db)
}
return .Commit
return .commit
}
// Read values:
@@ -695,11 +695,11 @@ dbv.isNull // Bool
// All the five storage classes supported by SQLite:
switch dbv.storage {
case .Null: print("NULL")
case .Int64(let int64): print("Int64: \(int64)")
case .Double(let double): print("Double: \(double)")
case .String(let string): print("String: \(string)")
case .Blob(let data): print("NSData: \(data)")
case .null: print("NULL")
case .int64(let int64): print("Int64: \(int64)")
case .double(let double): print("Double: \(double)")
case .string(let string): print("String: \(string)")
case .blob(let data): print("NSData: \(data)")
}
```
@@ -824,10 +824,10 @@ class Link : Record {
var url: NSURL
var verified: Bool
required init(_ row: Row) {
required init(row: Row) {
url = row.value("url")
verified = row.value("verified")
super.init(row)
super.init(row: row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
@@ -982,17 +982,13 @@ A classic technique is to store *integers* instead, since SQLite performs exact
```swift
// Store
let amount = NSDecimalNumber(string: "0.1") // 0.1
let integer = amount // 100
.decimalNumberByMultiplyingByPowerOf10(2)
.longLongValue
// INSERT INTO transfers (amount) VALUES (100)
try db.execute("INSERT INTO transfers (amount) VALUES (?)", arguments: [integer])
let amount = NSDecimalNumber(string: "0.1") // 0.1
let integerAmount = amount.multiplying(byPowerOf10: 2).int64Value // 100
try db.execute("INSERT INTO transfers (amount) VALUES (?)", arguments: [integerAmount])
// Read
let integer = Int64.fetchOne(db, "SELECT SUM(amount) FROM transfers")! // 100
let amount = NSDecimalNumber(longLong: integer) // 0.1
.decimalNumberByMultiplyingByPowerOf10(-2)
let integerAmount = Int64.fetchOne(db, "SELECT SUM(amount) FROM transfers")! // 100
let amount = NSDecimalNumber(value: integerAmount).multiplying(byPowerOf10: -2) // 0.1
```
@@ -1002,11 +998,11 @@ let amount = NSDecimalNumber(longLong: integer) // 0.1
```swift
enum Color : Int {
case Red, White, Rose
case red, white, rose
}
enum Grape : String {
case Chardonnay, Merlot, Riesling
case chardonnay, merlot, riesling
}
// Declare DatabaseValueConvertible adoption
@@ -1016,7 +1012,7 @@ extension Grape : DatabaseValueConvertible { }
// Store
try db.execute(
"INSERT INTO wines (grape, color) VALUES (?, ?)",
arguments: [Grape.Merlot, Color.Red])
arguments: [Grape.merlot, Color.red])
// Read
for rows in Row.fetch(db, "SELECT * FROM wines") {
@@ -1028,15 +1024,15 @@ for rows in Row.fetch(db, "SELECT * FROM wines") {
**When a database value does not match any enum case**, you get a fatal error. This fatal error can be avoided with the [DatabaseValueConvertible.fromDatabaseValue()](#custom-value-types) method:
```swift
let row = Row.fetchOne(db, "SELECT 'Syrah'")!
let row = Row.fetchOne(db, "SELECT 'syrah'")!
row.value(atIndex: 0) as String // "Syrah"
row.value(atIndex: 0) as Grape? // fatal error: could not convert "Syrah" to Grape.
row.value(atIndex: 0) as Grape // fatal error: could not convert "Syrah" to Grape.
row.value(atIndex: 0) as String // "syrah"
row.value(atIndex: 0) as Grape? // fatal error: could not convert "syrah" to Grape.
row.value(atIndex: 0) as Grape // fatal error: could not convert "syrah" to Grape.
let dbv = row.databaseValue(atIndex: 0)
dbv.value() as String // "Syrah"
dbv.value() as Grape? // fatal error: could not convert "Syrah" to Grape.
dbv.value() as String // "syrah"
dbv.value() as Grape? // fatal error: could not convert "syrah" to Grape.
Grape.fromDatabaseValue(dbv) // nil
```
@@ -1047,9 +1043,9 @@ The `DatabaseQueue.inTransaction()` and `DatabasePool.writeInTransaction()` meth
```swift
try dbQueue.inTransaction { db in
let wine = Wine(color: .Red, name: "Pomerol")
let wine = Wine(color: .red, name: "Pomerol")
try wine.insert(db)
return .Commit
return .commit
}
```
@@ -1062,7 +1058,7 @@ try dbQueue.inDatabase { db in // or dbPool.write { db in
...
try db.inTransaction {
...
return .Commit
return .commit
}
...
}
@@ -1071,7 +1067,7 @@ try dbQueue.inDatabase { db in // or dbPool.write { db in
You can ask a database if a transaction is currently opened:
```swift
func myCriticalMethod(db: Database) {
func myCriticalMethod(_ db: Database) {
precondition(db.isInsideTransaction, "This method requires a transaction")
...
}
@@ -1087,11 +1083,11 @@ try dbQueue.inTransaction { db in
try db.inSavepoint {
try db.execute("DELETE ...")
try db.execute("INSERT ...") // need to rollback the delete above if this fails
return .Commit
return .commit
}
// Other savepoints, etc...
return .Commit
return .commit
}
```
@@ -1103,10 +1099,10 @@ try dbQueue.inDatabase { db in
...
try db.inSavepoint {
...
return .Commit
return .commit
}
...
return .Commit // writes changes to disk
return .commit // writes changes to disk
}
}
```
@@ -1123,14 +1119,14 @@ The transaction kind can be changed in the database configuration, or for each t
```swift
// A connection with default DEFERRED transactions:
var config = Configuration()
config.defaultTransactionKind = .Deferred
config.defaultTransactionKind = .deferred
let dbQueue = try DatabaseQueue(path: "...", configuration: config)
// Opens a DEFERRED transaction:
dbQueue.inTransaction { db in ... }
// Opens an EXCLUSIVE transaction:
dbQueue.inTransaction(.Exclusive) { db in ... }
dbQueue.inTransaction(.exclusive) { db in ... }
```
@@ -1144,13 +1140,13 @@ public protocol DatabaseValueConvertible {
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from databaseValue, if possible.
static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self?
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self?
}
```
All types that adopt this protocol can be used like all other [value types](#values) (Bool, Int, String, NSDate, Swift enums, etc.)
The `databaseValue` property returns [DatabaseValue](GRDB/Core/DatabaseValue.swift), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and NSData. DatabaseValue has no public initializer: to create one, use `DatabaseValue.Null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc.
The `databaseValue` property returns [DatabaseValue](GRDB/Core/DatabaseValue.swift), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and NSData. DatabaseValue has no public initializer: to create one, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc.
The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for NSDate, the method returns nil.
@@ -1166,10 +1162,10 @@ There are two kinds of prepared statements: **select statements**, and **update
```swift
try dbQueue.inDatabase { db in
let updateSQL = "INSERT INTO persons (name, age) VALUES (:name, :age)"
let updateStatement = try db.updateStatement(updateSQL)
let updateStatement = try db.makeUpdateStatement(updateSQL)
let selectSQL = "SELECT * FROM persons WHERE name = ?"
let selectStatement = try db.selectStatement(selectSQL)
let selectStatement = try db.makeSelectStatement(selectSQL)
}
```
@@ -1239,9 +1235,9 @@ let reverseString = DatabaseFunction(
return nil
}
// ... and return reversed string:
return String(string.characters.reverse())
return String(string.characters.reversed())
})
dbQueue.addFunction(reverseString) // Or dbPool.addFunction(...)
dbQueue.add(function: reverseString) // Or dbPool.add(function: ...)
dbQueue.inDatabase { db in
// "oof"
@@ -1263,7 +1259,7 @@ let averageOf = DatabaseFunction("averageOf", pure: true) { (databaseValues: [Da
let doubles = databaseValues.flatMap { Double.fromDatabaseValue($0) }
return doubles.reduce(0, combine: +) / Double(doubles.count)
}
dbQueue.addFunction(averageOf)
dbQueue.add(function: averageOf)
dbQueue.inDatabase { db in
// 2.0
@@ -1403,7 +1399,7 @@ class Person : RowConvertible {
var id: Int64?
var name: String
init(_ row: Row) {
init(row: Row) {
id = row.value(named: "id")
name = row.value(named: "name")
}
@@ -1414,7 +1410,7 @@ class Book : RowConvertible {
var title: String
var author: Person?
init(_ row: Row) {
init(row: Row) {
id = row.value(named: "id")
title = row.value(named: "title")
@@ -1454,7 +1450,7 @@ for row in Row.fetch(db, sql, adapter: adapter) {
print(row.subrow(named: "bestFriend"))
}
// Assuming Person.init(row) consumes the "bestFriend" subrow:
// Assuming Person.init(row: row) consumes the "bestFriend" subrow:
for person in Person.fetch(db, sql, adapter: adapter) {
person.name // Arthur
person.bestFriend?.name // Barbara
@@ -1474,7 +1470,7 @@ try dbQueue.inDatabase { db in
let sqliteConnection = db.sqliteConnection
// The raw pointer to a statement:
let statement = try db.selectStatement("SELECT ...")
let statement = try db.makeSelectStatement("SELECT ...")
let sqliteStatement = statement.sqliteStatement
}
```
@@ -1636,11 +1632,11 @@ You can now jump to:
```swift
public protocol RowConvertible {
/// Row initializer
init(_ row: Row)
init(row: Row)
/// Optional method which gives adopting types an opportunity to complete
/// their initialization after being fetched. Do not call it directly.
mutating func awakeFromFetch(row row: Row)
mutating func awakeFromFetch(row: Row)
}
```
@@ -1654,7 +1650,7 @@ struct PointOfInterest {
}
extension PointOfInterest : RowConvertible {
init(_ row: Row) {
init(row: Row) {
id = row.value(named: "id")
title = row.value(named: "title")
coordinate = CLLocationCoordinate2DMake(
@@ -1666,7 +1662,7 @@ extension PointOfInterest : RowConvertible {
See [column values](#column-values) for more information about the `row.value()` method.
> :point_up: **Note**: for performance reasons, the same row argument to `init(_:Row)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
RowConvertible allows adopting types to be fetched from SQL queries:
@@ -1685,7 +1681,7 @@ RowConvertible consume row columns by name:
```swift
extension PointOfInterest : RowConvertible {
init(_ row: Row) {
init(row: Row) {
id = row.value(named: "id") // "id"
title = row.value(named: "title") // "title"
coordinate = CLLocationCoordinate2DMake(
@@ -1758,14 +1754,14 @@ public protocol MutablePersistable : TableMapping {
/// Optional method that lets your adopting type store its rowID upon
/// successful insertion. Don't call it directly: it is called for you.
mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?)
mutating func didInsert(with rowID: Int64, for column: String?)
}
```
```swift
public protocol Persistable : MutablePersistable {
/// Non-mutating version of the optional didInsertWithRowID(:forColumn:)
func didInsertWithRowID(rowID: Int64, forColumn column: String?)
/// Non-mutating version of the optional didInsert(with:for:)
func didInsert(with rowID: Int64, for column: String?)
}
```
@@ -1779,7 +1775,7 @@ Yes, two protocols instead of one. Both grant exactly the same advantages. Here
The `persistentDictionary` property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information.
The optional `didInsertWithRowID` method lets the adopting type store its rowID after successful insertion. It is called from a protected dispatch queue, and serialized with all database updates.
The optional `didInsert` method lets the adopting type store its rowID after successful insertion. It is called from a protected dispatch queue, and serialized with all database updates.
**To use those protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitely. For example:
@@ -1796,7 +1792,7 @@ extension PointOfInterest : MutablePersistable {
}
// Update id upon successful insertion:
mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
@@ -1825,7 +1821,7 @@ pointOfInterest.exists(db) // Bool
- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails.
- `update` can also throw a PersistenceError of type NotFound, should the update fail because there is no matching row in the database.
- `update` can also throw a PersistenceError of type recordNotFound, should the update fail because there is no matching row in the database.
When saving an object that may or may not already exist in the database, prefer the `save` method:
@@ -1852,7 +1848,7 @@ When you subclass [Record](#record-class), you simply have to override the custo
class Person : Record {
var uuid: String?
override func insert(db: Database) throws {
override func insert(_ db: Database) throws {
if uuid == nil {
uuid = NSUUID().UUIDString
}
@@ -1867,12 +1863,12 @@ If you use the raw [Persistable](#persistable-protocol) protocol, use one of the
struct Link : Persistable {
var url: NSURL
func insert(db: Database) throws {
func insert(_ db: Database) throws {
try validate()
try performInsert(db)
}
func update(db: Database) throws {
func update(_ db: Database) throws {
try validate()
try performUpdate(db)
}
@@ -1907,13 +1903,13 @@ class Record {
class func databaseTableName() -> String
/// Initialize from a database row
required init(_ row: Row)
required init(row: Row)
/// The values persisted in the database
var persistentDictionary: [String: DatabaseValueConvertible?]
/// Optionally update record ID after a successful insertion
func didInsertWithRowID(rowID: Int64, forColumn column: String?)
func didInsert(with rowID: Int64, for column: String?)
}
```
@@ -1931,13 +1927,13 @@ class PointOfInterest : Record {
}
/// Initialize from a database row
required init(_ row: Row) {
required init(row: Row) {
id = row.value(named: "id")
title = row.value(named: "title")
coordinate = CLLocationCoordinate2DMake(
row.value(named: "latitude"),
row.value(named: "longitude"))
super.init(row)
super.init(row: row)
}
/// The values persisted in the database
@@ -1950,7 +1946,7 @@ class PointOfInterest : Record {
}
/// Update record ID after a successful insertion
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
@@ -2036,14 +2032,14 @@ For an efficient algorithm which synchronizes the content of a database table wi
**The query interface lets you write pure Swift instead of SQL:**
```swift
let count = Wine.filter(color == Color.Red).fetchCount(db)
let count = Wine.filter(color == Color.red).fetchCount(db)
let wines = Wine.filter(origin == "Burgundy").order(price).fetchAll(db)
```
Please bear in mind that the query interface can not generate all possible SQL queries. You may also *prefer* writing SQL, and this is just OK:
```swift
let count = Int.fetchOne(db, "SELECT COUNT(*) FROM wines WHERE color = ?", arguments [Color.Red])!
let count = Int.fetchOne(db, "SELECT COUNT(*) FROM wines WHERE color = ?", arguments [Color.red])!
let wines = Wine.fetchAll(db, "SELECT * FROM wines WHERE origin = ? ORDER BY price", arguments: ["Burgundy"])
```
@@ -2104,11 +2100,11 @@ All the methods above return another request, which you can further refine by ap
Person.select(max(ageColumn).aliased("maxAge"))
```
- `distinct` performs uniquing:
- `distinct()` performs uniquing:
```swift
// SELECT DISTINCT "name" FROM "persons"
Person.select(nameColumn).distinct
Person.select(nameColumn).distinct()
```
- `filter(expression)` applies conditions.
@@ -2140,7 +2136,7 @@ All the methods above return another request, which you can further refine by ap
.having(min(ageColumn) >= 18)
```
- `order(sortDescriptor, ...)` sorts.
- `order(ordering, ...)` sorts.
```swift
// SELECT * FROM "persons" ORDER BY "name"
@@ -2150,18 +2146,18 @@ All the methods above return another request, which you can further refine by ap
Person.order(scoreColumn.desc, nameColumn)
```
- `reverse()` reverses the eventual sort descriptors.
- `reversed()` reverses the eventual ordering.
```swift
// SELECT * FROM "persons" ORDER BY "score" ASC, "name" DESC
Person.order(scoreColumn.desc, nameColumn).reverse()
Person.order(scoreColumn.desc, nameColumn).reversed()
```
If no ordering was specified, the result is ordered by rowID in reverse order.
```swift
// SELECT * FROM "persons" ORDER BY "_rowid_" DESC
Person.all().reverse()
Person.all().reversed()
```
- `limit(limit, offset: offset)` limits and pages results.
@@ -2334,10 +2330,10 @@ Feed [requests](#requests) with SQL expressions built from your Swift code:
The query interface does not give access to those SQLite functions. Nothing against them, but they are not unicode aware.
Instead, GRDB extends SQLite with SQL functions that call the Swift built-in string functions `capitalizedString`, `lowercaseString`, `uppercaseString`, `localizedCapitalizedString`, `localizedLowercaseString` and `localizedUppercaseString`:
Instead, GRDB extends SQLite with SQL functions that call the Swift built-in string functions `capitalized`, `lowercased`, `uppercased`, `localizedCapitalized`, `localizedLowercased` and `localizedUppercased`:
```swift
Person.select(nameColumn.uppercaseString)
Person.select(nameColumn.uppercased())
```
> :point_up: **Note**: When *comparing* strings, you'd rather use a [custom comparison function](#string-comparison).
@@ -2431,10 +2427,10 @@ let count = Person.fetchCount(db) // Int
let count = Person.filter(emailColumn != nil).fetchCount(db)
// SELECT COUNT(DISTINCT "name") FROM "persons"
let count = Person.select(nameColumn).distinct.fetchCount(db)
let count = Person.select(nameColumn).distinct().fetchCount(db)
// SELECT COUNT(*) FROM (SELECT DISTINCT "name", "age" FROM "persons")
let count = Person.select(nameColumn, ageColumn).distinct.fetchCount(db)
let count = Person.select(nameColumn, ageColumn).distinct().fetchCount(db)
```
@@ -2511,10 +2507,10 @@ While your migration code runs with disabled foreign key checks, those are re-en
## Database Changes Observation
The `TransactionObserverType` protocol lets you **observe database changes**:
The `TransactionObserver` protocol lets you **observe database changes**:
```swift
public protocol TransactionObserverType : class {
public protocol TransactionObserver : class {
/// Notifies a database change:
/// - event.kind (insert, update, or delete)
/// - event.tableName
@@ -2523,16 +2519,16 @@ public protocol TransactionObserverType : class {
/// For performance reasons, the event is only valid for the duration of
/// this method call. If you need to keep it longer, store a copy:
/// event.copy().
func databaseDidChangeWithEvent(event: DatabaseEvent)
func databaseDidChange(with event: DatabaseEvent)
/// An opportunity to rollback pending changes by throwing an error.
func databaseWillCommit() throws
/// Database changes have been committed.
func databaseDidCommit(db: Database)
func databaseDidCommit(_ db: Database)
/// Database changes have been rollbacked.
func databaseDidRollback(db: Database)
func databaseDidRollback(_ db: Database)
}
```
@@ -2540,7 +2536,7 @@ To activate a transaction observer, add it to the database queue or pool:
```swift
let observer = MyObserver()
dbQueue.addTransactionObserver(observer)
dbQueue.add(transactionObserver: observer)
```
Database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated.
@@ -2553,13 +2549,13 @@ Changes are not actually applied until `databaseDidCommit` is called. On the oth
try dbQueue.inTransaction { db in
try db.execute("INSERT ...") // 1. didChange
try db.execute("UPDATE ...") // 2. didChange
return .Commit // 3. willCommit, 4. didCommit
return .commit // 3. willCommit, 4. didCommit
}
try dbQueue.inTransaction { db in
try db.execute("INSERT ...") // 1. didChange
try db.execute("UPDATE ...") // 2. didChange
return .Rollback // 3. didRollback
return .rollback // 3. didRollback
}
```
@@ -2587,7 +2583,7 @@ try dbQueue.inTransaction { db in
try db.execute("UPDATE ...") // not notified
try db.execute("ROLLBACK TO SAVEPOINT foo")
return .Commit // 4. willCommit, 5. didCommit
return .commit // 4. willCommit, 5. didCommit
}
```
@@ -2598,7 +2594,7 @@ try dbQueue.inTransaction { db in
do {
try dbQueue.inTransaction { db in
...
return .Commit // 1. willCommit (throws), 2. didRollback
return .commit // 1. willCommit (throws), 2. didRollback
}
} catch {
// 3. The error thrown by the transaction observer.
@@ -2607,9 +2603,9 @@ do {
> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates.
>
> :point_up: **Note**: the databaseDidChangeWithEvent and databaseWillCommit callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.
> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.
[FetchedRecordsController](#fetchedrecordscontroller) is based on the TransactionObserverType protocol.
[FetchedRecordsController](#fetchedrecordscontroller) is based on the TransactionObserver protocol.
See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter.
@@ -2692,7 +2688,7 @@ Changes are not reflected until they are applied in the database by a successful
try dbQueue.inTransaction { db in
try person1.insert(db)
try person2.insert(db)
return .Commit // Explicit transaction
return .commit // Explicit transaction
}
try dbQueue.inDatabase { db in
@@ -2786,7 +2782,7 @@ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> In
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = ...
let record = fetchedRecordsController.recordAtIndexPath(indexPath)
let record = fetchedRecordsController.record(at: indexPath)
// Configure the cell
return cell
}
@@ -2838,26 +2834,26 @@ self.controller.trackChanges(
// notification of individual record changes:
tableViewEvent: { [unowned self] (controller, record, event) in
switch event {
case .Insertion(let indexPath):
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .insertion(let indexPath):
self.tableView.insertRows(at: [indexPath], with: .fade)
case .Deletion(let indexPath):
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .deletion(let indexPath):
self.tableView.deleteRows(at: [indexPath], with: .fade)
case .Update(let indexPath, _):
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) {
self.configureCell(cell, atIndexPath: indexPath)
case .update(let indexPath, _):
if let cell = self.tableView.cellForRow(at: indexPath) {
self.configure(cell, at: indexPath)
}
case .Move(let indexPath, let newIndexPath, _):
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
case .move(let indexPath, let newIndexPath, _):
self.tableView.deleteRows(at: [indexPath], with: .fade)
self.tableView.insertRows(at: [newIndexPath], with: .fade)
// // Alternate technique which actually moves cells around:
// let cell = self.tableView.cellForRowAtIndexPath(indexPath)
// self.tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath)
// let cell = self.tableView.cellForRow(at: indexPath)
// self.tableView.moveRow(at: indexPath, to: newIndexPath)
// if let cell = cell {
// self.configureCell(cell, atIndexPath: newIndexPath)
// self.configure(cell, at: newIndexPath)
// }
}
},
@@ -3049,10 +3045,10 @@ To avoid fatal errors, you have to expose and handle each failure point by going
if let arguments = StatementArguments(arguments) {
// SQL may be invalid
let statement = try db.selectStatement(sql)
let statement = try db.makeSelectStatement(sql)
// Arguments may not fit the statement
try statement.validateArguments(arguments)
try statement.validate(arguments: arguments)
// OK now
let rows = Row.fetchAll(statement, arguments: arguments)
@@ -3078,18 +3074,18 @@ The `UPPER` and `LOWER` built-in SQLite functions are not unicode-aware:
String.fetchOne(db, "SELECT UPPER('Jérôme')")
```
GRDB extends SQLite with [SQL functions](#custom-sql-functions) that call the Swift built-in string functions `capitalizedString`, `lowercaseString`, `uppercaseString`, `localizedCapitalizedString`, `localizedLowercaseString` and `localizedUppercaseString`:
GRDB extends SQLite with [SQL functions](#custom-sql-functions) that call the Swift built-in string functions `capitalized`, `lowercased`, `uppercased`, `localizedCapitalized`, `localizedLowercased` and `localizedUppercased`:
```swift
// "JÉRÔME"
let uppercaseString = DatabaseFunction.uppercaseString
String.fetchOne(db, "SELECT \(uppercaseString.name)('Jérôme')")
let uppercase = DatabaseFunction.uppercase
String.fetchOne(db, "SELECT \(uppercased.name)('Jérôme')")
```
Those unicode-aware string functions are also readily available in the [query interface](#sql-functions):
```
Person.select(nameColumn.uppercaseString)
Person.select(nameColumn.uppercased)
```
@@ -3137,7 +3133,7 @@ let persons = Person.filter(uuidColumn.collating("NOCASE") == uuid).fetchAll(db)
let collation = DatabaseCollation("customCollation") { (lhs, rhs) -> NSComparisonResult in
// return the comparison of lhs and rhs strings.
}
dbQueue.addCollation(collation) // Or dbPool.addCollation(...)
dbQueue.add(collation: collation) // Or dbPool.add(collation: ...)
```
@@ -3172,7 +3168,7 @@ This method blocks the current thread until all current database accesses are co
```
let dbQueue = try DatabaseQueue(...)
dbQueue.setupMemoryManagement(application: UIApplication.sharedApplication())
dbQueue.setupMemoryManagement(in: UIApplication.sharedApplication())
```
@@ -3292,21 +3288,21 @@ FAQ
```swift
var configuration = Configuration()
configuration.readonly = true
let dbPath = NSBundle.mainBundle().pathForResource("db", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: dbPath, configuration: configuration)
let dbPath = NSBundle.main().pathForResource("db", ofType: "sqlite")!
let dbQueue = try DatabaseQueue(path: dbPath, configuration: configuration)
```
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the Documents folder. Only then, open a [connection](#database-connections):
```swift
let fm = NSFileManager.defaultManager()
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let dbPath = (documentsPath as NSString).stringByAppendingPathComponent("db.sqlite")
if !fm.fileExistsAtPath(dbPath) {
let dbResourcePath = NSBundle.mainBundle().pathForResource("db", ofType: "sqlite")!
try! fm.copyItemAtPath(dbResourcePath, toPath: dbPath)
let fm = NSFileManager.default()
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let dbPath = (documentsPath as NSString).appendingPathComponent("db.sqlite")
if !fm.fileExists(atPath: dbPath) {
let dbResourcePath = NSBundle.main().pathForResource("db", ofType: "sqlite")!
try fm.copyItem(atPath: dbResourcePath, toPath: dbPath)
}
let dbQueue = DatabaseQueue(path: dbPath)
let dbQueue = try DatabaseQueue(path: dbPath)
```
+2 -2
View File
@@ -10,7 +10,7 @@ class DatabasePoolCrashTests: GRDBCrashTestCase {
func testReaderCanNotStartTransaction() {
assertCrash("DatabasePool readers can not start transactions or savepoints.") {
try dbPool.read { db in
let statement = try db.updateStatement("BEGIN TRANSACTION")
let statement = try db.makeUpdateStatement("BEGIN TRANSACTION")
}
}
}
@@ -18,7 +18,7 @@ class DatabasePoolCrashTests: GRDBCrashTestCase {
func testReaderCanNotStartSavepoint() {
assertCrash("DatabasePool readers can not start transactions or savepoints.") {
try dbPool.read { db in
let statement = try db.updateStatement("SAVEPOINT foo")
let statement = try db.makeUpdateStatement("SAVEPOINT foo")
}
}
}
+9 -9
View File
@@ -24,7 +24,7 @@ class DatabaseQueueCrashTests: GRDBCrashTestCase {
assertCrash("Database methods are not reentrant.") {
try dbQueue.inDatabase { db in
try self.dbQueue.inTransaction { db in
return .Commit
return .commit
}
}
}
@@ -34,9 +34,9 @@ class DatabaseQueueCrashTests: GRDBCrashTestCase {
assertCrash("Database methods are not reentrant.") {
try dbQueue.inTransaction { db in
try self.dbQueue.inTransaction { db in
return .Commit
return .commit
}
return .Commit
return .commit
}
}
}
@@ -52,18 +52,18 @@ class DatabaseQueueCrashTests: GRDBCrashTestCase {
try db.execute("CREATE TABLE persons (name TEXT)")
rows = Row.fetch(db, "SELECT * FROM persons")
}
_ = rows!.generate()
_ = rows!.makeIterator()
}
}
func testRowSequenceCanNotBeIteratedOutsideOfDatabaseQueue() {
assertCrash("Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") {
var generator: DatabaseGenerator<Row>?
var iterator: DatabaseIterator<Row>?
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT)")
generator = Row.fetch(db, "SELECT * FROM persons").generate()
iterator = Row.fetch(db, "SELECT * FROM persons").makeIterator()
}
_ = generator!.next()
_ = iterator!.next()
}
}
@@ -84,9 +84,9 @@ class DatabaseQueueCrashTests: GRDBCrashTestCase {
queue.maxConcurrentOperationCount = 2
queue.addOperation(NSBlockOperation {
do {
try dbQueue1.inTransaction(.Exclusive) { db in
try dbQueue1.inTransaction(.exclusive) { db in
sleep(2) // let other queue try to read.
return .Commit
return .commit
}
}
catch is DatabaseError {
@@ -14,7 +14,7 @@ private struct IntConvertible: DatabaseValueConvertible {
var databaseValue: DatabaseValue {
return int.databaseValue
}
static func fromDatabaseValue(databaseValue: DatabaseValue) -> IntConvertible? {
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> IntConvertible? {
guard let int = Int.fromDatabaseValue(databaseValue) else {
return nil
}
@@ -31,7 +31,7 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase {
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.makeSelectStatement("SELECT int FROM ints ORDER BY int")
let sequence = IntConvertible.fetch(statement)
for _ in sequence { }
}
@@ -45,7 +45,7 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase {
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.makeSelectStatement("SELECT int FROM ints ORDER BY int")
_ = IntConvertible.fetchAll(statement)
}
}
@@ -14,7 +14,7 @@ class StatementColumnConvertibleCrashTests: GRDBCrashTestCase {
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.makeSelectStatement("SELECT int FROM ints ORDER BY int")
let sequence = Int.fetch(statement)
for _ in sequence { }
}
@@ -28,7 +28,7 @@ class StatementColumnConvertibleCrashTests: GRDBCrashTestCase {
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.selectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.makeSelectStatement("SELECT int FROM ints ORDER BY int")
_ = Int.fetchAll(statement)
}
}
@@ -1,14 +1,14 @@
//import XCTest
//import GRDB
//
//// See if TransactionObserverType can provide robust NSData external storage.
//// See if TransactionObserver can provide robust NSData external storage.
////
//// The answer is yes, we can.
////
//// However this requires records to be *managed*. All instances of our
//// RecordWithManagedData must be given their manager after instanciation.
//
//class ManagedDataController : TransactionObserverType {
//class ManagedDataController : TransactionObserver {
// // Base directory
// let path: String
//
@@ -30,11 +30,11 @@
// }
//
// func willSaveManagedData(managedData: ManagedData?) {
// // Next step: databaseDidChangeWithEvent() or databaseDidRollback()
// // Next step: databaseDidChange(with:) or databaseDidRollback()
// self.managedData = managedData
// }
//
// func databaseDidChangeWithEvent(event: DatabaseEvent) {
// func databaseDidChange(with event: DatabaseEvent) {
// guard let managedData = managedData else {
// return
// }
@@ -42,7 +42,7 @@
// self.managedData = nil
//
// switch event.kind {
// case .Insert, .Update:
// case .insert, .update:
// managedData.rowID = event.rowID
// // Replace any existing managedData for this rowID.
// pendingManagedDatas[event.rowID] = managedData
@@ -53,23 +53,23 @@
//
// func databaseWillCommit() throws {
// do {
// let fm = NSFileManager.defaultManager()
// let fm = NSFileManager.default()
// for (_, managedData) in pendingManagedDatas.sort({ $0.0 < $1.0 }) {
// if let forbiddenData = forbiddenData, let data = managedData.data where forbiddenData == data {
// throw NSError(domain: "ManagedDataController", code: 0, userInfo: nil)
// }
//
// let storagePath = storageDataPath(managedData)
// let storageDir = (storagePath as NSString).stringByDeletingLastPathComponent
// let storageDir = (storagePath as NSString).deletingLastPathComponent
// let tempPath = temporaryDataPath(managedData)
// let tempDir = (tempPath as NSString).stringByDeletingLastPathComponent
// let tempDir = (tempPath as NSString).deletingLastPathComponent
//
//
// // Move
//
// if fm.fileExistsAtPath(storagePath) {
// if fm.fileExistsAtPath(tempPath) {
// try! fm.removeItemAtPath(tempPath)
// try! fm.removeItem(atPath: tempPath)
// }
// if !fm.fileExistsAtPath(tempDir) {
// try fm.createDirectoryAtPath(tempDir, withIntermediateDirectories: true, attributes: nil)
@@ -99,24 +99,24 @@
// }
// }
//
// func databaseDidCommit(db: Database) {
// func databaseDidCommit(_ db: Database) {
// // TODO: clean up tmp directory
// cleanup()
// }
//
// func databaseDidRollback(db: Database) {
// func databaseDidRollback(_ db: Database) {
// if restoreFileSystemAfterRollback {
// let fm = NSFileManager.defaultManager()
// let fm = NSFileManager.default()
//
// for managedData in storedManagedDatas {
// if fm.fileExistsAtPath(storageDataPath(managedData)) {
// try! fm.removeItemAtPath(storageDataPath(managedData))
// try! fm.removeItem(atPath: storageDataPath(managedData))
// }
// }
//
// for managedData in movedManagedDatas {
// let storagePath = storageDataPath(managedData)
// let storageDir = (storagePath as NSString).stringByDeletingLastPathComponent
// let storageDir = (storagePath as NSString).deletingLastPathComponent
// let tempPath = temporaryDataPath(managedData)
// if fm.fileExistsAtPath(tempPath) {
// if !fm.fileExistsAtPath(storageDir) {
@@ -141,7 +141,7 @@
// guard managedData.rowID != nil else {
// return nil
// }
// let fm = NSFileManager.defaultManager()
// let fm = NSFileManager.default()
// if fm.fileExistsAtPath(storageDataPath(managedData)) {
// return NSData(contentsOfFile: storageDataPath(managedData))!
// } else {
@@ -150,25 +150,25 @@
// }
//
// private var temporaryDirectoryPath: String {
// return (path as NSString).stringByAppendingPathComponent("tmp")
// return (path as NSString).appendingPathComponent("tmp")
// }
//
// private func storageDataPath(managedData: ManagedData) -> String {
// var path = self.path as NSString
// path = path.stringByAppendingPathComponent(String(managedData.rowID!))
// path = path.stringByAppendingPathComponent(managedData.name)
// path = path.appendingPathComponent(String(managedData.rowID!))
// path = path.appendingPathComponent(managedData.name)
// return path as String
// }
//
// private func temporaryDataPath(managedData: ManagedData) -> String {
// var path = self.temporaryDirectoryPath as NSString
// path = path.stringByAppendingPathComponent(String(managedData.rowID!))
// path = path.stringByAppendingPathComponent(managedData.name)
// path = path.appendingPathComponent(String(managedData.rowID!))
// path = path.appendingPathComponent(managedData.name)
// return path as String
// }
//
// private func setupDirectories() {
// let fm = NSFileManager.defaultManager()
// let fm = NSFileManager.default()
// try! fm.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
// try! fm.createDirectoryAtPath(temporaryDirectoryPath, withIntermediateDirectories: true, attributes: nil)
// }
@@ -239,20 +239,20 @@
// super.updateFromRow(row)
// }
//
// override func insert(db: Database) throws {
// override func insert(_ db: Database) throws {
// // Hmm.
// managedData.willSave()
// try super.insert(db)
// }
//
// override func update(db: Database) throws {
// override func update(_ db: Database) throws {
// // Hmm.
// managedData.willSave()
// try super.update(db)
// }
//
// // OK
// static func setupInDatabase(db: Database) throws {
// static func setup(inDatabase db: Database) throws {
// // TODO: make tests run with a single "id INTEGER PRIMARY KEY" column.
// // The "update" method is doing nothing in this case, so we can expect troubles with managed data.
// try db.execute(
@@ -264,7 +264,7 @@
// var managedDataController: ManagedDataController!
//
// override var dbConfiguration: Configuration {
// managedDataController = ManagedDataController(path: "/tmp/ManagedDataController", forbiddenData: "Bunny".dataUsingEncoding(NSUTF8StringEncoding))
// managedDataController = ManagedDataController(path: "/tmp/ManagedDataController", forbiddenData: "Bunny".data(using: NSUTF8StringEncoding))
// var c = super.dbConfiguration
// c.transactionObserver = managedDataController
// return c
@@ -275,7 +275,7 @@
//
// assertNoError {
// try dbQueue.inDatabase { db in
// try RecordWithManagedData.setupInDatabase(db)
// try RecordWithManagedData.setup(inDatabase: db)
// }
// }
// }
@@ -287,7 +287,7 @@
// try dbQueue.inDatabase { db in
// // TODO: this explicit line is a problem
// record.managedData.controller = self.managedDataController
// record.data = "foo".dataUsingEncoding(NSUTF8StringEncoding)
// record.data = "foo".data(using: NSUTF8StringEncoding)
// try record.save(db)
// }
//
@@ -295,7 +295,7 @@
// dbQueue.inDatabase { db in
// let reloadedRecord = RecordWithManagedData.fetchOne(db, key: record.id)!
// reloadedRecord.managedData.controller = self.managedDataController
// XCTAssertEqual(reloadedRecord.data, "foo".dataUsingEncoding(NSUTF8StringEncoding))
// XCTAssertEqual(reloadedRecord.data, "foo".data(using: NSUTF8StringEncoding))
// }
// }
// }
@@ -306,33 +306,33 @@
// let record = RecordWithManagedData()
// record.managedData.controller = self.managedDataController
// try dbQueue.inDatabase { db in
// record.data = "foo".dataUsingEncoding(NSUTF8StringEncoding)
// record.data = "foo".data(using: NSUTF8StringEncoding)
// try record.save(db)
// }
//
// try dbQueue.inTransaction { db in
// // ... and that changes...
// record.data = "bar".dataUsingEncoding(NSUTF8StringEncoding)
// record.data = "bar".data(using: NSUTF8StringEncoding)
// try record.save(db)
//
// // ... after changes...
// record.data = "baz".dataUsingEncoding(NSUTF8StringEncoding)
// record.data = "baz".data(using: NSUTF8StringEncoding)
// try record.save(db)
//
// // ... are not applied in the file system...
// let reloadedRecord = RecordWithManagedData.fetchOne(db, key: record.id)!
// reloadedRecord.managedData.controller = self.managedDataController
// XCTAssertEqual(reloadedRecord.data, "foo".dataUsingEncoding(NSUTF8StringEncoding))
// XCTAssertEqual(reloadedRecord.data, "foo".data(using: NSUTF8StringEncoding))
//
// // ... until database commit:
// return .Commit
// return .commit
// }
//
// // We find our modified data after commit:
// dbQueue.inDatabase { db in
// let reloadedRecord = RecordWithManagedData.fetchOne(db, key: record.id)!
// reloadedRecord.managedData.controller = self.managedDataController
// XCTAssertEqual(reloadedRecord.data, "baz".dataUsingEncoding(NSUTF8StringEncoding))
// XCTAssertEqual(reloadedRecord.data, "baz".data(using: NSUTF8StringEncoding))
// }
// }
// }
@@ -343,31 +343,31 @@
// let record = RecordWithManagedData()
// record.managedData.controller = self.managedDataController
// try dbQueue.inDatabase { db in
// record.data = "foo".dataUsingEncoding(NSUTF8StringEncoding)
// record.data = "foo".data(using: NSUTF8StringEncoding)
// try record.save(db)
// }
//
// do {
// try dbQueue.inTransaction { db in
// // ... and that changes...
// record.data = "bar".dataUsingEncoding(NSUTF8StringEncoding)
// record.data = "bar".data(using: NSUTF8StringEncoding)
// try record.save(db)
//
// // ... after changes...
// record.data = "baz".dataUsingEncoding(NSUTF8StringEncoding)
// record.data = "baz".data(using: NSUTF8StringEncoding)
// try record.save(db)
//
// // ... are not applied in the file system...
// let reloadedRecord = RecordWithManagedData.fetchOne(db, key: record.id)!
// reloadedRecord.managedData.controller = self.managedDataController
// XCTAssertEqual(reloadedRecord.data, "foo".dataUsingEncoding(NSUTF8StringEncoding))
// XCTAssertEqual(reloadedRecord.data, "foo".data(using: NSUTF8StringEncoding))
//
// // ... until database commit, which may fail:
// let forbiddenRecord = RecordWithManagedData()
// forbiddenRecord.managedData.controller = self.managedDataController
// forbiddenRecord.data = "Bunny".dataUsingEncoding(NSUTF8StringEncoding)
// forbiddenRecord.data = "Bunny".data(using: NSUTF8StringEncoding)
// try forbiddenRecord.save(db)
// return .Commit
// return .commit
// }
// XCTFail("Expected error")
// } catch let error as NSError {
@@ -378,7 +378,7 @@
// dbQueue.inDatabase { db in
// let reloadedRecord = RecordWithManagedData.fetchOne(db, key: record.id)!
// reloadedRecord.managedData.controller = self.managedDataController
// XCTAssertEqual(reloadedRecord.data, "foo".dataUsingEncoding(NSUTF8StringEncoding))
// XCTAssertEqual(reloadedRecord.data, "foo".data(using: NSUTF8StringEncoding))
// }
// }
// }
+4 -4
View File
@@ -13,7 +13,7 @@
// init() {
// direction = .Save
// }
// init(_ row: Row) {
// init(row: Row) {
// direction = .Fetch(row)
// }
// subscript(name: String) -> Binding {
@@ -95,7 +95,7 @@
// var firstName: String?
// var lastName: String?
// var fullName: String {
// return [firstName, lastName].flatMap { $0 }.joinWithSeparator(" ")
// return [firstName, lastName].flatMap { $0 }.joined(separator: " ")
// }
//
// init(firstName: String? = nil, lastName: String? = nil) {
@@ -129,8 +129,8 @@
// return mapping.dictionary
// }
//
// required init(_ row: Row) {
// super.init(row)
// required init(row: Row) {
// super.init(row: row)
// }
//}
//
@@ -24,7 +24,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
func fetchPositionalValues() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("ProfilingDatabase", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("ProfilingDatabase", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
var count = 0
@@ -50,7 +50,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
func fetchNamedValues() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("ProfilingDatabase", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("ProfilingDatabase", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
var count = 0
@@ -76,7 +76,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
func fetchRecords() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("ProfilingDatabase", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("ProfilingDatabase", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
let items = dbQueue.inDatabase { db in
Item.fetchAll(db)
@@ -89,7 +89,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
func insertPositionalValues() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -97,10 +97,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
@@ -108,17 +108,17 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
try! dbQueue.inTransaction { db in
let statement = try! db.updateStatement("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)")
let statement = try! db.makeUpdateStatement("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
return .commit
}
}
func insertNamedValues() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -126,10 +126,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
@@ -137,18 +137,18 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
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)")
let statement = try! db.makeUpdateStatement("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
return .commit
}
}
func insertRecords() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -156,10 +156,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
@@ -170,7 +170,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
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
return .commit
}
}
}
@@ -206,7 +206,7 @@ class Item : Record {
return "items"
}
required init(_ row: GRDB.Row) {
required init(row: GRDB.Row) {
i0 = row.value(named: "i0")
i1 = row.value(named: "i1")
i2 = row.value(named: "i2")
@@ -217,7 +217,7 @@ class Item : Record {
i7 = row.value(named: "i7")
i8 = row.value(named: "i8")
i9 = row.value(named: "i9")
super.init(row)
super.init(row: row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
+13 -13
View File
@@ -20,25 +20,25 @@ class GRDBTestCase: XCTestCase {
// Builds a database queue based on dbConfiguration
func makeDatabaseQueue(filename: String = "db.sqlite") throws -> DatabaseQueue {
try NSFileManager.defaultManager().createDirectoryAtPath(dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).stringByAppendingPathComponent(filename)
try NSFileManager.default().createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename)
let dbQueue = try DatabaseQueue(path: dbPath, configuration: dbConfiguration)
try setUpDatabase(dbQueue)
try setup(dbQueue)
return dbQueue
}
// Builds a database pool based on dbConfiguration
func makeDatabasePool(filename: String = "db.sqlite") throws -> DatabasePool {
try NSFileManager.defaultManager().createDirectoryAtPath(dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).stringByAppendingPathComponent(filename)
try NSFileManager.default().createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true, attributes: nil)
let dbPath = (dbDirectoryPath as NSString).appendingPathComponent(filename)
let dbPool = try DatabasePool(path: dbPath, configuration: dbConfiguration)
try setUpDatabase(dbPool)
try setup(dbPool)
return dbPool
}
// Subclasses can override
// Default implementation is empty.
func setUpDatabase(dbWriter: DatabaseWriter) throws {
func setup(_ dbWriter: DatabaseWriter) throws {
}
// The default path for database pool directory
@@ -54,8 +54,8 @@ class GRDBTestCase: XCTestCase {
super.setUp()
let dbPoolDirectoryName = "GRDBTestCase-\(NSProcessInfo.processInfo().globallyUniqueString)"
dbDirectoryPath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(dbPoolDirectoryName)
do { try NSFileManager.defaultManager().removeItemAtPath(dbDirectoryPath) } catch { }
dbDirectoryPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(dbPoolDirectoryName)
do { try NSFileManager.default().removeItem(atPath: dbDirectoryPath) } catch { }
dbConfiguration = Configuration()
@@ -83,7 +83,7 @@ class GRDBTestCase: XCTestCase {
// - sqlite3_next_stmt https://www.sqlite.org/capi3ref.html#sqlite3_next_stmt
// - sqlite3_stmt_busy https://www.sqlite.org/capi3ref.html#sqlite3_stmt_busy
// - sqlite3_stmt_readonly https://www.sqlite.org/capi3ref.html#sqlite3_stmt_readonly
var stmt: SQLiteStatement = sqlite3_next_stmt(sqliteConnection, nil)
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
while stmt != nil {
XCTAssertTrue(sqlite3_stmt_readonly(stmt) != 0 || sqlite3_stmt_busy(stmt) == 0)
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
@@ -105,10 +105,10 @@ class GRDBTestCase: XCTestCase {
override func tearDown() {
super.tearDown()
do { try NSFileManager.defaultManager().removeItemAtPath(dbDirectoryPath) } catch { }
do { try NSFileManager.default().removeItem(atPath: dbDirectoryPath) } catch { }
}
func assertNoError(file: StaticString = #file, line: UInt = #line, @noescape _ test: (Void) throws -> Void) {
func assertNoError(file: StaticString = #file, line: UInt = #line, _ test: @noescape(Void) throws -> Void) {
do {
try test()
} catch {
@@ -116,7 +116,7 @@ class GRDBTestCase: XCTestCase {
}
}
func sql(databaseReader: DatabaseReader, _ request: FetchRequest) -> String {
func sql(_ databaseReader: DatabaseReader, _ request: FetchRequest) -> String {
return databaseReader.read { db in
_ = Row.fetchOne(db, request)
return self.lastSQLQuery
@@ -8,7 +8,7 @@ private let expectedRowCount = 100_000
class FetchNamedValuesTests: XCTestCase {
func testFMDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
@@ -38,7 +38,7 @@ class FetchNamedValuesTests: XCTestCase {
}
func testGRDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
measureBlock {
@@ -66,7 +66,7 @@ class FetchNamedValuesTests: XCTestCase {
}
func testSQLiteSwift() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
self.measureBlock {
@@ -8,13 +8,13 @@ private let expectedRowCount = 100_000
class FetchPositionalValuesTests: XCTestCase {
func testSQLite() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
var connection: COpaquePointer = nil
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
var connection: OpaquePointer = nil
sqlite3_open_v2(databasePath, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil)
self.measureBlock {
var count = 0
var statement: COpaquePointer = nil
var statement: OpaquePointer = nil
sqlite3_prepare_v2(connection, "SELECT * FROM items", -1, &statement, nil)
loop: while true {
@@ -49,7 +49,7 @@ class FetchPositionalValuesTests: XCTestCase {
}
func testFMDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
@@ -79,7 +79,7 @@ class FetchPositionalValuesTests: XCTestCase {
}
func testGRDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
measureBlock {
@@ -107,7 +107,7 @@ class FetchPositionalValuesTests: XCTestCase {
}
func testSQLiteSwift() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
self.measureBlock {
+10 -10
View File
@@ -10,15 +10,15 @@ private let expectedRowCount = 100_000
class FetchRecordTests: XCTestCase {
func testSQLite() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
var connection: COpaquePointer = nil
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
var connection: OpaquePointer = nil
sqlite3_open_v2(databasePath, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil)
self.measureBlock {
var statement: COpaquePointer = nil
var statement: OpaquePointer = 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 columnNames = (Int32(0)..<10).map { String(cString: sqlite3_column_name(statement, $0))! }
let index0 = Int32(columnNames.indexOf("i0")!)
let index1 = Int32(columnNames.indexOf("i1")!)
let index2 = Int32(columnNames.indexOf("i2")!)
@@ -68,7 +68,7 @@ class FetchRecordTests: XCTestCase {
func testFMDB() {
// Here we test the loading of an array of Records.
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = FMDatabaseQueue(path: databasePath)
self.measureBlock {
@@ -89,7 +89,7 @@ class FetchRecordTests: XCTestCase {
}
func testGRDB() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let dbQueue = try! DatabaseQueue(path: databasePath)
measureBlock {
@@ -104,7 +104,7 @@ class FetchRecordTests: XCTestCase {
}
func testSQLiteSwift() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")!
let db = try! Connection(databasePath)
self.measureBlock {
@@ -131,8 +131,8 @@ class FetchRecordTests: XCTestCase {
}
func testCoreData() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceCoreDataTests", ofType: "sqlite")!
let modelURL = NSBundle(forClass: self.dynamicType).URLForResource("PerformanceModel", withExtension: "momd")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceCoreDataTests", ofType: "sqlite")!
let modelURL = NSBundle(for: 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)
@@ -159,7 +159,7 @@ class FetchRecordTests: XCTestCase {
}
func testRealm() {
let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceRealmTests", ofType: "realm")!
let databasePath = NSBundle(for: self.dynamicType).pathForResource("PerformanceRealmTests", ofType: "realm")!
let realm = try! Realm(path: databasePath)
measureBlock {
+11 -11
View File
@@ -9,7 +9,7 @@ class InsertNamedValuesTests: XCTestCase {
func testFMDB() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -17,11 +17,11 @@ class InsertNamedValuesTests: XCTestCase {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
measureBlock {
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -39,7 +39,7 @@ class InsertNamedValuesTests: XCTestCase {
func testGRDB() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -47,11 +47,11 @@ class InsertNamedValuesTests: XCTestCase {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
measureBlock {
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
@@ -59,18 +59,18 @@ class InsertNamedValuesTests: XCTestCase {
}
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)")
let statement = try! db.makeUpdateStatement("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
return .commit
}
}
}
func testSQLiteSwift() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -78,11 +78,11 @@ class InsertNamedValuesTests: XCTestCase {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
measureBlock {
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let db = try! Connection(databasePath)
try! db.run(itemsTable.create { t in
@@ -9,7 +9,7 @@ class InsertPositionalValuesTests: XCTestCase {
func testSQLite() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -17,19 +17,19 @@ class InsertPositionalValuesTests: XCTestCase {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
measureBlock {
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
var connection: COpaquePointer = nil
var connection: OpaquePointer = 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
var statement: OpaquePointer = 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) {
@@ -55,7 +55,7 @@ class InsertPositionalValuesTests: XCTestCase {
func testFMDB() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -63,10 +63,10 @@ class InsertPositionalValuesTests: XCTestCase {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
measureBlock {
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -84,7 +84,7 @@ class InsertPositionalValuesTests: XCTestCase {
func testGRDB() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -92,10 +92,10 @@ class InsertPositionalValuesTests: XCTestCase {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
measureBlock {
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
@@ -103,18 +103,18 @@ class InsertPositionalValuesTests: XCTestCase {
}
try! dbQueue.inTransaction { db in
let statement = try! db.updateStatement("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)")
let statement = try! db.makeUpdateStatement("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
return .commit
}
}
}
func testSQLiteSwift() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -122,10 +122,10 @@ class InsertPositionalValuesTests: XCTestCase {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
measureBlock {
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let db = try! Connection(databasePath)
try! db.run(itemsTable.create { t in
+10 -10
View File
@@ -10,8 +10,8 @@ class InsertRecordTests: XCTestCase {
func testGRDB() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
@@ -19,11 +19,11 @@ class InsertRecordTests: XCTestCase {
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)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
measureBlock {
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
@@ -34,15 +34,15 @@ class InsertRecordTests: XCTestCase {
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
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 databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
let modelURL = NSBundle(for: self.dynamicType).URLForResource("PerformanceModel", withExtension: "momd")!
let mom = NSManagedObjectModel(contentsOfURL: modelURL)!
measureBlock {
@@ -66,16 +66,16 @@ class InsertRecordTests: XCTestCase {
}
try! moc.save()
try! psc.removePersistentStore(store)
try! NSFileManager.defaultManager().removeItemAtPath(databasePath)
try! NSFileManager.default().removeItem(atPath: databasePath)
}
}
func testRealm() {
let databaseFileName = "GRDBPerformanceTests-\(NSProcessInfo.processInfo().globallyUniqueString).realm"
let databasePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(databaseFileName)
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
measureBlock {
_ = try? NSFileManager.defaultManager().removeItemAtPath(databasePath)
_ = try? NSFileManager.default().removeItem(atPath: databasePath)
let realm = try! Realm(path: databasePath)
try! realm.write {
+2 -2
View File
@@ -50,7 +50,7 @@ class Item : Record {
return "items"
}
required init(_ row: GRDB.Row) {
required init(row: GRDB.Row) {
i0 = row.value(named: "i0")
i1 = row.value(named: "i1")
i2 = row.value(named: "i2")
@@ -61,7 +61,7 @@ class Item : Record {
i7 = row.value(named: "i7")
i8 = row.value(named: "i8")
i9 = row.value(named: "i9")
super.init(row)
super.init(row: row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
@@ -9,7 +9,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
func testDatabasePoolDeinitClosesAllConnections() {
assertNoError {
let countQueue = dispatch_queue_create(nil, nil)
let countQueue = dispatch_queue_create(nil, nil)!
var openConnectionCount = 0
var totalOpenConnectionCount = 0
@@ -49,7 +49,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
func testDatabasePoolReleaseMemoryClosesReaderConnections() {
assertNoError {
let countQueue = dispatch_queue_create(nil, nil)
let countQueue = dispatch_queue_create(nil, nil)!
var openConnectionCount = 0
var totalOpenConnectionCount = 0
@@ -78,35 +78,35 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
// SELECT * FROM items
// step
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// SELECT * FROM items
// step
// >
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// step step
// >
let s3 = dispatch_semaphore_create(0)
let s3 = dispatch_semaphore_create(0)!
// end end releaseMemory
let block1 = { () in
dbPool.read { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s3)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() == nil)
}
}
let block2 = { () in
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
dbPool.read { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s2)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
}
}
let block3 = { () in
@@ -128,7 +128,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
func testBlocksRetainConnection() {
assertNoError {
let countQueue = dispatch_queue_create(nil, nil)
let countQueue = dispatch_queue_create(nil, nil)!
var openConnectionCount = 0
var totalOpenConnectionCount = 0
@@ -148,10 +148,10 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
// Block 1 Block 2
// read {
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// dbPool = nil
// >
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// use database
// }
@@ -193,14 +193,14 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
}
}
func testDatabaseGeneratorRetainConnection() {
func testDatabaseIteratorRetainConnection() {
// Until iOS 8.2, OSX 10.10, GRDB does not support deallocating a
// database when some statements are not finalized.
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
assertNoError {
let countQueue = dispatch_queue_create(nil, nil)
let countQueue = dispatch_queue_create(nil, nil)!
var openConnectionCount = 0
var totalOpenConnectionCount = 0
@@ -222,10 +222,10 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
// SELECT
// step
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// dbPool = nil
// >
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// step
// end
// }
@@ -245,13 +245,13 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
}
let block2 = { [weak dbPool] () in
weak var connection: Database? = nil
var generator: DatabaseGenerator<Int>? = nil
var iterator: DatabaseIterator<Int>? = nil
do {
if let dbPool = dbPool {
dbPool.write { db in
connection = db
generator = Int.fetch(db, "SELECT id FROM items").generate()
XCTAssertTrue(generator!.next() != nil)
iterator = Int.fetch(db, "SELECT id FROM items").makeIterator()
XCTAssertTrue(iterator!.next() != nil)
dispatch_semaphore_signal(s1)
}
} else {
@@ -261,9 +261,9 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
do {
XCTAssertTrue(dbPool == nil)
XCTAssertTrue(generator!.next() != nil)
XCTAssertTrue(generator!.next() == nil)
generator = nil
XCTAssertTrue(iterator!.next() != nil)
XCTAssertTrue(iterator!.next() == nil)
iterator = nil
XCTAssertTrue(connection == nil)
}
}
@@ -293,10 +293,10 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
// Block 1 Block 2
// create statement INSERT
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// dbPool = nil
// >
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// dbPool is nil
let (block1, block2) = { () -> (() -> (), () -> ()) in
@@ -312,7 +312,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
if let dbPool = dbPool {
do {
try dbPool.write { db in
statement = try db.updateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
statement = try db.makeUpdateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
dispatch_semaphore_signal(s1)
}
} catch {
@@ -17,12 +17,12 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
dbPool.write { db in
// Assert that the writer cache is empty
XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil)
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
}
dbPool.read { db in
// Assert that a reader cache is empty
XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil)
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
}
try dbPool.read { db in
@@ -31,12 +31,12 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
XCTAssertEqual(primaryKey.rowIDColumn, "id")
// Assert that reader cache is warmed
XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") != nil)
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
}
dbPool.write { db in
// Assert that writer cache is warmed
XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") != nil)
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
}
try dbPool.write { db in
@@ -44,12 +44,12 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
try db.execute("DROP TABLE items")
// Assert that the writer cache is empty
XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil)
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
}
dbPool.read { db in
// Assert that a reader cache is empty
XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil)
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
}
try dbPool.read { db in
@@ -83,7 +83,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
// Block 1 Block 2
// SELECT 1 FROM items WHERE id = 1
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// SELECT 1 FROM items WHERE id = 1
let block1 = { () in
@@ -9,7 +9,7 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
func testDatabaseQueueuDeinitClosesConnection() {
assertNoError {
let countQueue = dispatch_queue_create(nil, nil)
let countQueue = dispatch_queue_create(nil, nil)!
var openConnectionCount = 0
var totalOpenConnectionCount = 0
@@ -41,7 +41,7 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
func testBlocksRetainConnection() {
assertNoError {
let countQueue = dispatch_queue_create(nil, nil)
let countQueue = dispatch_queue_create(nil, nil)!
var openConnectionCount = 0
var totalOpenConnectionCount = 0
@@ -61,10 +61,10 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
// Block 1 Block 2
// inDatabase {
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// dbQueue = nil
// >
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// use database
// }
@@ -106,14 +106,14 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
}
}
func testDatabaseGeneratorRetainConnection() {
func testDatabaseIteratorRetainConnection() {
// Until iOS 8.2, OSX 10.10, GRDB does not support deallocating a
// database when some statements are not finalized.
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
assertNoError {
let countQueue = dispatch_queue_create(nil, nil)
let countQueue = dispatch_queue_create(nil, nil)!
var openConnectionCount = 0
var totalOpenConnectionCount = 0
@@ -135,10 +135,10 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
// SELECT
// step
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// dbQueue = nil
// >
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// step
// end
// }
@@ -158,13 +158,13 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
}
let block2 = { [weak dbQueue] () in
weak var connection: Database? = nil
var generator: DatabaseGenerator<Int>? = nil
var iterator: DatabaseIterator<Int>? = nil
do {
if let dbQueue = dbQueue {
dbQueue.write { db in
connection = db
generator = Int.fetch(db, "SELECT id FROM items").generate()
XCTAssertTrue(generator!.next() != nil)
iterator = Int.fetch(db, "SELECT id FROM items").makeIterator()
XCTAssertTrue(iterator!.next() != nil)
dispatch_semaphore_signal(s1)
}
} else {
@@ -174,9 +174,9 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
do {
XCTAssertTrue(dbQueue == nil)
XCTAssertTrue(generator!.next() != nil)
XCTAssertTrue(generator!.next() == nil)
generator = nil
XCTAssertTrue(iterator!.next() != nil)
XCTAssertTrue(iterator!.next() == nil)
iterator = nil
XCTAssertTrue(connection == nil)
}
}
@@ -206,10 +206,10 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
// Block 1 Block 2
// create statement INSERT
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// dbQueue = nil
// >
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// dbQueue is nil
let (block1, block2) = { () -> (() -> (), () -> ()) in
@@ -226,7 +226,7 @@ class DatabaseQueueuReleaseMemoryTests: GRDBTestCase {
if let dbQueue = dbQueue {
do {
try dbQueue.write { db in
statement = try db.updateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
statement = try db.makeUpdateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
dispatch_semaphore_signal(s1)
}
} catch {
@@ -17,7 +17,7 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
dbQueue.inDatabase { db in
// Assert that cache is empty
XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil)
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
}
try dbQueue.inDatabase { db in
@@ -26,7 +26,7 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
XCTAssertEqual(primaryKey.rowIDColumn, "id")
// Assert that cache is warmed
XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") != nil)
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
}
try dbQueue.inDatabase { db in
@@ -34,7 +34,7 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
try db.execute("DROP TABLE items")
// Assert that cache is empty
XCTAssertTrue(db.schemaCache.primaryKey(tableName: "items") == nil)
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
}
try dbQueue.inDatabase { db in
+2 -2
View File
@@ -26,7 +26,7 @@ class NSDataMemoryTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE datas (data BLOB)")
let data = "foo".dataUsingEncoding(NSUTF8StringEncoding)
let data = "foo".data(using: NSUTF8StringEncoding)
try db.execute("INSERT INTO datas (data) VALUES (?)", arguments: [data])
for row in Row.fetch(db, "SELECT * FROM datas") {
@@ -51,7 +51,7 @@ class NSDataMemoryTests: GRDBTestCase {
let row = Row.fetchOne(db, "SELECT * FROM datas")!
let databaseValue = row.first!.1
switch databaseValue.storage {
case .Blob(let data):
case .blob(let data):
do {
// This data should not be copied:
let nonCopiedData: NSData = row.value(atIndex: 0)
@@ -13,7 +13,7 @@ class StatementInformationTests : GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE foo (id INTEGER)")
try db.execute("CREATE TABLE bar (id INTEGER, fooId INTEGER)")
let statement = try db.selectStatement("SELECT * FROM FOO JOIN BAR ON fooId = foo.id")
let statement = try db.makeSelectStatement("SELECT * FROM FOO JOIN BAR ON fooId = foo.id")
XCTAssertTrue(statement.sourceTables.count == 2)
XCTAssertTrue(statement.sourceTables.contains("foo"))
XCTAssertTrue(statement.sourceTables.contains("bar"))
@@ -26,16 +26,16 @@ class StatementInformationTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let statement = try db.updateStatement("CREATE TABLE foo (id INTEGER)")
let statement = try db.makeUpdateStatement("CREATE TABLE foo (id INTEGER)")
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
try statement.execute()
}
do {
let statement = try db.updateStatement("ALTER TABLE foo ADD COLUMN name TEXT")
let statement = try db.makeUpdateStatement("ALTER TABLE foo ADD COLUMN name TEXT")
XCTAssertTrue(statement.invalidatesDatabaseSchemaCache)
}
do {
let statement = try db.updateStatement("DROP TABLE foo")
let statement = try db.makeUpdateStatement("DROP TABLE foo")
XCTAssertTrue(statement.invalidatesDatabaseSchemaCache)
}
}
@@ -49,12 +49,12 @@ class CollationTests: GRDBTestCase {
if length1 == length2 {
return (string1 as NSString).compare(string2)
} else if length1 < length2 {
return .OrderedAscending
return .orderedAscending
} else {
return .OrderedDescending
return .orderedDescending
}
}
dbQueue.addCollation(collation)
dbQueue.add(collation: collation)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT COLLATE LOCALIZED_STANDARD)")
+10 -10
View File
@@ -44,7 +44,7 @@ class DatabaseTests : GRDBTestCase {
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
// The tested function:
let statement = try db.updateStatement("INSERT INTO persons (name, age) VALUES ('Arthur', 41)")
let statement = try db.makeUpdateStatement("INSERT INTO persons (name, age) VALUES ('Arthur', 41)")
try statement.execute()
let row = Row.fetchOne(db, "SELECT * FROM persons")!
@@ -60,7 +60,7 @@ class DatabaseTests : GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
let statement = try db.updateStatement("INSERT INTO persons (name, age) VALUES (?, ?)")
let statement = try db.makeUpdateStatement("INSERT INTO persons (name, age) VALUES (?, ?)")
try statement.execute(arguments: ["Arthur", 41])
let row = Row.fetchOne(db, "SELECT * FROM persons")!
@@ -76,7 +76,7 @@ class DatabaseTests : GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
let statement = try db.updateStatement("INSERT INTO persons (name, age) VALUES (:name, :age)")
let statement = try db.makeUpdateStatement("INSERT INTO persons (name, age) VALUES (:name, :age)")
try statement.execute(arguments: ["name": "Arthur", "age": 41])
let row = Row.fetchOne(db, "SELECT * FROM persons")!
@@ -170,7 +170,7 @@ class DatabaseTests : GRDBTestCase {
try db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41])
try db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil])
let statement = try db.selectStatement("SELECT * FROM persons")
let statement = try db.makeSelectStatement("SELECT * FROM persons")
let rows = Row.fetchAll(statement)
XCTAssertEqual(rows.count, 2)
}
@@ -185,7 +185,7 @@ class DatabaseTests : GRDBTestCase {
try db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41])
try db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil])
let statement = try db.selectStatement("SELECT * FROM persons WHERE name = ?")
let statement = try db.makeSelectStatement("SELECT * FROM persons WHERE name = ?")
let rows = Row.fetchAll(statement, arguments: ["Arthur"])
XCTAssertEqual(rows.count, 1)
}
@@ -200,7 +200,7 @@ class DatabaseTests : GRDBTestCase {
try db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur", "age": 41])
try db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Barbara", "age": nil])
let statement = try db.selectStatement("SELECT * FROM persons WHERE name = :name")
let statement = try db.makeSelectStatement("SELECT * FROM persons WHERE name = :name")
let rows = Row.fetchAll(statement, arguments: ["name": "Arthur"])
XCTAssertEqual(rows.count, 1)
}
@@ -278,7 +278,7 @@ class DatabaseTests : GRDBTestCase {
XCTAssertEqual(names2[0]!, "Arthur")
XCTAssertEqual(names2[1]!, "Barbara")
return .Commit
return .commit
}
}
}
@@ -300,7 +300,7 @@ class DatabaseTests : GRDBTestCase {
XCTAssertEqual(names2[0], "Arthur")
XCTAssertEqual(names2[1], "Barbara")
return .Commit
return .commit
}
}
}
@@ -339,7 +339,7 @@ class DatabaseTests : GRDBTestCase {
} catch {
XCTFail()
}
return .Commit
return .commit
}
XCTFail()
} catch let error as DatabaseError {
@@ -350,7 +350,7 @@ class DatabaseTests : GRDBTestCase {
}
// Make sure we can open another transaction
try dbQueue.inTransaction { db in .Commit }
try dbQueue.inTransaction { db in .commit }
}
}
}
@@ -15,7 +15,7 @@ class InMemoryDatabaseTests : GRDBTestCase
try db.execute("INSERT INTO foo (bar) VALUES ('baz')")
let baz = String.fetchOne(db, "SELECT bar FROM foo")!
XCTAssertEqual(baz, "baz")
return .Rollback
return .rollback
}
}
}
@@ -18,7 +18,7 @@ class ReadOnlyDatabaseTests : GRDBTestCase {
dbConfiguration.readonly = true
let dbQueue = try makeDatabaseQueue()
let statement = try dbQueue.inDatabase { db in
try db.updateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.makeUpdateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
do {
try dbQueue.inDatabase { db in
@@ -17,13 +17,13 @@ class DatabaseErrorTests: GRDBTestCase {
self.sqlQueries.removeAll()
try db.execute("INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
XCTFail()
return .Commit
return .commit
}
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 19) // SQLITE_CONSTRAINT
XCTAssertEqual(error.message!.lowercaseString, "foreign key constraint failed") // lowercaseString: accept multiple SQLite version
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercaseString, "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
XCTAssertEqual(sqlQueries.count, 2)
XCTAssertEqual(sqlQueries[0], "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
@@ -45,7 +45,7 @@ class DatabaseErrorTests: GRDBTestCase {
self.sqlQueries.removeAll()
try db.execute("INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
XCTFail()
return .Commit
return .commit
}
XCTFail()
} catch {
@@ -55,9 +55,9 @@ class DatabaseErrorTests: GRDBTestCase {
}
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 19) // SQLITE_CONSTRAINT
XCTAssertEqual(error.message!.lowercaseString, "foreign key constraint failed") // lowercaseString: accept multiple SQLite version
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercaseString, "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
}
}
}
@@ -77,38 +77,38 @@ class DatabaseErrorTests: GRDBTestCase {
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 19) // SQLITE_CONSTRAINT
XCTAssertEqual(error.message!.lowercaseString, "foreign key constraint failed") // lowercaseString: accept multiple SQLite version
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercaseString, "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
}
}
// statement.execute(arguments)
try dbQueue.inDatabase { db in
do {
let statement = try db.updateStatement("INSERT INTO pets (masterId, name) VALUES (?, ?)")
let statement = try db.makeUpdateStatement("INSERT INTO pets (masterId, name) VALUES (?, ?)")
try statement.execute(arguments: [1, "Bobby"])
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 19) // SQLITE_CONSTRAINT
XCTAssertEqual(error.message!.lowercaseString, "foreign key constraint failed") // lowercaseString: accept multiple SQLite version
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercaseString, "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
}
}
// statement.execute()
try dbQueue.inDatabase { db in
do {
let statement = try db.updateStatement("INSERT INTO pets (masterId, name) VALUES (?, ?)")
let statement = try db.makeUpdateStatement("INSERT INTO pets (masterId, name) VALUES (?, ?)")
statement.arguments = [1, "Bobby"]
try statement.execute()
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 19) // SQLITE_CONSTRAINT
XCTAssertEqual(error.message!.lowercaseString, "foreign key constraint failed") // lowercaseString: accept multiple SQLite version
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
XCTAssertEqual(error.description.lowercaseString, "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed")
}
}
}
@@ -126,9 +126,9 @@ class DatabaseErrorTests: GRDBTestCase {
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.code, 19) // SQLITE_CONSTRAINT
XCTAssertEqual(error.message!.lowercaseString, "foreign key constraint failed") // lowercaseString: accept multiple SQLite version
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
XCTAssertEqual(error.description.lowercaseString, "sqlite error 19 with statement `insert into pets (masterid, name) values (1, 'bobby')`: foreign key constraint failed")
XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (1, 'bobby')`: foreign key constraint failed")
}
}
}
@@ -9,8 +9,8 @@ class DatabasePoolBackupTests: GRDBTestCase {
func testBackup() {
assertNoError {
let source = try makeDatabasePool("source.sqlite")
let destination = try makeDatabasePool("destination.sqlite")
let source = try makeDatabasePool(filename: "source.sqlite")
let destination = try makeDatabasePool(filename: "destination.sqlite")
try source.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
@@ -38,8 +38,8 @@ class DatabasePoolBackupTests: GRDBTestCase {
func testConcurrentWriteDuringBackup() {
assertNoError {
let source = try makeDatabasePool("source.sqlite")
let destination = try makeDatabasePool("destination.sqlite")
let source = try makeDatabasePool(filename: "source.sqlite")
let destination = try makeDatabasePool(filename: "destination.sqlite")
try source.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
@@ -47,14 +47,14 @@ class DatabasePoolBackupTests: GRDBTestCase {
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
}
let s1 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
let s2 = dispatch_semaphore_create(0)!
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
try! source.writeInTransaction(.Immediate) { db in
try! source.writeInTransaction(.immediate) { db in
try db.execute("INSERT INTO items (id) VALUES (NULL)")
dispatch_semaphore_signal(s2)
return .Commit
return .commit
}
}
@@ -12,9 +12,9 @@ class DatabasePoolCollationTests: GRDBTestCase {
let dbPool = try makeDatabasePool()
let collation1 = DatabaseCollation("collation1") { (string1, string2) in
return (string1 == string2) ? .OrderedSame : ((string1 < string2) ? .OrderedAscending : .OrderedDescending)
return (string1 == string2) ? .orderedSame : ((string1 < string2) ? .orderedAscending : .orderedDescending)
}
dbPool.addCollation(collation1)
dbPool.add(collation: collation1)
try dbPool.write { db in
try db.execute("CREATE TABLE items (text TEXT COLLATE collation1)")
@@ -28,9 +28,9 @@ class DatabasePoolCollationTests: GRDBTestCase {
}
let collation2 = DatabaseCollation("collation2") { (string1, string2) in
return (string1 == string2) ? .OrderedSame : ((string1 < string2) ? .OrderedDescending : .OrderedAscending)
return (string1 == string2) ? .orderedSame : ((string1 < string2) ? .orderedDescending : .orderedAscending)
}
dbPool.addCollation(collation2)
dbPool.add(collation: collation2)
dbPool.read { db in
XCTAssertEqual(String.fetchAll(db, "SELECT text FROM items ORDER BY text COLLATE collation2"), ["c", "b", "a"])
@@ -36,10 +36,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// SELECT * FROM items SELECT * FROM items
// step step
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// step
// <
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// step step
// step end
// end COMMIT
@@ -47,24 +47,24 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
dbPool.read { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
}
}
let block2 = { () in
dbPool.read { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s2)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
}
}
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
@@ -89,22 +89,22 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// SELECT * FROM items
// step
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// DELETE * FROM items
// <
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// step
// end
// COMMIT
let block1 = { () in
dbPool.read { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
}
}
let block2 = { () in
@@ -140,23 +140,23 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// SELECT * FROM items
// step
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// DELETE * FROM items
// Checkpoint
// <
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// step
// end
// COMMIT
let block1 = { () in
dbPool.read { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
}
}
let block2 = { () in
@@ -189,11 +189,11 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// BEGIN DEFERRED TRANSACTION
// SELECT COUNT(*) FROM items -> 0
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// INSERT INTO items (id) VALUES (NULL)
// Checkpoint
// <
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// SELECT COUNT(*) FROM items -> 0
// COMMIT
@@ -235,33 +235,33 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// BEGIN IMMEDIATE TRANSACTION
// INSERT INTO items (id) VALUES (NULL)
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// BEGIN DEFERRED TRANSACTION
// SELECT COUNT(*) FROM items -> 0
// <
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// INSERT INTO items (id) VALUES (NULL)
// >
let s3 = dispatch_semaphore_create(0)
let s3 = dispatch_semaphore_create(0)!
// SELECT COUNT(*) FROM items -> 0
// <
let s4 = dispatch_semaphore_create(0)
let s4 = dispatch_semaphore_create(0)!
// COMMIT
// >
let s5 = dispatch_semaphore_create(0)
let s5 = dispatch_semaphore_create(0)!
// SELECT COUNT(*) FROM items -> 0
// COMMIT
let block1 = { () in
do {
try dbPool.writeInTransaction(.Immediate) { db in
try dbPool.writeInTransaction(.immediate) { db in
try db.execute("INSERT INTO items (id) VALUES (NULL)")
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
try db.execute("INSERT INTO items (id) VALUES (NULL)")
dispatch_semaphore_signal(s3)
dispatch_semaphore_wait(s4, DISPATCH_TIME_FOREVER)
return .Commit
return .commit
}
dispatch_semaphore_signal(s5)
} catch {
@@ -301,22 +301,22 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// SELECT * FROM items
// step
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// DELETE * FROM items
// <
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// step
// end
// SELECT COUNT(*) FROM items -> 0
let block1 = { () in
dbPool.nonIsolatedRead { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
}
}
@@ -352,22 +352,22 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// SELECT * FROM items
// step
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// DELETE * FROM items
// Checkpoint
// <
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// step
// end
let block1 = { () in
dbPool.nonIsolatedRead { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
}
}
let block2 = { () in
@@ -399,11 +399,11 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// Block 1 Block 2
// SELECT COUNT(*) FROM items -> 0
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// INSERT INTO items (id) VALUES (NULL)
// Checkpoint
// <
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// SELECT COUNT(*) FROM items -> 1
let block1 = { () in
@@ -10,34 +10,34 @@ class DatabasePoolFileAttributesTests: GRDBTestCase {
func testDefaultFileAttributes() {
assertNoError {
let dbPool = try makeDatabasePool()
let fm = NSFileManager.defaultManager()
let fm = NSFileManager.default()
try dbPool.write { db in
try db.execute("CREATE TABLE foo (bar INTEGER)")
}
var attributes = try fm.attributesOfItemAtPath(dbPool.path)
var attributes = try fm.attributesOfItem(atPath: dbPool.path)
XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
attributes = try fm.attributesOfItemAtPath(dbPool.path + "-wal")
attributes = try fm.attributesOfItem(atPath: dbPool.path + "-wal")
XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
attributes = try fm.attributesOfItemAtPath(dbPool.path + "-shm")
attributes = try fm.attributesOfItem(atPath: dbPool.path + "-shm")
XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
}
}
func testExplicitFileAttributesOnExistingFile() {
assertNoError {
let fm = NSFileManager.defaultManager()
let fm = NSFileManager.default()
do {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE foo (bar INTEGER)")
}
var attributes = try fm.attributesOfItemAtPath(dbPool.path)
var attributes = try fm.attributesOfItem(atPath: dbPool.path)
XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
attributes = try fm.attributesOfItemAtPath(dbPool.path + "-wal")
attributes = try fm.attributesOfItem(atPath: dbPool.path + "-wal")
XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
attributes = try fm.attributesOfItemAtPath(dbPool.path + "-shm")
attributes = try fm.attributesOfItem(atPath: dbPool.path + "-shm")
XCTAssertFalse((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
}
@@ -46,12 +46,12 @@ class DatabasePoolFileAttributesTests: GRDBTestCase {
let dbPool = try makeDatabasePool()
// TODO: this test is fragile: we have to wait until the database
// store has been notified of file creation.
NSThread.sleepForTimeInterval(0.1)
var attributes = try fm.attributesOfItemAtPath(dbPool.path)
NSThread.sleep(forTimeInterval: 0.1)
var attributes = try fm.attributesOfItem(atPath: dbPool.path)
XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
attributes = try fm.attributesOfItemAtPath(dbPool.path + "-wal")
attributes = try fm.attributesOfItem(atPath: dbPool.path + "-wal")
XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
attributes = try fm.attributesOfItemAtPath(dbPool.path + "-shm")
attributes = try fm.attributesOfItem(atPath: dbPool.path + "-shm")
XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
}
}
@@ -59,7 +59,7 @@ class DatabasePoolFileAttributesTests: GRDBTestCase {
func testExplicitFileAttributesOnNewFile() {
assertNoError {
let fm = NSFileManager.defaultManager()
let fm = NSFileManager.default()
dbConfiguration.fileAttributes = [NSFileExtensionHidden: true]
let dbPool = try makeDatabasePool()
@@ -68,12 +68,12 @@ class DatabasePoolFileAttributesTests: GRDBTestCase {
}
// TODO: this test is fragile: we have to wait until the database
// store has been notified of file creation.
NSThread.sleepForTimeInterval(0.1)
var attributes = try fm.attributesOfItemAtPath(dbPool.path)
NSThread.sleep(forTimeInterval: 0.1)
var attributes = try fm.attributesOfItem(atPath: dbPool.path)
XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
attributes = try fm.attributesOfItemAtPath(dbPool.path + "-wal")
attributes = try fm.attributesOfItem(atPath: dbPool.path + "-wal")
XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
attributes = try fm.attributesOfItemAtPath(dbPool.path + "-shm")
attributes = try fm.attributesOfItem(atPath: dbPool.path + "-shm")
XCTAssertTrue((attributes[NSFileExtensionHidden] as! NSNumber).boolValue)
}
}
@@ -15,7 +15,7 @@ class DatabasePoolFunctionTests: GRDBTestCase {
return databaseValues[0]
}
dbPool.addFunction(function1)
dbPool.add(function: function1)
try dbPool.write { db in
try db.execute("CREATE TABLE items (text TEXT)")
@@ -28,7 +28,7 @@ class DatabasePoolFunctionTests: GRDBTestCase {
let function2 = DatabaseFunction("function2", argumentCount: 1, pure: true) { (databaseValues: [DatabaseValue]) in
return "foo"
}
dbPool.addFunction(function2)
dbPool.add(function: function2)
dbPool.read { db in
XCTAssertTrue(String.fetchOne(db, "SELECT function2(text) FROM items") == "foo")
@@ -13,7 +13,7 @@ class DatabasePoolReadOnlyTests: GRDBTestCase {
// Create a non-WAL database:
do {
let dbQueue = try makeDatabaseQueue(databaseFileName)
let dbQueue = try makeDatabaseQueue(filename: databaseFileName)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
for _ in 0..<3 {
@@ -24,46 +24,46 @@ class DatabasePoolReadOnlyTests: GRDBTestCase {
// Open a read-only pool on that database:
dbConfiguration.readonly = true
let dbPool = try makeDatabasePool(databaseFileName)
let dbPool = try makeDatabasePool(filename: databaseFileName)
// Make sure the database is not in WAL mode
let mode = dbPool.read { db in
String.fetchOne(db, "PRAGMA journal_mode")!
}
XCTAssertNotEqual(mode.lowercaseString, "wal")
XCTAssertNotEqual(mode.lowercased(), "wal")
// Block 1 Block 2
// SELECT * FROM items SELECT * FROM items
// step step
// >
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// step
// <
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// step step
// step end
// end
let block1 = { () in
dbPool.read { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
}
}
let block2 = { () in
dbPool.read { db in
let generator = Row.fetch(db, "SELECT * FROM items").generate()
XCTAssertTrue(generator.next() != nil)
let iterator = Row.fetch(db, "SELECT * FROM items").makeIterator()
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(iterator.next() != nil)
dispatch_semaphore_signal(s2)
XCTAssertTrue(generator.next() != nil)
XCTAssertTrue(generator.next() == nil)
XCTAssertTrue(iterator.next() != nil)
XCTAssertTrue(iterator.next() == nil)
}
}
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
@@ -9,8 +9,8 @@ class DatabaseQueueBackupTests: GRDBTestCase {
func testBackup() {
assertNoError {
let source = try makeDatabaseQueue("source.sqlite")
let destination = try makeDatabaseQueue("destination.sqlite")
let source = try makeDatabaseQueue(filename: "source.sqlite")
let destination = try makeDatabaseQueue(filename: "destination.sqlite")
try source.inDatabase { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
@@ -21,7 +21,7 @@ class ConcurrencyTests: GRDBTestCase {
}
}
dbConfiguration.busyMode = .Callback(busyCallback)
dbConfiguration.busyMode = .callback(busyCallback)
}
func testWrappedReadWrite() {
@@ -53,33 +53,33 @@ class ConcurrencyTests: GRDBTestCase {
// Queue 1 Queue 2
// BEGIN DEFERRED TRANSACTION
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// BEGIN DEFERRED TRANSACTION
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// INSERT INTO stuffs (id) VALUES (NULL)
let s3 = dispatch_semaphore_create(0)
let s3 = dispatch_semaphore_create(0)!
// INSERT INTO stuffs (id) VALUES (NULL) <--- Error
// ROLLBACK
let s4 = dispatch_semaphore_create(0)
let s4 = dispatch_semaphore_create(0)!
// COMMIT
try! dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
}
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)
let group = dispatch_group_create()
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)!
let group = dispatch_group_create()!
// Queue 1
dispatch_group_async(group, queue) {
do {
try dbQueue1.inTransaction(.Deferred) { db in
try dbQueue1.inTransaction(.deferred) { db in
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
try db.execute("INSERT INTO stuffs (id) VALUES (NULL)")
dispatch_semaphore_signal(s3)
dispatch_semaphore_wait(s4, DISPATCH_TIME_FOREVER)
return .Commit
return .commit
}
}
catch {
@@ -92,11 +92,11 @@ class ConcurrencyTests: GRDBTestCase {
dispatch_group_async(group, queue) {
do {
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
try dbQueue2.inTransaction(.Deferred) { db in
try dbQueue2.inTransaction(.deferred) { db in
dispatch_semaphore_signal(s2)
dispatch_semaphore_wait(s3, DISPATCH_TIME_FOREVER)
try db.execute("INSERT INTO stuffs (id) VALUES (NULL)")
return .Commit
return .commit
}
}
catch let error as DatabaseError {
@@ -126,21 +126,21 @@ class ConcurrencyTests: GRDBTestCase {
// Queue 1 Queue 2
// BEGIN EXCLUSIVE TRANSACTION
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// BEGIN EXCLUSIVE TRANSACTION <--- Error
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// COMMIT
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)
let group = dispatch_group_create()
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)!
let group = dispatch_group_create()!
// Queue 1
dispatch_group_async(group, queue) {
do {
try dbQueue1.inTransaction(.Exclusive) { db in
try dbQueue1.inTransaction(.exclusive) { db in
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
return .Commit
return .commit
}
}
catch {
@@ -153,8 +153,8 @@ class ConcurrencyTests: GRDBTestCase {
dispatch_group_async(group, queue) {
do {
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
try dbQueue2.inTransaction(.Exclusive) { db in
return .Commit
try dbQueue2.inTransaction(.exclusive) { db in
return .commit
}
}
catch let error as DatabaseError {
@@ -184,21 +184,21 @@ class ConcurrencyTests: GRDBTestCase {
// Queue 1 Queue 2
// BEGIN IMMEDIATE TRANSACTION
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// BEGIN IMMEDIATE TRANSACTION <--- Error
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// COMMIT
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)
let group = dispatch_group_create()
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)!
let group = dispatch_group_create()!
// Queue 1
dispatch_group_async(group, queue) {
do {
try dbQueue1.inTransaction(.Immediate) { db in
try dbQueue1.inTransaction(.immediate) { db in
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
return .Commit
return .commit
}
}
catch {
@@ -211,8 +211,8 @@ class ConcurrencyTests: GRDBTestCase {
dispatch_group_async(group, queue) {
do {
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
try dbQueue2.inTransaction(.Immediate) { db in
return .Commit
try dbQueue2.inTransaction(.immediate) { db in
return .commit
}
}
catch let error as DatabaseError {
@@ -250,7 +250,7 @@ class ConcurrencyTests: GRDBTestCase {
// Queue 1 Queue 2
// BEGIN EXCLUSIVE TRANSACTION
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// (Waiting) BEGIN EXCLUSIVE TRANSACTION <--- Busy
// (Waiting) BEGIN EXCLUSIVE TRANSACTION <--- Busy
// (Waiting) BEGIN EXCLUSIVE TRANSACTION <--- Busy
@@ -265,16 +265,16 @@ class ConcurrencyTests: GRDBTestCase {
return true
}
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)
let group = dispatch_group_create()
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)!
let group = dispatch_group_create()!
// Queue 1
dispatch_group_async(group, queue) {
do {
try dbQueue1.inTransaction(.Exclusive) { db in
try dbQueue1.inTransaction(.exclusive) { db in
dispatch_semaphore_signal(s1)
usleep(100_000) // 0.1s
return .Commit
return .commit
}
}
catch {
@@ -286,8 +286,8 @@ class ConcurrencyTests: GRDBTestCase {
dispatch_group_async(group, queue) {
do {
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
try dbQueue2.inTransaction(.Exclusive) { db in
return .Commit
try dbQueue2.inTransaction(.exclusive) { db in
return .commit
}
}
catch {
@@ -319,19 +319,19 @@ class ConcurrencyTests: GRDBTestCase {
// Queue 1 Queue 2
// BEGIN IMMEDIATE TRANSACTION
// INSERT INTO stuffs (id) VALUES (NULL)
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// SELECT * FROM stuffs <--- 0 result
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// COMMIT
let s3 = dispatch_semaphore_create(0)
let s3 = dispatch_semaphore_create(0)!
// SELECT * FROM stuffs <--- 1 result
try! dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
}
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)
let group = dispatch_group_create()
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)!
let group = dispatch_group_create()!
// Queue 1
dispatch_group_async(group, queue) {
@@ -340,7 +340,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("INSERT INTO stuffs (id) VALUES (NULL)")
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
return .Commit
return .commit
}
}
catch {
@@ -393,10 +393,10 @@ class ConcurrencyTests: GRDBTestCase {
// Queue 1 Queue 2
// BEGIN IMMEDIATE TRANSACTION
// INSERT INTO stuffs (id) VALUES (NULL)
let s1 = dispatch_semaphore_create(0)
let s1 = dispatch_semaphore_create(0)!
// BEGIN DEFERRED TRANSACTION
// SELECT * FROM stuffs
let s2 = dispatch_semaphore_create(0)
let s2 = dispatch_semaphore_create(0)!
// COMMIT <--- Busy (Waiting)
// COMMIT <--- Busy (Waiting)
// COMMIT
@@ -413,8 +413,8 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
}
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)
let group = dispatch_group_create()
let queue = dispatch_queue_create("GRDB", DISPATCH_QUEUE_CONCURRENT)!
let group = dispatch_group_create()!
// Queue 1
dispatch_group_async(group, queue) {
@@ -423,7 +423,7 @@ class ConcurrencyTests: GRDBTestCase {
try db.execute("INSERT INTO stuffs (id) VALUES (NULL)")
dispatch_semaphore_signal(s1)
dispatch_semaphore_wait(s2, DISPATCH_TIME_FOREVER)
return .Commit
return .commit
}
}
catch {
@@ -435,11 +435,11 @@ class ConcurrencyTests: GRDBTestCase {
dispatch_group_async(group, queue) {
do {
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
try dbQueue2.inTransaction(.Deferred) { db in
try dbQueue2.inTransaction(.deferred) { db in
_ = Row.fetchAll(db, "SELECT * FROM stuffs")
dispatch_semaphore_signal(s2)
usleep(100_000) // 0.1s
return .Commit
return .commit
}
}
catch {
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more