WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

Make all fetch() methods @warn_unused_result

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder: better arithmetics

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder documentation

TODO.md

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

TODO.md

TODO.md

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

Rename DatabasePersistable to Persistable

Rename DatabaseTableMapping to TableMapping

WIP QueryBuilder documentation

WIP QueryBuilder documentation

Update GRDBDemoiOS so that it uses the Query Interface, and sorts people by name with a custom collation.

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

Configuration documentation

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder

WIP QueryBuilder

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder documentation

WIP QueryBuilder

README.md

README.md

README.md

README.md

README.md

README.md

README.md

README.md
This commit is contained in:
Gwendal Roué committed 2016-01-28 07:54:18 +01:00
1 parent 7c9d379aba
commit 3b3cb6bdec
38 files changed
+5193 -1299

No files matched your search

@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
56300B8A1C564EC8005A543B /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B891C564EC8005A543B /* Database.swift */; };
56900E421BBFF7D500B815B5 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56900E411BBFF7D500B815B5 /* PersonEditionViewController.swift */; };
56B8F4581B4E22B200C24296 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B8F4571B4E22B200C24296 /* AppDelegate.swift */; };
56B8F45A1B4E22B200C24296 /* MasterViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B8F4591B4E22B200C24296 /* MasterViewController.swift */; };
@@ -20,6 +21,20 @@
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
56300B901C564EC9005A543B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B8F4871B4E235C00C24296 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56553C181C3E906C00522B5C;
remoteInfo = GRDBOSXCrashTests;
};
56300B921C564EC9005A543B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B8F4871B4E235C00C24296 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 560C981A1C0E22D300BF8471;
remoteInfo = GRDBOSXPerformanceTests;
};
567AA8A41B4E3F120082C3E4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B8F4871B4E235C00C24296 /* GRDB.xcodeproj */;
@@ -88,6 +103,7 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
56300B891C564EC8005A543B /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
56900E411BBFF7D500B815B5 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
56B8F4541B4E22B200C24296 /* GRDBDemoiOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoiOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
56B8F4571B4E22B200C24296 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
@@ -117,7 +133,9 @@
isa = PBXGroup;
children = (
567AA8A51B4E3F120082C3E4 /* GRDB.framework */,
56300B911C564EC9005A543B /* GRDBOSXCrashTests.xctest */,
567AA8A71B4E3F120082C3E4 /* GRDBTests.xctest */,
56300B931C564EC9005A543B /* GRDBOSXPerformanceTests.xctest */,
567AA8A91B4E3F120082C3E4 /* GRDB.framework */,
567AA8AB1B4E3F120082C3E4 /* GRDBTests.xctest */,
);
@@ -188,6 +206,7 @@
isa = PBXGroup;
children = (
56B8F4571B4E22B200C24296 /* AppDelegate.swift */,
56300B891C564EC8005A543B /* Database.swift */,
56900E3E1BBFF2E900B815B5 /* Controllers */,
56900E3F1BBFF2F200B815B5 /* Models */,
56900E3C1BBFF2C400B815B5 /* Resources */,
@@ -260,6 +279,20 @@
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
56300B911C564EC9005A543B /* GRDBOSXCrashTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXCrashTests.xctest;
remoteRef = 56300B901C564EC9005A543B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56300B931C564EC9005A543B /* GRDBOSXPerformanceTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXPerformanceTests.xctest;
remoteRef = 56300B921C564EC9005A543B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
567AA8A51B4E3F120082C3E4 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
@@ -308,6 +341,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56300B8A1C564EC8005A543B /* Database.swift in Sources */,
56B8F45C1B4E22B200C24296 /* DetailViewController.swift in Sources */,
56B8F45A1B4E22B200C24296 /* MasterViewController.swift in Sources */,
56B8F4991B4E23AA00C24296 /* Person.swift in Sources */,
@@ -1,9 +1,4 @@
import UIKit
import GRDB
// The shared database queue, stored in a global.
// It is created in AppDelegate.application(_:didFinishLaunchingWithOptions:)
var dbQueue: DatabaseQueue!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
@@ -11,34 +6,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDele
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Connect to the database
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
let databasePath = documentsPath.stringByAppendingPathComponent("db.sqlite")
dbQueue = try! DatabaseQueue(path: databasePath)
// Use DatabaseMigrator to setup the database
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"firstName TEXT, " +
"lastName TEXT " +
")")
}
migrator.registerMigration("addPersons") { db in
try Person(firstName: "Arthur", lastName: "Miller").insert(db)
try Person(firstName: "Barbra", lastName: "Streisand").insert(db)
try Person(firstName: "Cinderella").insert(db)
}
try! migrator.migrate(dbQueue)
// Setup view controllers
// Set up database
setupDatabase()
// Set up view controllers
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
@@ -60,4 +31,3 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDele
}
}
@@ -0,0 +1,63 @@
import GRDB
// The columns for the GRDB Query Interface
//
// See https://github.com/groue/GRDB.swift/#the-query-interface
struct Col {
static let id = SQLColumn("id")
static let firstName = SQLColumn("firstName")
static let lastName = SQLColumn("lastName")
}
// The shared database queue, stored in a global.
// It is initialized in setupDatabase()
var dbQueue: DatabaseQueue!
func setupDatabase() {
// Connect to the database
//
// See https://github.com/groue/GRDB.swift/#database-queues
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
let databasePath = documentsPath.stringByAppendingPathComponent("db.sqlite")
dbQueue = try! DatabaseQueue(path: databasePath)
// SQLite does not support Unicode: let's add a custom collation which will
// allow us to sort persons by name.
//
// See https://github.com/groue/GRDB.swift/#string-comparison
let collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in
return (lhs as NSString).localizedCaseInsensitiveCompare(rhs)
}
dbQueue.inDatabase { db in
db.addCollation(collation)
}
// Use DatabaseMigrator to setup the database
//
// See https://github.com/groue/GRDB.swift/#migrations
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"firstName TEXT COLLATE localized_case_insensitive, " +
"lastName TEXT COLLATE localized_case_insensitive" +
")")
}
migrator.registerMigration("addPersons") { db in
try Person(firstName: "Arthur", lastName: "Miller").insert(db)
try Person(firstName: "Barbra", lastName: "Streisand").insert(db)
try Person(firstName: "Cinderella").insert(db)
}
try! migrator.migrate(dbQueue)
}
@@ -24,7 +24,7 @@ class MasterViewController: UITableViewController {
func reloadPersons() {
persons = dbQueue.inDatabase { db in
Person.fetchAll(db, "SELECT * FROM persons ORDER BY LOWER(firstName), LOWER(lastName)")
Person.order(Col.firstName, Col.lastName).fetchAll(db)
}
}
@@ -5,7 +5,7 @@ class Person : Record {
var firstName: String?
var lastName: String?
var fullName: String {
return [firstName, lastName].flatMap { $0 }.joinWithSeparator(" ")
return [firstName, lastName].flatMap { $0 }.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
init(firstName: String? = nil, lastName: String? = nil) {
@@ -15,36 +15,42 @@
562FF9EC1BCE903D00759400 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 562FF9EB1BCE903D00759400 /* libsqlite3.tbd */; };
562FF9EF1BCE912C00759400 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */; };
562FF9F21BCE914E00759400 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9F11BCE914E00759400 /* Person.swift */; };
563445081C4A8060003D3DC6 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445071C4A8060003D3DC6 /* Utils.swift */; };
56FCB3691C21210B00305D10 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3421C21210B00305D10 /* Configuration.swift */; };
56FCB36A1C21210B00305D10 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3431C21210B00305D10 /* Database.swift */; };
56FCB36C1C21210B00305D10 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3451C21210B00305D10 /* DatabaseError.swift */; };
56FCB36D1C21210B00305D10 /* DatabaseQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3461C21210B00305D10 /* DatabaseQueue.swift */; };
56FCB36E1C21210B00305D10 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3471C21210B00305D10 /* DatabaseValue.swift */; };
56FCB36F1C21210B00305D10 /* DatabasePersistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3491C21210B00305D10 /* DatabasePersistable.swift */; };
56FCB3701C21210B00305D10 /* DatabaseTableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB34A1C21210B00305D10 /* DatabaseTableMapping.swift */; };
56FCB3711C21210B00305D10 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB34B1C21210B00305D10 /* DatabaseValueConvertible.swift */; };
56FCB3721C21210B00305D10 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB34C1C21210B00305D10 /* RowConvertible.swift */; };
56FCB3731C21210B00305D10 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB34D1C21210B00305D10 /* SQLiteStatementConvertible.swift */; };
56FCB3741C21210B00305D10 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB34E1C21210B00305D10 /* Row.swift */; };
56FCB3761C21210B00305D10 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3501C21210B00305D10 /* Statement.swift */; };
56FCB3791C21210B00305D10 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3541C21210B00305D10 /* CGFloat.swift */; };
56FCB37A1C21210B00305D10 /* DatabaseCoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3561C21210B00305D10 /* DatabaseCoder.swift */; };
56FCB37B1C21210B00305D10 /* DatabaseDateComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3571C21210B00305D10 /* DatabaseDateComponents.swift */; };
56FCB37C1C21210B00305D10 /* DatabaseValue+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3581C21210B00305D10 /* DatabaseValue+Foundation.swift */; };
56FCB37D1C21210B00305D10 /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3591C21210B00305D10 /* NSData.swift */; };
56FCB37E1C21210B00305D10 /* NSDate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB35A1C21210B00305D10 /* NSDate.swift */; };
56FCB37F1C21210B00305D10 /* NSNull.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB35B1C21210B00305D10 /* NSNull.swift */; };
56FCB3801C21210B00305D10 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB35C1C21210B00305D10 /* NSNumber.swift */; };
56FCB3811C21210B00305D10 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB35D1C21210B00305D10 /* NSString.swift */; };
56FCB3821C21210B00305D10 /* NSURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB35E1C21210B00305D10 /* NSURL.swift */; };
56FCB3831C21210B00305D10 /* Row+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB35F1C21210B00305D10 /* Row+Foundation.swift */; };
56FCB3841C21210B00305D10 /* StatementArguments+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3601C21210B00305D10 /* StatementArguments+Foundation.swift */; };
56FCB3851C21210B00305D10 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3621C21210B00305D10 /* DatabaseMigrator.swift */; };
56FCB3861C21210B00305D10 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3631C21210B00305D10 /* Migration.swift */; };
56FCB3871C21210B00305D10 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3651C21210B00305D10 /* Record.swift */; };
56FCB3881C21210B00305D10 /* RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3671C21210B00305D10 /* RawRepresentable.swift */; };
56FCB3891C21210B00305D10 /* StandardLibraryTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FCB3681C21210B00305D10 /* StandardLibraryTypes.swift */; };
566A20F31C58A4B300C5A218 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F21C58A4B300C5A218 /* AppDatabase.swift */; };
566A21271C58A54F00C5A218 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F61C58A54F00C5A218 /* Configuration.swift */; };
566A21281C58A54F00C5A218 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F71C58A54F00C5A218 /* Database.swift */; };
566A21291C58A54F00C5A218 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F81C58A54F00C5A218 /* DatabaseError.swift */; };
566A212A1C58A54F00C5A218 /* DatabaseQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F91C58A54F00C5A218 /* DatabaseQueue.swift */; };
566A212B1C58A54F00C5A218 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FA1C58A54F00C5A218 /* DatabaseValue.swift */; };
566A212C1C58A54F00C5A218 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FC1C58A54F00C5A218 /* DatabaseValueConvertible.swift */; };
566A212D1C58A54F00C5A218 /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FD1C58A54F00C5A218 /* Persistable.swift */; };
566A212E1C58A54F00C5A218 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FE1C58A54F00C5A218 /* RowConvertible.swift */; };
566A212F1C58A54F00C5A218 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20FF1C58A54F00C5A218 /* SQLiteStatementConvertible.swift */; };
566A21301C58A54F00C5A218 /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21001C58A54F00C5A218 /* TableMapping.swift */; };
566A21311C58A54F00C5A218 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21011C58A54F00C5A218 /* Row.swift */; };
566A21321C58A54F00C5A218 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21021C58A54F00C5A218 /* Statement.swift */; };
566A21331C58A54F00C5A218 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21031C58A54F00C5A218 /* Utils.swift */; };
566A21341C58A54F00C5A218 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21051C58A54F00C5A218 /* CGFloat.swift */; };
566A21351C58A54F00C5A218 /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21071C58A54F00C5A218 /* FetchRequest.swift */; };
566A21361C58A54F00C5A218 /* Collation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21091C58A54F00C5A218 /* Collation.swift */; };
566A21371C58A54F00C5A218 /* Function.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210A1C58A54F00C5A218 /* Function.swift */; };
566A21381C58A54F00C5A218 /* Operator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210B1C58A54F00C5A218 /* Operator.swift */; };
566A21391C58A54F00C5A218 /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210C1C58A54F00C5A218 /* SQLQuery.swift */; };
566A213A1C58A54F00C5A218 /* DatabaseCoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210E1C58A54F00C5A218 /* DatabaseCoder.swift */; };
566A213B1C58A54F00C5A218 /* DatabaseDateComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A210F1C58A54F00C5A218 /* DatabaseDateComponents.swift */; };
566A213C1C58A54F00C5A218 /* DatabaseValue+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21101C58A54F00C5A218 /* DatabaseValue+Foundation.swift */; };
566A213D1C58A54F00C5A218 /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21111C58A54F00C5A218 /* NSData.swift */; };
566A213E1C58A54F00C5A218 /* NSDate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21121C58A54F00C5A218 /* NSDate.swift */; };
566A213F1C58A54F00C5A218 /* NSNull.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21131C58A54F00C5A218 /* NSNull.swift */; };
566A21401C58A54F00C5A218 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21141C58A54F00C5A218 /* NSNumber.swift */; };
566A21411C58A54F00C5A218 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21151C58A54F00C5A218 /* NSString.swift */; };
566A21421C58A54F00C5A218 /* NSURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21161C58A54F00C5A218 /* NSURL.swift */; };
566A21431C58A54F00C5A218 /* Row+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21171C58A54F00C5A218 /* Row+Foundation.swift */; };
566A21441C58A54F00C5A218 /* StatementArguments+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21181C58A54F00C5A218 /* StatementArguments+Foundation.swift */; };
566A21471C58A54F00C5A218 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */; };
566A21481C58A54F00C5A218 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A211F1C58A54F00C5A218 /* Migration.swift */; };
566A214A1C58A54F00C5A218 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21231C58A54F00C5A218 /* Record.swift */; };
566A214B1C58A54F00C5A218 /* RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21251C58A54F00C5A218 /* RawRepresentable.swift */; };
566A214C1C58A54F00C5A218 /* StandardLibraryTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -59,36 +65,42 @@
562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
562FF9F11BCE914E00759400 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
562FF9F41BCE930C00759400 /* GRDBDemoiOS7-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBDemoiOS7-Bridging-Header.h"; sourceTree = "<group>"; };
563445071C4A8060003D3DC6 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
56FCB3421C21210B00305D10 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = "<group>"; };
56FCB3431C21210B00305D10 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
56FCB3451C21210B00305D10 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = "<group>"; };
56FCB3461C21210B00305D10 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = "<group>"; };
56FCB3471C21210B00305D10 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = "<group>"; };
56FCB3491C21210B00305D10 /* DatabasePersistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistable.swift; sourceTree = "<group>"; };
56FCB34A1C21210B00305D10 /* DatabaseTableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTableMapping.swift; sourceTree = "<group>"; };
56FCB34B1C21210B00305D10 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
56FCB34C1C21210B00305D10 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
56FCB34D1C21210B00305D10 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = "<group>"; };
56FCB34E1C21210B00305D10 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = "<group>"; };
56FCB3501C21210B00305D10 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = "<group>"; };
56FCB3541C21210B00305D10 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = "<group>"; };
56FCB3561C21210B00305D10 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = "<group>"; };
56FCB3571C21210B00305D10 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = "<group>"; };
56FCB3581C21210B00305D10 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = "<group>"; };
56FCB3591C21210B00305D10 /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
56FCB35A1C21210B00305D10 /* NSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDate.swift; sourceTree = "<group>"; };
56FCB35B1C21210B00305D10 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = "<group>"; };
56FCB35C1C21210B00305D10 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = "<group>"; };
56FCB35D1C21210B00305D10 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
56FCB35E1C21210B00305D10 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = "<group>"; };
56FCB35F1C21210B00305D10 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = "<group>"; };
56FCB3601C21210B00305D10 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = "<group>"; };
56FCB3621C21210B00305D10 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
56FCB3631C21210B00305D10 /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56FCB3651C21210B00305D10 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
56FCB3671C21210B00305D10 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = "<group>"; };
56FCB3681C21210B00305D10 /* StandardLibraryTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibraryTypes.swift; sourceTree = "<group>"; };
566A20F21C58A4B300C5A218 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
566A20F61C58A54F00C5A218 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = "<group>"; };
566A20F71C58A54F00C5A218 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
566A20F81C58A54F00C5A218 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = "<group>"; };
566A20F91C58A54F00C5A218 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = "<group>"; };
566A20FA1C58A54F00C5A218 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = "<group>"; };
566A20FC1C58A54F00C5A218 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
566A20FD1C58A54F00C5A218 /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = "<group>"; };
566A20FE1C58A54F00C5A218 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
566A20FF1C58A54F00C5A218 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = "<group>"; };
566A21001C58A54F00C5A218 /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = "<group>"; };
566A21011C58A54F00C5A218 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = "<group>"; };
566A21021C58A54F00C5A218 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = "<group>"; };
566A21031C58A54F00C5A218 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
566A21051C58A54F00C5A218 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = "<group>"; };
566A21071C58A54F00C5A218 /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = "<group>"; };
566A21091C58A54F00C5A218 /* Collation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Collation.swift; sourceTree = "<group>"; };
566A210A1C58A54F00C5A218 /* Function.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Function.swift; sourceTree = "<group>"; };
566A210B1C58A54F00C5A218 /* Operator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Operator.swift; sourceTree = "<group>"; };
566A210C1C58A54F00C5A218 /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
566A210E1C58A54F00C5A218 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = "<group>"; };
566A210F1C58A54F00C5A218 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = "<group>"; };
566A21101C58A54F00C5A218 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = "<group>"; };
566A21111C58A54F00C5A218 /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
566A21121C58A54F00C5A218 /* NSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDate.swift; sourceTree = "<group>"; };
566A21131C58A54F00C5A218 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = "<group>"; };
566A21141C58A54F00C5A218 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = "<group>"; };
566A21151C58A54F00C5A218 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
566A21161C58A54F00C5A218 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = "<group>"; };
566A21171C58A54F00C5A218 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = "<group>"; };
566A21181C58A54F00C5A218 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = "<group>"; };
566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
566A211F1C58A54F00C5A218 /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
566A21231C58A54F00C5A218 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
566A21251C58A54F00C5A218 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = "<group>"; };
566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibraryTypes.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -123,6 +135,7 @@
isa = PBXGroup;
children = (
562FF9941BCE8FA400759400 /* AppDelegate.swift */,
566A20F21C58A4B300C5A218 /* AppDatabase.swift */,
562FF9F01BCE913900759400 /* Controllers */,
562FF9F31BCE915B00759400 /* Models */,
562FF9A61BCE8FB000759400 /* Resources */,
@@ -151,25 +164,11 @@
name = "Supporting Files";
sourceTree = "<group>";
};
562FF9A81BCE900100759400 /* GRDB */ = {
isa = PBXGroup;
children = (
56FCB3411C21210B00305D10 /* Core */,
56FCB3531C21210B00305D10 /* CoreGraphics */,
56FCB3551C21210B00305D10 /* Foundation */,
56FCB3611C21210B00305D10 /* Migrations */,
56FCB3641C21210B00305D10 /* Record */,
56FCB3661C21210B00305D10 /* Swift */,
);
name = GRDB;
path = ../../GRDB;
sourceTree = SOURCE_ROOT;
};
562FF9ED1BCE904D00759400 /* Libraries */ = {
isa = PBXGroup;
children = (
562FF9EB1BCE903D00759400 /* libsqlite3.tbd */,
562FF9A81BCE900100759400 /* GRDB */,
566A20F41C58A54F00C5A218 /* GRDB */,
);
name = Libraries;
sourceTree = "<group>";
@@ -191,82 +190,117 @@
name = Models;
sourceTree = "<group>";
};
56FCB3411C21210B00305D10 /* Core */ = {
566A20F41C58A54F00C5A218 /* GRDB */ = {
isa = PBXGroup;
children = (
56FCB3421C21210B00305D10 /* Configuration.swift */,
56FCB3431C21210B00305D10 /* Database.swift */,
56FCB3451C21210B00305D10 /* DatabaseError.swift */,
56FCB3461C21210B00305D10 /* DatabaseQueue.swift */,
56FCB3471C21210B00305D10 /* DatabaseValue.swift */,
56FCB3481C21210B00305D10 /* Protocols */,
56FCB34E1C21210B00305D10 /* Row.swift */,
56FCB3501C21210B00305D10 /* Statement.swift */,
563445071C4A8060003D3DC6 /* Utils.swift */,
566A20F51C58A54F00C5A218 /* Core */,
566A21041C58A54F00C5A218 /* CoreGraphics */,
566A21061C58A54F00C5A218 /* FetchRequest */,
566A210D1C58A54F00C5A218 /* Foundation */,
566A211D1C58A54F00C5A218 /* Migrations */,
566A21221C58A54F00C5A218 /* Record */,
566A21241C58A54F00C5A218 /* Swift */,
);
name = GRDB;
path = ../../../GRDB;
sourceTree = "<group>";
};
566A20F51C58A54F00C5A218 /* Core */ = {
isa = PBXGroup;
children = (
566A20F61C58A54F00C5A218 /* Configuration.swift */,
566A20F71C58A54F00C5A218 /* Database.swift */,
566A20F81C58A54F00C5A218 /* DatabaseError.swift */,
566A20F91C58A54F00C5A218 /* DatabaseQueue.swift */,
566A20FA1C58A54F00C5A218 /* DatabaseValue.swift */,
566A20FB1C58A54F00C5A218 /* Protocols */,
566A21011C58A54F00C5A218 /* Row.swift */,
566A21021C58A54F00C5A218 /* Statement.swift */,
566A21031C58A54F00C5A218 /* Utils.swift */,
);
path = Core;
sourceTree = "<group>";
};
56FCB3481C21210B00305D10 /* Protocols */ = {
566A20FB1C58A54F00C5A218 /* Protocols */ = {
isa = PBXGroup;
children = (
56FCB3491C21210B00305D10 /* DatabasePersistable.swift */,
56FCB34A1C21210B00305D10 /* DatabaseTableMapping.swift */,
56FCB34B1C21210B00305D10 /* DatabaseValueConvertible.swift */,
56FCB34C1C21210B00305D10 /* RowConvertible.swift */,
56FCB34D1C21210B00305D10 /* SQLiteStatementConvertible.swift */,
566A20FC1C58A54F00C5A218 /* DatabaseValueConvertible.swift */,
566A20FD1C58A54F00C5A218 /* Persistable.swift */,
566A20FE1C58A54F00C5A218 /* RowConvertible.swift */,
566A20FF1C58A54F00C5A218 /* SQLiteStatementConvertible.swift */,
566A21001C58A54F00C5A218 /* TableMapping.swift */,
);
path = Protocols;
sourceTree = "<group>";
};
56FCB3531C21210B00305D10 /* CoreGraphics */ = {
566A21041C58A54F00C5A218 /* CoreGraphics */ = {
isa = PBXGroup;
children = (
56FCB3541C21210B00305D10 /* CGFloat.swift */,
566A21051C58A54F00C5A218 /* CGFloat.swift */,
);
path = CoreGraphics;
sourceTree = "<group>";
};
56FCB3551C21210B00305D10 /* Foundation */ = {
566A21061C58A54F00C5A218 /* FetchRequest */ = {
isa = PBXGroup;
children = (
56FCB3561C21210B00305D10 /* DatabaseCoder.swift */,
56FCB3571C21210B00305D10 /* DatabaseDateComponents.swift */,
56FCB3581C21210B00305D10 /* DatabaseValue+Foundation.swift */,
56FCB3591C21210B00305D10 /* NSData.swift */,
56FCB35A1C21210B00305D10 /* NSDate.swift */,
56FCB35B1C21210B00305D10 /* NSNull.swift */,
56FCB35C1C21210B00305D10 /* NSNumber.swift */,
56FCB35D1C21210B00305D10 /* NSString.swift */,
56FCB35E1C21210B00305D10 /* NSURL.swift */,
56FCB35F1C21210B00305D10 /* Row+Foundation.swift */,
56FCB3601C21210B00305D10 /* StatementArguments+Foundation.swift */,
566A21071C58A54F00C5A218 /* FetchRequest.swift */,
566A21081C58A54F00C5A218 /* SQLSupport */,
);
path = FetchRequest;
sourceTree = "<group>";
};
566A21081C58A54F00C5A218 /* SQLSupport */ = {
isa = PBXGroup;
children = (
566A21091C58A54F00C5A218 /* Collation.swift */,
566A210A1C58A54F00C5A218 /* Function.swift */,
566A210B1C58A54F00C5A218 /* Operator.swift */,
566A210C1C58A54F00C5A218 /* SQLQuery.swift */,
);
path = SQLSupport;
sourceTree = "<group>";
};
566A210D1C58A54F00C5A218 /* Foundation */ = {
isa = PBXGroup;
children = (
566A210E1C58A54F00C5A218 /* DatabaseCoder.swift */,
566A210F1C58A54F00C5A218 /* DatabaseDateComponents.swift */,
566A21101C58A54F00C5A218 /* DatabaseValue+Foundation.swift */,
566A21111C58A54F00C5A218 /* NSData.swift */,
566A21121C58A54F00C5A218 /* NSDate.swift */,
566A21131C58A54F00C5A218 /* NSNull.swift */,
566A21141C58A54F00C5A218 /* NSNumber.swift */,
566A21151C58A54F00C5A218 /* NSString.swift */,
566A21161C58A54F00C5A218 /* NSURL.swift */,
566A21171C58A54F00C5A218 /* Row+Foundation.swift */,
566A21181C58A54F00C5A218 /* StatementArguments+Foundation.swift */,
);
path = Foundation;
sourceTree = "<group>";
};
56FCB3611C21210B00305D10 /* Migrations */ = {
566A211D1C58A54F00C5A218 /* Migrations */ = {
isa = PBXGroup;
children = (
56FCB3621C21210B00305D10 /* DatabaseMigrator.swift */,
56FCB3631C21210B00305D10 /* Migration.swift */,
566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */,
566A211F1C58A54F00C5A218 /* Migration.swift */,
);
path = Migrations;
sourceTree = "<group>";
};
56FCB3641C21210B00305D10 /* Record */ = {
566A21221C58A54F00C5A218 /* Record */ = {
isa = PBXGroup;
children = (
56FCB3651C21210B00305D10 /* Record.swift */,
566A21231C58A54F00C5A218 /* Record.swift */,
);
path = Record;
sourceTree = "<group>";
};
56FCB3661C21210B00305D10 /* Swift */ = {
566A21241C58A54F00C5A218 /* Swift */ = {
isa = PBXGroup;
children = (
56FCB3671C21210B00305D10 /* RawRepresentable.swift */,
56FCB3681C21210B00305D10 /* StandardLibraryTypes.swift */,
566A21251C58A54F00C5A218 /* RawRepresentable.swift */,
566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */,
);
path = Swift;
sourceTree = "<group>";
@@ -341,40 +375,46 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56FCB3821C21210B00305D10 /* NSURL.swift in Sources */,
56FCB3881C21210B00305D10 /* RawRepresentable.swift in Sources */,
56FCB3841C21210B00305D10 /* StatementArguments+Foundation.swift in Sources */,
56FCB37A1C21210B00305D10 /* DatabaseCoder.swift in Sources */,
56FCB3891C21210B00305D10 /* StandardLibraryTypes.swift in Sources */,
56FCB3731C21210B00305D10 /* SQLiteStatementConvertible.swift in Sources */,
56FCB37F1C21210B00305D10 /* NSNull.swift in Sources */,
56FCB37D1C21210B00305D10 /* NSData.swift in Sources */,
56FCB36A1C21210B00305D10 /* Database.swift in Sources */,
563445081C4A8060003D3DC6 /* Utils.swift in Sources */,
56FCB37C1C21210B00305D10 /* DatabaseValue+Foundation.swift in Sources */,
566A21381C58A54F00C5A218 /* Operator.swift in Sources */,
566A21411C58A54F00C5A218 /* NSString.swift in Sources */,
566A21401C58A54F00C5A218 /* NSNumber.swift in Sources */,
566A21351C58A54F00C5A218 /* FetchRequest.swift in Sources */,
566A21271C58A54F00C5A218 /* Configuration.swift in Sources */,
562FF9EF1BCE912C00759400 /* PersonEditionViewController.swift in Sources */,
56FCB3831C21210B00305D10 /* Row+Foundation.swift in Sources */,
56FCB3711C21210B00305D10 /* DatabaseValueConvertible.swift in Sources */,
56FCB3691C21210B00305D10 /* Configuration.swift in Sources */,
56FCB3851C21210B00305D10 /* DatabaseMigrator.swift in Sources */,
56FCB37E1C21210B00305D10 /* NSDate.swift in Sources */,
562FF9971BCE8FA400759400 /* PersonsViewController.swift in Sources */,
56FCB36E1C21210B00305D10 /* DatabaseValue.swift in Sources */,
56FCB3791C21210B00305D10 /* CGFloat.swift in Sources */,
56FCB3801C21210B00305D10 /* NSNumber.swift in Sources */,
566A214B1C58A54F00C5A218 /* RawRepresentable.swift in Sources */,
562FF9F21BCE914E00759400 /* Person.swift in Sources */,
56FCB3701C21210B00305D10 /* DatabaseTableMapping.swift in Sources */,
56FCB3861C21210B00305D10 /* Migration.swift in Sources */,
56FCB3761C21210B00305D10 /* Statement.swift in Sources */,
56FCB36C1C21210B00305D10 /* DatabaseError.swift in Sources */,
56FCB3811C21210B00305D10 /* NSString.swift in Sources */,
56FCB36F1C21210B00305D10 /* DatabasePersistable.swift in Sources */,
566A212B1C58A54F00C5A218 /* DatabaseValue.swift in Sources */,
562FF9951BCE8FA400759400 /* AppDelegate.swift in Sources */,
56FCB3741C21210B00305D10 /* Row.swift in Sources */,
56FCB36D1C21210B00305D10 /* DatabaseQueue.swift in Sources */,
56FCB37B1C21210B00305D10 /* DatabaseDateComponents.swift in Sources */,
56FCB3871C21210B00305D10 /* Record.swift in Sources */,
56FCB3721C21210B00305D10 /* RowConvertible.swift in Sources */,
566A213C1C58A54F00C5A218 /* DatabaseValue+Foundation.swift in Sources */,
566A212D1C58A54F00C5A218 /* Persistable.swift in Sources */,
566A21421C58A54F00C5A218 /* NSURL.swift in Sources */,
566A21441C58A54F00C5A218 /* StatementArguments+Foundation.swift in Sources */,
566A212E1C58A54F00C5A218 /* RowConvertible.swift in Sources */,
566A21481C58A54F00C5A218 /* Migration.swift in Sources */,
566A21291C58A54F00C5A218 /* DatabaseError.swift in Sources */,
566A21281C58A54F00C5A218 /* Database.swift in Sources */,
566A212C1C58A54F00C5A218 /* DatabaseValueConvertible.swift in Sources */,
566A21331C58A54F00C5A218 /* Utils.swift in Sources */,
566A214A1C58A54F00C5A218 /* Record.swift in Sources */,
566A21321C58A54F00C5A218 /* Statement.swift in Sources */,
566A21391C58A54F00C5A218 /* SQLQuery.swift in Sources */,
566A21301C58A54F00C5A218 /* TableMapping.swift in Sources */,
566A21431C58A54F00C5A218 /* Row+Foundation.swift in Sources */,
566A214C1C58A54F00C5A218 /* StandardLibraryTypes.swift in Sources */,
566A21341C58A54F00C5A218 /* CGFloat.swift in Sources */,
566A21361C58A54F00C5A218 /* Collation.swift in Sources */,
566A21311C58A54F00C5A218 /* Row.swift in Sources */,
566A212A1C58A54F00C5A218 /* DatabaseQueue.swift in Sources */,
566A213E1C58A54F00C5A218 /* NSDate.swift in Sources */,
566A212F1C58A54F00C5A218 /* SQLiteStatementConvertible.swift in Sources */,
566A20F31C58A4B300C5A218 /* AppDatabase.swift in Sources */,
566A213F1C58A54F00C5A218 /* NSNull.swift in Sources */,
566A213A1C58A54F00C5A218 /* DatabaseCoder.swift in Sources */,
566A213B1C58A54F00C5A218 /* DatabaseDateComponents.swift in Sources */,
566A213D1C58A54F00C5A218 /* NSData.swift in Sources */,
566A21371C58A54F00C5A218 /* Function.swift in Sources */,
566A21471C58A54F00C5A218 /* DatabaseMigrator.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -0,0 +1,64 @@
import Foundation
// The columns for the GRDB Query Interface
//
// See https://github.com/groue/GRDB.swift/#the-query-interface
struct Col {
static let id = SQLColumn("id")
static let firstName = SQLColumn("firstName")
static let lastName = SQLColumn("lastName")
}
// The shared database queue, stored in a global.
// It is initialized in setupDatabase()
var dbQueue: DatabaseQueue!
func setupDatabase() {
// Connect to the database
//
// See https://github.com/groue/GRDB.swift/#database-queues
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
let databasePath = documentsPath.stringByAppendingPathComponent("db.sqlite")
dbQueue = try! DatabaseQueue(path: databasePath)
// SQLite does not support Unicode: let's add a custom collation which will
// allow us to sort persons by name.
//
// See https://github.com/groue/GRDB.swift/#string-comparison
let collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in
return (lhs as NSString).localizedCaseInsensitiveCompare(rhs)
}
dbQueue.inDatabase { db in
db.addCollation(collation)
}
// Use DatabaseMigrator to setup the database
//
// See https://github.com/groue/GRDB.swift/#migrations
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"firstName TEXT COLLATE localized_case_insensitive, " +
"lastName TEXT COLLATE localized_case_insensitive" +
")")
}
migrator.registerMigration("addPersons") { db in
try Person(firstName: "Arthur", lastName: "Miller").insert(db)
try Person(firstName: "Barbra", lastName: "Streisand").insert(db)
try Person(firstName: "Cinderella").insert(db)
}
try! migrator.migrate(dbQueue)
}
@@ -1,42 +1,12 @@
import UIKit
// The shared database queue, stored in a global.
// It is created in AppDelegate.application(_:didFinishLaunchingWithOptions:)
var dbQueue: DatabaseQueue!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Connect to the database
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
let databasePath = documentsPath.stringByAppendingPathComponent("db.sqlite")
dbQueue = try! DatabaseQueue(path: databasePath)
// Use DatabaseMigrator to setup the database
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"firstName TEXT, " +
"lastName TEXT " +
")")
}
migrator.registerMigration("addPersons") { db in
try Person(firstName: "Arthur", lastName: "Miller").insert(db)
try Person(firstName: "Barbra", lastName: "Streisand").insert(db)
try Person(firstName: "Cinderella").insert(db)
}
try! migrator.migrate(dbQueue)
setupDatabase()
return true
}
}
@@ -3,7 +3,7 @@ class Person : Record {
var firstName: String?
var lastName: String?
var fullName: String {
return [firstName, lastName].flatMap { $0 }.joinWithSeparator(" ")
return [firstName, lastName].flatMap { $0 }.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
init(firstName: String? = nil, lastName: String? = nil) {
@@ -14,7 +14,7 @@ class PersonsViewController: UITableViewController {
func reloadPersons() {
persons = dbQueue.inDatabase { db in
Person.fetchAll(db, "SELECT * FROM persons ORDER BY LOWER(firstName), LOWER(lastName)")
Person.order(Col.firstName, Col.lastName).fetchAll(db)
}
}
@@ -61,6 +61,7 @@ class PersonsViewController: UITableViewController {
let person = persons[indexPath.row]
cell.textLabel!.text = person.fullName
cell.selectionStyle = .None
return cell
}
@@ -75,6 +76,10 @@ class PersonsViewController: UITableViewController {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
+9
View File
@@ -5,10 +5,12 @@ class GRDBTestCase: XCTestCase {
var databasePath: String!
var dbQueue: DatabaseQueue!
var sqlQueries: [String]!
var lastSQLQuery: String!
var dbConfiguration: Configuration {
var dbConfiguration = Configuration()
dbConfiguration.trace = { (sql) in
self.sqlQueries.append(sql)
self.lastSQLQuery = sql
// LogSQL(sql) // Uncomment for verbose tests
}
return dbConfiguration
@@ -39,4 +41,11 @@ class GRDBTestCase: XCTestCase {
XCTFail("unexpected error: \(error)")
}
}
func sql<T>(request: FetchRequest<T>) -> String {
return dbQueue.inDatabase { db in
let _ = Row.fetchOne(db, request)
return self.lastSQLQuery
}
}
}
@@ -391,7 +391,7 @@ class ConcurrencyTests: XCTestCase {
do {
dispatch_semaphore_wait(s1, DISPATCH_TIME_FOREVER)
try self.dbQueue2.inTransaction(.Deferred) { db in
Row.fetchAll(db, "SELECT * FROM stuffs")
let _ = Row.fetchAll(db, "SELECT * FROM stuffs")
dispatch_semaphore_signal(s2)
usleep(100_000) // 0.1s
return .Commit
@@ -1,7 +1,7 @@
import XCTest
import GRDB
struct MutablePersistablePerson : MutableDatabasePersistable {
struct MutablePersistablePerson : MutablePersistable {
var id: Int64?
var name: String?
@@ -18,7 +18,7 @@ struct MutablePersistablePerson : MutableDatabasePersistable {
}
}
struct MutablePersistableCountry : MutableDatabasePersistable {
struct MutablePersistableCountry : MutablePersistable {
var rowID: Int64?
var isoCode: String
var name: String
@@ -36,7 +36,7 @@ struct MutablePersistableCountry : MutableDatabasePersistable {
}
}
struct MutablePersistableCustomizedCountry : MutableDatabasePersistable {
struct MutablePersistableCustomizedCountry : MutablePersistable {
var rowID: Int64?
var isoCode: String
var name: String
@@ -84,7 +84,7 @@ struct MutablePersistableCustomizedCountry : MutableDatabasePersistable {
}
}
class MutableDatabasePersistableTests: GRDBTestCase {
class MutablePersistableTests: GRDBTestCase {
override func setUp() {
super.setUp()
@@ -1,7 +1,7 @@
import XCTest
import GRDB
struct PersistablePerson : DatabasePersistable {
struct PersistablePerson : Persistable {
var name: String?
var age: Int?
@@ -14,7 +14,7 @@ struct PersistablePerson : DatabasePersistable {
}
}
class PersistablePersonClass : DatabasePersistable {
class PersistablePersonClass : Persistable {
var id: Int64?
var name: String?
var age: Int?
@@ -38,7 +38,7 @@ class PersistablePersonClass : DatabasePersistable {
}
}
struct PersistableCountry : DatabasePersistable {
struct PersistableCountry : Persistable {
var isoCode: String
var name: String
@@ -51,7 +51,7 @@ struct PersistableCountry : DatabasePersistable {
}
}
struct PersistableCustomizedCountry : DatabasePersistable {
struct PersistableCustomizedCountry : Persistable {
var isoCode: String
var name: String
let willInsert: Void -> Void
@@ -94,7 +94,7 @@ struct PersistableCustomizedCountry : DatabasePersistable {
}
}
class DatabasePersistableTests: GRDBTestCase {
class PersistableTests: GRDBTestCase {
override func setUp() {
super.setUp()
@@ -0,0 +1,361 @@
import XCTest
import GRDB
private struct Col {
static let id = SQLColumn("id")
static let name = SQLColumn("name")
static let age = SQLColumn("age")
static let readerId = SQLColumn("readerId")
}
private let tableRequest = FetchRequest<Void>(tableName: "readers")
class FetchRequestTests: GRDBTestCase {
var collation: DatabaseCollation!
override func setUp() {
super.setUp()
collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in
return (lhs as NSString).localizedCaseInsensitiveCompare(rhs)
}
dbQueue.inDatabase { db in
db.addCollation(self.collation)
}
var migrator = DatabaseMigrator()
migrator.registerMigration("createReaders") { db in
try db.execute(
"CREATE TABLE readers (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
try! migrator.migrate(dbQueue)
}
// MARK: - Fetch rows
func testFetchRowFromRequest() {
assertNoError {
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42])
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36])
do {
let rows = Row.fetchAll(db, tableRequest)
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0].value(named: "id") as Int64, 1)
XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur")
XCTAssertEqual(rows[0].value(named: "age") as Int, 42)
XCTAssertEqual(rows[1].value(named: "id") as Int64, 2)
XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara")
XCTAssertEqual(rows[1].value(named: "age") as Int, 36)
}
do {
let row = Row.fetchOne(db, tableRequest)!
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(row.value(named: "id") as Int64, 1)
XCTAssertEqual(row.value(named: "name") as String, "Arthur")
XCTAssertEqual(row.value(named: "age") as Int, 42)
}
do {
var names: [String] = []
for row in Row.fetch(db, tableRequest) {
names.append(row.value(named: "name"))
}
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(names, ["Arthur", "Barbara"])
}
}
}
}
// MARK: - Count
func testFetchCount() {
assertNoError {
try dbQueue.inDatabase { db in
XCTAssertEqual(tableRequest.fetchCount(db), 0)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
let readers: [(String, Int?)] = [
("Arthur", 42),
("Barbara", 36),
("Craig", 42),
("Craig", 42),
("Daniel", nil)]
for (name, age) in readers {
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: [name, age])
}
XCTAssertEqual(tableRequest.fetchCount(db), 5)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
XCTAssertEqual(tableRequest.filter(Col.age == 42).fetchCount(db), 3)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE (\"age\" = 42)")
XCTAssertEqual(tableRequest.fetchCount(db, Col.age), 4)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(\"age\") FROM \"readers\"")
XCTAssertEqual(tableRequest.fetchCount(db, Col.age ?? 0), 5)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(IFNULL(\"age\", 0)) FROM \"readers\"")
XCTAssertEqual(tableRequest.fetchCount(db, distinct: Col.age), 2)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT \"age\") FROM \"readers\"")
XCTAssertEqual(tableRequest.fetchCount(db, distinct: Col.age / Col.age), 1)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT (\"age\" / \"age\")) FROM \"readers\"")
}
}
}
// MARK: - Select
func testSelectLiteral() {
assertNoError {
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42])
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36])
let request = tableRequest.select(sql: "name, id - 1")
let rows = Row.fetchAll(db, request)
XCTAssertEqual(self.lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"")
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0].value(atIndex: 0) as String, "Arthur")
XCTAssertEqual(rows[0].value(atIndex: 1) as Int64, 0)
XCTAssertEqual(rows[1].value(atIndex: 0) as String, "Barbara")
XCTAssertEqual(rows[1].value(atIndex: 1) as Int64, 1)
}
}
}
func testSelect() {
assertNoError {
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42])
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36])
let request = tableRequest.select(Col.name, Col.id - 1)
let rows = Row.fetchAll(db, request)
XCTAssertEqual(self.lastSQLQuery, "SELECT \"name\", (\"id\" - 1) FROM \"readers\"")
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0].value(atIndex: 0) as String, "Arthur")
XCTAssertEqual(rows[0].value(atIndex: 1) as Int64, 0)
XCTAssertEqual(rows[1].value(atIndex: 0) as String, "Barbara")
XCTAssertEqual(rows[1].value(atIndex: 1) as Int64, 1)
}
}
}
func testSelectAliased() {
assertNoError {
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42])
let request = tableRequest.select(Col.name.aliased("nom"), (Col.age + 1).aliased("agePlusOne"))
let row = Row.fetchOne(db, request)!
XCTAssertEqual(self.lastSQLQuery, "SELECT \"name\" AS \"nom\", (\"age\" + 1) AS \"agePlusOne\" FROM \"readers\"")
XCTAssertEqual(row.value(named: "nom") as String, "Arthur")
XCTAssertEqual(row.value(named: "agePlusOne") as Int, 43)
}
}
}
func testMultipleSelect() {
XCTAssertEqual(
sql(tableRequest.select(Col.age).select(Col.name)),
"SELECT \"name\" FROM \"readers\"")
}
// MARK: - Distinct
func testDistinct() {
XCTAssertEqual(
sql(tableRequest.select(Col.name).distinct),
"SELECT DISTINCT \"name\" FROM \"readers\"")
}
// MARK: - Filter
func testFilterLiteral() {
XCTAssertEqual(
sql(tableRequest.filter(sql: "id <> 1")),
"SELECT * FROM \"readers\" WHERE id <> 1")
}
func testFilter() {
XCTAssertEqual(
sql(tableRequest.filter(true)),
"SELECT * FROM \"readers\" WHERE 1")
}
func testMultipleFilter() {
XCTAssertEqual(
sql(tableRequest.filter(true).filter(false)),
"SELECT * FROM \"readers\" WHERE (1 AND 0)")
}
// MARK: - Group
func testGroupLiteral() {
XCTAssertEqual(
sql(tableRequest.group(sql: "age, lower(name)")),
"SELECT * FROM \"readers\" GROUP BY age, lower(name)")
}
func testGroup() {
XCTAssertEqual(
sql(tableRequest.group(Col.age)),
"SELECT * FROM \"readers\" GROUP BY \"age\"")
XCTAssertEqual(
sql(tableRequest.group(Col.age, Col.name)),
"SELECT * FROM \"readers\" GROUP BY \"age\", \"name\"")
}
func testMultipleGroup() {
XCTAssertEqual(
sql(tableRequest.group(Col.age).group(Col.name)),
"SELECT * FROM \"readers\" GROUP BY \"name\"")
}
// MARK: - Having
func testHavingLiteral() {
XCTAssertEqual(
sql(tableRequest.group(Col.name).having(sql: "min(age) > 18")),
"SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18")
}
func testHaving() {
XCTAssertEqual(
sql(tableRequest.group(Col.name).having(min(Col.age) > 18)),
"SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (MIN(\"age\") > 18)")
}
func testMultipleHaving() {
XCTAssertEqual(
sql(tableRequest.group(Col.name).having(min(Col.age) > 18).having(max(Col.age) < 50)),
"SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((MIN(\"age\") > 18) AND (MAX(\"age\") < 50))")
}
// MARK: - Sort
func testSortLiteral() {
XCTAssertEqual(
sql(tableRequest.order(sql: "lower(age) desc")),
"SELECT * FROM \"readers\" ORDER BY lower(age) desc")
}
func testSort() {
XCTAssertEqual(
sql(tableRequest.order(Col.age)),
"SELECT * FROM \"readers\" ORDER BY \"age\"")
XCTAssertEqual(
sql(tableRequest.order(Col.age.asc)),
"SELECT * FROM \"readers\" ORDER BY \"age\" ASC")
XCTAssertEqual(
sql(tableRequest.order(Col.age.desc)),
"SELECT * FROM \"readers\" ORDER BY \"age\" DESC")
XCTAssertEqual(
sql(tableRequest.order(Col.age, Col.name.desc)),
"SELECT * FROM \"readers\" ORDER BY \"age\", \"name\" DESC")
XCTAssertEqual(
sql(tableRequest.order(abs(Col.age))),
"SELECT * FROM \"readers\" ORDER BY ABS(\"age\")")
}
func testSortWithCollation() {
XCTAssertEqual(
sql(tableRequest.order(Col.name.collating("NOCASE"))),
"SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE")
XCTAssertEqual(
sql(tableRequest.order(Col.name.collating("NOCASE").asc)),
"SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC")
XCTAssertEqual(
sql(tableRequest.order(Col.name.collating(collation))),
"SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE localized_case_insensitive")
}
func testMultipleSort() {
XCTAssertEqual(
sql(tableRequest.order(Col.age).order(Col.name)),
"SELECT * FROM \"readers\" ORDER BY \"age\", \"name\"")
}
// MARK: - Reverse
func testReverse() {
XCTAssertEqual(
sql(tableRequest.reverse()),
"SELECT * FROM \"readers\" ORDER BY \"id\" DESC")
XCTAssertEqual(
sql(tableRequest.order(Col.age).reverse()),
"SELECT * FROM \"readers\" ORDER BY \"age\" DESC")
XCTAssertEqual(
sql(tableRequest.order(Col.age.asc).reverse()),
"SELECT * FROM \"readers\" ORDER BY \"age\" DESC")
XCTAssertEqual(
sql(tableRequest.order(Col.age.desc).reverse()),
"SELECT * FROM \"readers\" ORDER BY \"age\" ASC")
XCTAssertEqual(
sql(tableRequest.order(Col.age, Col.name.desc).reverse()),
"SELECT * FROM \"readers\" ORDER BY \"age\" DESC, \"name\" ASC")
XCTAssertEqual(
sql(tableRequest.order(abs(Col.age)).reverse()),
"SELECT * FROM \"readers\" ORDER BY ABS(\"age\") DESC")
}
func testReverseWithCollation() {
XCTAssertEqual(
sql(tableRequest.order(Col.name.collating("NOCASE")).reverse()),
"SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC")
XCTAssertEqual(
sql(tableRequest.order(Col.name.collating("NOCASE").asc).reverse()),
"SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC")
XCTAssertEqual(
sql(tableRequest.order(Col.name.collating(collation)).reverse()),
"SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE localized_case_insensitive DESC")
}
func testMultipleReverse() {
XCTAssertEqual(
sql(tableRequest.reverse().reverse()),
"SELECT * FROM \"readers\"")
XCTAssertEqual(
sql(tableRequest.order(Col.age).order(Col.name).reverse().reverse()),
"SELECT * FROM \"readers\" ORDER BY \"age\", \"name\"")
}
// MARK: - Limit
func testLimit() {
XCTAssertEqual(
sql(tableRequest.limit(1)),
"SELECT * FROM \"readers\" LIMIT 1")
XCTAssertEqual(
sql(tableRequest.limit(1, offset: 2)),
"SELECT * FROM \"readers\" LIMIT 1 OFFSET 2")
}
func testMultipleLimit() {
XCTAssertEqual(
sql(tableRequest.limit(1, offset: 2).limit(3)),
"SELECT * FROM \"readers\" LIMIT 3")
}
}
@@ -0,0 +1,95 @@
import XCTest
import GRDB
private class Reader : Record {
var id: Int64?
let name: String
let age: Int?
init(id: Int64?, name: String, age: Int?) {
self.id = id
self.name = name
self.age = age
super.init()
}
required init(_ row: Row){
self.id = row.value(named: "id")
self.name = row.value(named: "name")
self.age = row.value(named: "age")
super.init(row)
}
override static func databaseTableName() -> String {
return "readers"
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["id": id, "name": name, "age": age]
}
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
id = rowID
}
}
class RecordFetchRequestTests: GRDBTestCase {
override func setUp() {
super.setUp()
var migrator = DatabaseMigrator()
migrator.registerMigration("createReaders") { db in
try db.execute(
"CREATE TABLE readers (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
try! migrator.migrate(dbQueue)
}
// MARK: - Fetch Record
func testFetch() {
assertNoError {
try dbQueue.inDatabase { db in
let arthur = Reader(id: nil, name: "Arthur", age: 42)
try arthur.insert(db)
let barbara = Reader(id: nil, name: "Barbara", age: 36)
try barbara.insert(db)
let request = Reader.all()
do {
let readers = request.fetchAll(db)
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(readers.count, 2)
XCTAssertEqual(readers[0].id!, arthur.id!)
XCTAssertEqual(readers[0].name, arthur.name)
XCTAssertEqual(readers[0].age, arthur.age)
XCTAssertEqual(readers[1].id!, barbara.id!)
XCTAssertEqual(readers[1].name, barbara.name)
XCTAssertEqual(readers[1].age, barbara.age)
}
do {
let reader = request.fetchOne(db)!
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(reader.id!, arthur.id!)
XCTAssertEqual(reader.name, arthur.name)
XCTAssertEqual(reader.age, arthur.age)
}
do {
let names = request.fetch(db).map { $0.name }
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(names, [arthur.name, barbara.name])
}
}
}
}
}
@@ -0,0 +1,140 @@
import XCTest
import GRDB
private struct Reader : RowConvertible, MutablePersistable {
var id: Int64?
let name: String
let age: Int?
static func fromRow(row: Row) -> Reader {
return Reader(
id: row.value(named: "id"),
name: row.value(named: "name"),
age: row.value(named: "age"))
}
static func databaseTableName() -> String {
return "readers"
}
var persistentDictionary: [String: DatabaseValueConvertible?] {
return ["id": id, "name": name, "age": age]
}
mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
id = rowID
}
}
private struct AltReader : RowConvertible {
var id: Int64?
let name: String
let age: Int?
static func fromRow(row: Row) -> AltReader {
return AltReader(
id: row.value(named: "id"),
name: row.value(named: "name"),
age: row.value(named: "age"))
}
}
class RowConvertibleFetchRequestTests: GRDBTestCase {
override func setUp() {
super.setUp()
var migrator = DatabaseMigrator()
migrator.registerMigration("createReaders") { db in
try db.execute(
"CREATE TABLE readers (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
try! migrator.migrate(dbQueue)
}
// MARK: - Fetch RowConvertible
func testFetch() {
assertNoError {
try dbQueue.inDatabase { db in
var arthur = Reader(id: nil, name: "Arthur", age: 42)
try arthur.insert(db)
var barbara = Reader(id: nil, name: "Barbara", age: 36)
try barbara.insert(db)
let request = Reader.all()
do {
let readers = request.fetchAll(db)
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(readers.count, 2)
XCTAssertEqual(readers[0].id!, arthur.id!)
XCTAssertEqual(readers[0].name, arthur.name)
XCTAssertEqual(readers[0].age, arthur.age)
XCTAssertEqual(readers[1].id!, barbara.id!)
XCTAssertEqual(readers[1].name, barbara.name)
XCTAssertEqual(readers[1].age, barbara.age)
}
do {
let reader = request.fetchOne(db)!
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(reader.id!, arthur.id!)
XCTAssertEqual(reader.name, arthur.name)
XCTAssertEqual(reader.age, arthur.age)
}
do {
let names = request.fetch(db).map { $0.name }
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(names, [arthur.name, barbara.name])
}
}
}
}
func testAlternativeFetch() {
assertNoError {
try dbQueue.inDatabase { db in
var arthur = Reader(id: nil, name: "Arthur", age: 42)
try arthur.insert(db)
var barbara = Reader(id: nil, name: "Barbara", age: 36)
try barbara.insert(db)
let request = Reader.all()
do {
let readers = AltReader.fetchAll(db, request)
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(readers.count, 2)
XCTAssertEqual(readers[0].id!, arthur.id!)
XCTAssertEqual(readers[0].name, arthur.name)
XCTAssertEqual(readers[0].age, arthur.age)
XCTAssertEqual(readers[1].id!, barbara.id!)
XCTAssertEqual(readers[1].name, barbara.name)
XCTAssertEqual(readers[1].age, barbara.age)
}
do {
let reader = AltReader.fetchOne(db, request)!
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(reader.id!, arthur.id!)
XCTAssertEqual(reader.name, arthur.name)
XCTAssertEqual(reader.age, arthur.age)
}
do {
let names = AltReader.fetch(db, request).map { $0.name }
XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"")
XCTAssertEqual(names, [arthur.name, barbara.name])
}
}
}
}
}
@@ -0,0 +1,752 @@
import XCTest
import GRDB
private struct Col {
static let id = SQLColumn("id")
static let name = SQLColumn("name")
static let age = SQLColumn("age")
static let readerId = SQLColumn("readerId")
}
private let tableRequest = FetchRequest<Void>(tableName: "readers")
class SQLSupportTests: GRDBTestCase {
var collation: DatabaseCollation!
var customFunction: DatabaseFunction!
override func setUp() {
super.setUp()
collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in
return (lhs as NSString).localizedCaseInsensitiveCompare(rhs)
}
dbQueue.inDatabase { db in
db.addCollation(self.collation)
}
customFunction = DatabaseFunction("avgOf", pure: true) { databaseValues in
let sum = databaseValues.flatMap { $0.value() as Int? }.reduce(0, combine: +)
return Double(sum) / Double(databaseValues.count)
}
dbQueue.inDatabase { db in
db.addFunction(self.customFunction)
}
var migrator = DatabaseMigrator()
migrator.registerMigration("createReaders") { db in
try db.execute(
"CREATE TABLE readers (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
try! migrator.migrate(dbQueue)
}
// MARK: - Boolean expressions
func testContains() {
// emptyArray.contains(): 0
XCTAssertEqual(
sql(tableRequest.filter([Int]().contains(Col.id))),
"SELECT * FROM \"readers\" WHERE 0")
// Array.contains(): IN operator
XCTAssertEqual(
sql(tableRequest.filter([1,2,3].contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (1, 2, 3))")
// Array.contains(): IN operator
XCTAssertEqual(
sql(tableRequest.filter([Col.id].contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (\"id\"))")
// Sequence.contains(): IN operator
XCTAssertEqual(
sql(tableRequest.filter(AnySequence([1,2,3]).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (1, 2, 3))")
// Sequence.contains(): IN operator
XCTAssertEqual(
sql(tableRequest.filter(AnySequence([Col.id]).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (\"id\"))")
// !Sequence.contains(): NOT IN operator
XCTAssertEqual(
sql(tableRequest.filter(![1,2,3].contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" NOT IN (1, 2, 3))")
// !!Sequence.contains(): IN operator
XCTAssertEqual(
sql(tableRequest.filter(!(![1,2,3].contains(Col.id)))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (1, 2, 3))")
// Range.contains(): BETWEEN operator
var range: Range<Int64> = 1..<10
XCTAssertEqual(
sql(tableRequest.filter(range.contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" BETWEEN 1 AND 9)")
// Range.contains(): BETWEEN operator
range = 1...10
XCTAssertEqual(
sql(tableRequest.filter(range.contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" BETWEEN 1 AND 10)")
// ClosedInterval: BETWEEN operator
let closedInterval: ClosedInterval<String> = "A"..."z"
XCTAssertEqual(
sql(tableRequest.filter(closedInterval.contains(Col.name))),
"SELECT * FROM \"readers\" WHERE (\"name\" BETWEEN 'A' AND 'z')")
// HalfOpenInterval: min <= x < max
let halfOpenInterval: HalfOpenInterval<String> = "A"..<"z"
XCTAssertEqual(
sql(tableRequest.filter(halfOpenInterval.contains(Col.name))),
"SELECT * FROM \"readers\" WHERE ((\"name\" >= 'A') AND (\"name\" < 'z'))")
}
func testContainsWithCollation() {
// Array.contains(): IN operator
XCTAssertEqual(
sql(tableRequest.filter(["arthur", "barbara"].contains(Col.name.collating("NOCASE")))),
"SELECT * FROM \"readers\" WHERE (\"name\" IN ('arthur', 'barbara') COLLATE NOCASE)")
// Sequence.contains(): IN operator
XCTAssertEqual(
sql(tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Col.name.collating("NOCASE")))),
"SELECT * FROM \"readers\" WHERE (\"name\" IN ('arthur', 'barbara') COLLATE NOCASE)")
// Sequence.contains(): IN operator
XCTAssertEqual(
sql(tableRequest.filter(AnySequence([Col.name]).contains(Col.name.collating("NOCASE")))),
"SELECT * FROM \"readers\" WHERE (\"name\" IN (\"name\") COLLATE NOCASE)")
// ClosedInterval: BETWEEN operator
let closedInterval: ClosedInterval<String> = "A"..."z"
XCTAssertEqual(
sql(tableRequest.filter(closedInterval.contains(Col.name.collating("NOCASE")))),
"SELECT * FROM \"readers\" WHERE (\"name\" BETWEEN 'A' AND 'z' COLLATE NOCASE)")
// HalfOpenInterval: min <= x < max
let halfOpenInterval: HalfOpenInterval<String> = "A"..<"z"
XCTAssertEqual(
sql(tableRequest.filter(halfOpenInterval.contains(Col.name.collating("NOCASE")))),
"SELECT * FROM \"readers\" WHERE ((\"name\" >= 'A' COLLATE NOCASE) AND (\"name\" < 'z' COLLATE NOCASE))")
}
func testGreaterThan() {
// TODO: test compound expressions such as `average(Col.age) + 10 > 20`
XCTAssertEqual(
sql(tableRequest.filter(Col.age > 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" > 10)")
XCTAssertEqual(
sql(tableRequest.filter(10 > Col.age)),
"SELECT * FROM \"readers\" WHERE (10 > \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(10 > 10)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(Col.age > Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" > \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.name > "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" > 'B')")
XCTAssertEqual(
sql(tableRequest.filter("B" > Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' > \"name\")")
XCTAssertEqual(
sql(tableRequest.filter("B" > "B")),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(Col.name > Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" > \"name\")")
}
func testGreaterThanWithCollation() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating("NOCASE") > "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" > 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating(collation) > "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" > 'fOo' COLLATE localized_case_insensitive)")
}
func testGreaterThanOrEqual() {
// TODO: test compound expressions such as `average(Col.age) + 10 > 20`
XCTAssertEqual(
sql(tableRequest.filter(Col.age >= 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" >= 10)")
XCTAssertEqual(
sql(tableRequest.filter(10 >= Col.age)),
"SELECT * FROM \"readers\" WHERE (10 >= \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(10 >= 10)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(tableRequest.filter(Col.age >= Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" >= \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.name >= "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" >= 'B')")
XCTAssertEqual(
sql(tableRequest.filter("B" >= Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' >= \"name\")")
XCTAssertEqual(
sql(tableRequest.filter("B" >= "B")),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(tableRequest.filter(Col.name >= Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" >= \"name\")")
}
func testGreaterThanOrEqualWithCollation() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating("NOCASE") >= "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" >= 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating(collation) >= "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" >= 'fOo' COLLATE localized_case_insensitive)")
}
func testLessThan() {
// TODO: test compound expressions such as `average(Col.age) + 10 > 20`
XCTAssertEqual(
sql(tableRequest.filter(Col.age < 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" < 10)")
XCTAssertEqual(
sql(tableRequest.filter(10 < Col.age)),
"SELECT * FROM \"readers\" WHERE (10 < \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(10 < 10)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(Col.age < Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" < \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.name < "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" < 'B')")
XCTAssertEqual(
sql(tableRequest.filter("B" < Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' < \"name\")")
XCTAssertEqual(
sql(tableRequest.filter("B" < "B")),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(Col.name < Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" < \"name\")")
}
func testLessThanWithCollation() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating("NOCASE") < "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" < 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating(collation) < "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" < 'fOo' COLLATE localized_case_insensitive)")
}
func testLessThanOrEqual() {
// TODO: test compound expressions such as `average(Col.age) + 10 > 20`
XCTAssertEqual(
sql(tableRequest.filter(Col.age <= 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" <= 10)")
XCTAssertEqual(
sql(tableRequest.filter(10 <= Col.age)),
"SELECT * FROM \"readers\" WHERE (10 <= \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(10 <= 10)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(tableRequest.filter(Col.age <= Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" <= \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.name <= "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" <= 'B')")
XCTAssertEqual(
sql(tableRequest.filter("B" <= Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' <= \"name\")")
XCTAssertEqual(
sql(tableRequest.filter("B" <= "B")),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(tableRequest.filter(Col.name <= Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" <= \"name\")")
}
func testLessThanOrEqualWithCollation() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating("NOCASE") <= "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" <= 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating(collation) <= "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" <= 'fOo' COLLATE localized_case_insensitive)")
}
func testEqual() {
XCTAssertEqual(
sql(tableRequest.filter(Col.age == 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" = 10)")
XCTAssertEqual(
sql(tableRequest.filter(10 == Col.age)),
"SELECT * FROM \"readers\" WHERE (10 = \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(10 == 10)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(tableRequest.filter(Col.age == Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" = \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.age == nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(tableRequest.filter(nil == Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(tableRequest.filter(Col.age == Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" = \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.name == "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" = 'B')")
XCTAssertEqual(
sql(tableRequest.filter("B" == Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' = \"name\")")
XCTAssertEqual(
sql(tableRequest.filter("B" == "B")),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(tableRequest.filter(Col.name == Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" = \"name\")")
}
func testEqualWithCollation() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating("NOCASE") == "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" = 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating(collation) == "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" = 'fOo' COLLATE localized_case_insensitive)")
}
func testNotEqual() {
XCTAssertEqual(
sql(tableRequest.filter(Col.age != 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" <> 10)")
XCTAssertEqual(
sql(tableRequest.filter(10 != Col.age)),
"SELECT * FROM \"readers\" WHERE (10 <> \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(10 != 10)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(Col.age != Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.age != nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(tableRequest.filter(nil != Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(tableRequest.filter(Col.age != Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.name != "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" <> 'B')")
XCTAssertEqual(
sql(tableRequest.filter("B" != Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' <> \"name\")")
XCTAssertEqual(
sql(tableRequest.filter("B" != "B")),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(Col.name != Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" <> \"name\")")
}
func testNotEqualWithCollation() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating("NOCASE") != "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" <> 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating(collation) != "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" <> 'fOo' COLLATE localized_case_insensitive)")
}
func testNotEqualWithSwiftNotOperator() {
XCTAssertEqual(
sql(tableRequest.filter(!(Col.age == 10))),
"SELECT * FROM \"readers\" WHERE (\"age\" <> 10)")
XCTAssertEqual(
sql(tableRequest.filter(!(10 == Col.age))),
"SELECT * FROM \"readers\" WHERE (10 <> \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(!(10 == 10))),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(!(Col.age == Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(!(Col.age == nil))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(tableRequest.filter(!(nil == Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(tableRequest.filter(!(Col.age == Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
}
func testIs() {
XCTAssertEqual(
sql(tableRequest.filter(Col.age === 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS 10)")
XCTAssertEqual(
sql(tableRequest.filter(10 === Col.age)),
"SELECT * FROM \"readers\" WHERE (10 IS \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(10 === 10)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(tableRequest.filter(Col.age === Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.age === nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(tableRequest.filter(nil === Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(tableRequest.filter(Col.age === Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.name === "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS 'B')")
XCTAssertEqual(
sql(tableRequest.filter("B" === Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' IS \"name\")")
XCTAssertEqual(
sql(tableRequest.filter("B" === "B")),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(Col.name === Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS \"name\")")
}
func testIsWithCollation() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating("NOCASE") === "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating(collation) === "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS 'fOo' COLLATE localized_case_insensitive)")
}
func testIsNot() {
XCTAssertEqual(
sql(tableRequest.filter(Col.age !== 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT 10)")
XCTAssertEqual(
sql(tableRequest.filter(10 !== Col.age)),
"SELECT * FROM \"readers\" WHERE (10 IS NOT \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(10 !== 10)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(Col.age !== Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.age !== nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(tableRequest.filter(nil !== Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(tableRequest.filter(Col.age !== Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.name !== "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT 'B')")
XCTAssertEqual(
sql(tableRequest.filter("B" !== Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' IS NOT \"name\")")
XCTAssertEqual(
sql(tableRequest.filter("B" !== "B")),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(tableRequest.filter(Col.name !== Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT \"name\")")
}
func testIsNotWithCollation() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating("NOCASE") !== "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(tableRequest.filter(Col.name.collating(collation) !== "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT 'fOo' COLLATE localized_case_insensitive)")
}
func testIsNotWithSwiftNotOperator() {
XCTAssertEqual(
sql(tableRequest.filter(!(Col.age === 10))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT 10)")
XCTAssertEqual(
sql(tableRequest.filter(!(10 === Col.age))),
"SELECT * FROM \"readers\" WHERE (10 IS NOT \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(!(10 === 10))),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(!(Col.age === Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(!(Col.age === nil))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(tableRequest.filter(!(nil === Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(tableRequest.filter(!(Col.age === Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT \"age\")")
}
func testLogicalOperators() {
XCTAssertEqual(
sql(tableRequest.filter(!Col.age)),
"SELECT * FROM \"readers\" WHERE (NOT \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.age && true)),
"SELECT * FROM \"readers\" WHERE (\"age\" AND 1)")
XCTAssertEqual(
sql(tableRequest.filter(true && Col.age)),
"SELECT * FROM \"readers\" WHERE (1 AND \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.age || false)),
"SELECT * FROM \"readers\" WHERE (\"age\" OR 0)")
XCTAssertEqual(
sql(tableRequest.filter(false || Col.age)),
"SELECT * FROM \"readers\" WHERE (0 OR \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.age != nil || Col.name != nil)),
"SELECT * FROM \"readers\" WHERE ((\"age\" IS NOT NULL) OR (\"name\" IS NOT NULL))")
XCTAssertEqual(
sql(tableRequest.filter(Col.age != nil || Col.name != nil && Col.id != nil)),
"SELECT * FROM \"readers\" WHERE ((\"age\" IS NOT NULL) OR ((\"name\" IS NOT NULL) AND (\"id\" IS NOT NULL)))")
XCTAssertEqual(
sql(tableRequest.filter((Col.age != nil || Col.name != nil) && Col.id != nil)),
"SELECT * FROM \"readers\" WHERE (((\"age\" IS NOT NULL) OR (\"name\" IS NOT NULL)) AND (\"id\" IS NOT NULL))")
}
// MARK: - String expressions
func testLowercaseString() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.lowercaseString == "foo")),
"SELECT * FROM \"readers\" WHERE (LOWER(\"name\") = 'foo')")
}
func testUppercaseString() {
XCTAssertEqual(
sql(tableRequest.filter(Col.name.uppercaseString == "FOO")),
"SELECT * FROM \"readers\" WHERE (UPPER(\"name\") = 'FOO')")
}
// MARK: - Arithmetic expressions
func testPrefixMinusOperator() {
XCTAssertEqual(
sql(tableRequest.filter(-Col.age)),
"SELECT * FROM \"readers\" WHERE -\"age\"")
}
func testInfixMinusOperator() {
XCTAssertEqual(
sql(tableRequest.filter(Col.age - 2)),
"SELECT * FROM \"readers\" WHERE (\"age\" - 2)")
XCTAssertEqual(
sql(tableRequest.filter(2 - Col.age)),
"SELECT * FROM \"readers\" WHERE (2 - \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(2 - 2)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(tableRequest.filter(Col.age - Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" - \"age\")")
}
func testInfixPlusOperator() {
XCTAssertEqual(
sql(tableRequest.filter(Col.age + 2)),
"SELECT * FROM \"readers\" WHERE (\"age\" + 2)")
XCTAssertEqual(
sql(tableRequest.filter(2 + Col.age)),
"SELECT * FROM \"readers\" WHERE (2 + \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(2 + 2)),
"SELECT * FROM \"readers\" WHERE 4")
XCTAssertEqual(
sql(tableRequest.filter(Col.age + Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" + \"age\")")
}
func testInfixMultiplyOperator() {
XCTAssertEqual(
sql(tableRequest.filter(Col.age * 2)),
"SELECT * FROM \"readers\" WHERE (\"age\" * 2)")
XCTAssertEqual(
sql(tableRequest.filter(2 * Col.age)),
"SELECT * FROM \"readers\" WHERE (2 * \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(2 * 2)),
"SELECT * FROM \"readers\" WHERE 4")
XCTAssertEqual(
sql(tableRequest.filter(Col.age * Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" * \"age\")")
}
func testInfixDivideOperator() {
XCTAssertEqual(
sql(tableRequest.filter(Col.age / 2)),
"SELECT * FROM \"readers\" WHERE (\"age\" / 2)")
XCTAssertEqual(
sql(tableRequest.filter(2 / Col.age)),
"SELECT * FROM \"readers\" WHERE (2 / \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(2 / 2)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(tableRequest.filter(Col.age / Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" / \"age\")")
}
func testCompoundArithmeticExpression() {
// Int / Double
XCTAssertEqual(
sql(tableRequest.filter(Col.age / 2.0)),
"SELECT * FROM \"readers\" WHERE (\"age\" / 2.0)")
// Double / Int
XCTAssertEqual(
sql(tableRequest.filter(2.0 / Col.age)),
"SELECT * FROM \"readers\" WHERE (2.0 / \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(Col.age + 2 * 5)),
"SELECT * FROM \"readers\" WHERE (\"age\" + 10)")
XCTAssertEqual(
sql(tableRequest.filter(Col.age * 2 + 5)),
"SELECT * FROM \"readers\" WHERE ((\"age\" * 2) + 5)")
}
// MARK: - IFNULL expression
func testIfNull() {
var optInt: Int? = nil
let int: Int = 1
XCTAssertEqual(
sql(tableRequest.filter(Col.age ?? 2)),
"SELECT * FROM \"readers\" WHERE IFNULL(\"age\", 2)")
XCTAssertEqual(
sql(tableRequest.filter(optInt ?? Col.age)),
"SELECT * FROM \"readers\" WHERE \"age\"")
optInt = 1
XCTAssertEqual(
sql(tableRequest.filter(optInt ?? Col.age)),
"SELECT * FROM \"readers\" WHERE IFNULL(1, \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(int ?? Col.age)),
"SELECT * FROM \"readers\" WHERE IFNULL(1, \"age\")")
XCTAssertEqual(
sql(tableRequest.filter(3 ?? 2)),
"SELECT * FROM \"readers\" WHERE 3")
XCTAssertEqual(
sql(tableRequest.filter(Col.age ?? Col.age)),
"SELECT * FROM \"readers\" WHERE IFNULL(\"age\", \"age\")")
}
// MARK: - Aggregated expressions
func testCountExpression() {
XCTAssertEqual(
sql(tableRequest.select(count(Col.age))),
"SELECT COUNT(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(tableRequest.select(count(Col.age ?? 0))),
"SELECT COUNT(IFNULL(\"age\", 0)) FROM \"readers\"")
XCTAssertEqual(
sql(tableRequest.select(count(distinct: Col.age))),
"SELECT COUNT(DISTINCT \"age\") FROM \"readers\"")
XCTAssertEqual(
sql(tableRequest.select(count(distinct: Col.age / Col.age))),
"SELECT COUNT(DISTINCT (\"age\" / \"age\")) FROM \"readers\"")
}
func testAvgExpression() {
XCTAssertEqual(
sql(tableRequest.select(average(Col.age))),
"SELECT AVG(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(tableRequest.select(average(Col.age / 2))),
"SELECT AVG((\"age\" / 2)) FROM \"readers\"")
}
func testMinExpression() {
XCTAssertEqual(
sql(tableRequest.select(min(Col.age))),
"SELECT MIN(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(tableRequest.select(min(Col.age / 2))),
"SELECT MIN((\"age\" / 2)) FROM \"readers\"")
}
func testMaxExpression() {
XCTAssertEqual(
sql(tableRequest.select(max(Col.age))),
"SELECT MAX(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(tableRequest.select(max(Col.age / 2))),
"SELECT MAX((\"age\" / 2)) FROM \"readers\"")
}
func testSumExpression() {
XCTAssertEqual(
sql(tableRequest.select(sum(Col.age))),
"SELECT SUM(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(tableRequest.select(sum(Col.age / 2))),
"SELECT SUM((\"age\" / 2)) FROM \"readers\"")
}
// MARK: - Function
func testCustomFunction() {
XCTAssertEqual(
sql(tableRequest.select(customFunction.apply(Col.age, 1, 2))),
"SELECT avgOf(\"age\", 1, 2) FROM \"readers\"")
}
}
@@ -0,0 +1,191 @@
import XCTest
import GRDB
private struct Col {
static let id = SQLColumn("id")
static let name = SQLColumn("name")
static let age = SQLColumn("age")
static let readerId = SQLColumn("readerId")
}
private struct Reader : TableMapping {
static func databaseTableName() -> String {
return "readers"
}
}
class TableMappingFetchRequestTests: GRDBTestCase {
override func setUp() {
super.setUp()
var migrator = DatabaseMigrator()
migrator.registerMigration("createReaders") { db in
try db.execute(
"CREATE TABLE readers (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
try! migrator.migrate(dbQueue)
}
// MARK: - Count
func testFetchCount() {
assertNoError {
try dbQueue.inDatabase { db in
XCTAssertEqual(Reader.fetchCount(db), 0)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
let readers: [(String, Int?)] = [
("Arthur", 42),
("Barbara", 36),
("Craig", 42),
("Craig", 42),
("Daniel", nil)]
for (name, age) in readers {
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: [name, age])
}
XCTAssertEqual(Reader.fetchCount(db), 5)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
XCTAssertEqual(Reader.filter(Col.age == 42).fetchCount(db), 3)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE (\"age\" = 42)")
XCTAssertEqual(Reader.fetchCount(db, Col.age), 4)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(\"age\") FROM \"readers\"")
XCTAssertEqual(Reader.fetchCount(db, Col.age ?? 0), 5)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(IFNULL(\"age\", 0)) FROM \"readers\"")
XCTAssertEqual(Reader.fetchCount(db, distinct: Col.age), 2)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT \"age\") FROM \"readers\"")
XCTAssertEqual(Reader.fetchCount(db, distinct: Col.age / Col.age), 1)
XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT (\"age\" / \"age\")) FROM \"readers\"")
}
}
}
// MARK: - Select
func testSelectLiteral() {
assertNoError {
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42])
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36])
let request = Reader.select(sql: "name, id - 1")
let rows = Row.fetchAll(db, request)
XCTAssertEqual(self.lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"")
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0].value(atIndex: 0) as String, "Arthur")
XCTAssertEqual(rows[0].value(atIndex: 1) as Int64, 0)
XCTAssertEqual(rows[1].value(atIndex: 0) as String, "Barbara")
XCTAssertEqual(rows[1].value(atIndex: 1) as Int64, 1)
}
}
}
func testSelect() {
assertNoError {
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42])
try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36])
let request = Reader.select(Col.name, Col.id - 1)
let rows = Row.fetchAll(db, request)
XCTAssertEqual(self.lastSQLQuery, "SELECT \"name\", (\"id\" - 1) FROM \"readers\"")
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0].value(atIndex: 0) as String, "Arthur")
XCTAssertEqual(rows[0].value(atIndex: 1) as Int64, 0)
XCTAssertEqual(rows[1].value(atIndex: 0) as String, "Barbara")
XCTAssertEqual(rows[1].value(atIndex: 1) as Int64, 1)
}
}
}
func testMultipleSelect() {
XCTAssertEqual(
sql(Reader.select(Col.age).select(Col.name)),
"SELECT \"name\" FROM \"readers\"")
}
// MARK: - Filter
func testFilterLiteral() {
XCTAssertEqual(
sql(Reader.filter(sql: "id <> 1")),
"SELECT * FROM \"readers\" WHERE id <> 1")
}
func testFilter() {
XCTAssertEqual(
sql(Reader.filter(true)),
"SELECT * FROM \"readers\" WHERE 1")
}
func testMultipleFilter() {
XCTAssertEqual(
sql(Reader.filter(true).filter(false)),
"SELECT * FROM \"readers\" WHERE (1 AND 0)")
}
// MARK: - Sort
func testSortLiteral() {
XCTAssertEqual(
sql(Reader.order(sql: "lower(age) desc")),
"SELECT * FROM \"readers\" ORDER BY lower(age) desc")
}
func testSort() {
XCTAssertEqual(
sql(Reader.order(Col.age)),
"SELECT * FROM \"readers\" ORDER BY \"age\"")
XCTAssertEqual(
sql(Reader.order(Col.age.asc)),
"SELECT * FROM \"readers\" ORDER BY \"age\" ASC")
XCTAssertEqual(
sql(Reader.order(Col.age.desc)),
"SELECT * FROM \"readers\" ORDER BY \"age\" DESC")
XCTAssertEqual(
sql(Reader.order(Col.age, Col.name.desc)),
"SELECT * FROM \"readers\" ORDER BY \"age\", \"name\" DESC")
XCTAssertEqual(
sql(Reader.order(abs(Col.age))),
"SELECT * FROM \"readers\" ORDER BY ABS(\"age\")")
}
func testMultipleSort() {
XCTAssertEqual(
sql(Reader.order(Col.age).order(Col.name)),
"SELECT * FROM \"readers\" ORDER BY \"age\", \"name\"")
}
// MARK: - Limit
func testLimit() {
XCTAssertEqual(
sql(Reader.limit(1)),
"SELECT * FROM \"readers\" LIMIT 1")
XCTAssertEqual(
sql(Reader.limit(1, offset: 2)),
"SELECT * FROM \"readers\" LIMIT 1 OFFSET 2")
}
func testMultipleLimit() {
XCTAssertEqual(
sql(Reader.limit(1, offset: 2).limit(3)),
"SELECT * FROM \"readers\" LIMIT 3")
}
}
+112 -28
View File
@@ -10,8 +10,8 @@
5606AF911C0ED37000D20487 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; };
5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
560B3FAC1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */; };
560B3FAD1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */; };
560B3FAC1C19E01000C58EC7 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */; };
560B3FAD1C19E01000C58EC7 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */; };
560C97C71BFD0B8400BF8471 /* FunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */; };
560C97C81BFD0B8400BF8471 /* FunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */; };
560C97DA1C0E22D300BF8471 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86191BA988F2001F9168 /* FMDatabase.m */; };
@@ -28,18 +28,38 @@
5614DEF01BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; };
5614DEF11BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */; };
5614DEF81BAA1B43003163B3 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; };
56300B5F1C53C38F005A543B /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* FetchRequestTests.swift */; };
56300B611C53C42C005A543B /* RowConvertible+FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+FetchRequestTests.swift */; };
56300B621C53C42C005A543B /* RowConvertible+FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+FetchRequestTests.swift */; };
56300B661C53C8A7005A543B /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* FetchRequestTests.swift */; };
56300B681C53D25E005A543B /* SQLSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* SQLSupportTests.swift */; };
56300B691C53D25E005A543B /* SQLSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* SQLSupportTests.swift */; };
56300B6B1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift */; };
56300B6C1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift */; };
56300B781C53F592005A543B /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* FetchRequest.swift */; };
56300B791C53F592005A543B /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* FetchRequest.swift */; };
56300B7C1C53F592005A543B /* Collation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B721C53F592005A543B /* Collation.swift */; };
56300B7D1C53F592005A543B /* Collation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B721C53F592005A543B /* Collation.swift */; };
56300B7E1C53F592005A543B /* Function.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B731C53F592005A543B /* Function.swift */; };
56300B7F1C53F592005A543B /* Function.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B731C53F592005A543B /* Function.swift */; };
56300B801C53F592005A543B /* Operator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B741C53F592005A543B /* Operator.swift */; };
56300B811C53F592005A543B /* Operator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B741C53F592005A543B /* Operator.swift */; };
56300B821C53F592005A543B /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B751C53F592005A543B /* SQLQuery.swift */; };
56300B831C53F592005A543B /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B751C53F592005A543B /* SQLQuery.swift */; };
56300B851C54DC95005A543B /* Record+FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+FetchRequestTests.swift */; };
56300B861C54DC95005A543B /* Record+FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+FetchRequestTests.swift */; };
563445051C4A7FD7003D3DC6 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; };
563445061C4A7FD7003D3DC6 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; };
56437C841C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */; };
56437C851C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */; };
56437C841C180EDB007D6DB3 /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* Persistable.swift */; };
56437C851C180EDB007D6DB3 /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56437C831C180EDB007D6DB3 /* Persistable.swift */; };
564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; };
564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; };
56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
56553C121C3E906C00522B5C /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; };
56553C131C3E906C00522B5C /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC3773F319C8CBB3004FCF85 /* GRDB.framework */; };
56553C1A1C3E91BC00522B5C /* CrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CB92EC1BA453E500DFD5FC /* CrashTests.swift */; };
5658420E1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */; };
5658420F1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */; };
5658420E1C1A1C820099FE88 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */; };
5658420F1C1A1C820099FE88 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */; };
565B0FEF1BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; };
565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; };
565D5D681BBC604000DC9BD4 /* Row+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D671BBC604000DC9BD4 /* Row+Foundation.swift */; };
@@ -126,8 +146,8 @@
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
56A238991B9C752B0082EB20 /* DatabaseTableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */; };
56A2389A1B9C752B0082EB20 /* DatabaseTableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */; };
56A238991B9C752B0082EB20 /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238961B9C752B0082EB20 /* TableMapping.swift */; };
56A2389A1B9C752B0082EB20 /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238961B9C752B0082EB20 /* TableMapping.swift */; };
56A2389B1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */; };
56A2389C1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */; };
56A2389D1B9C752B0082EB20 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238981B9C752B0082EB20 /* RowConvertible.swift */; };
@@ -308,16 +328,26 @@
/* Begin PBXFileReference section */
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistableTests.swift; sourceTree = "<group>"; };
560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = "<group>"; };
560C97C61BFD0B8400BF8471 /* FunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionTests.swift; sourceTree = "<group>"; };
560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = "<group>"; };
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
56300B5D1C53C38F005A543B /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = "<group>"; };
56300B601C53C42C005A543B /* RowConvertible+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+FetchRequestTests.swift"; sourceTree = "<group>"; };
56300B671C53D25E005A543B /* SQLSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSupportTests.swift; sourceTree = "<group>"; };
56300B6A1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+FetchRequestTests.swift"; sourceTree = "<group>"; };
56300B6F1C53F592005A543B /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = "<group>"; };
56300B721C53F592005A543B /* Collation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Collation.swift; sourceTree = "<group>"; };
56300B731C53F592005A543B /* Function.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Function.swift; sourceTree = "<group>"; };
56300B741C53F592005A543B /* Operator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Operator.swift; sourceTree = "<group>"; };
56300B751C53F592005A543B /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
56300B841C54DC95005A543B /* Record+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+FetchRequestTests.swift"; sourceTree = "<group>"; };
563445041C4A7FD7003D3DC6 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistable.swift; sourceTree = "<group>"; };
56437C831C180EDB007D6DB3 /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollationTests.swift; sourceTree = "<group>"; };
56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableDatabasePersistableTests.swift; sourceTree = "<group>"; };
5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = "<group>"; };
565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = "<group>"; };
565D5D671BBC604000DC9BD4 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = "<group>"; };
565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = "<group>"; };
@@ -362,7 +392,7 @@
56A238761B9C75030082EB20 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = "<group>"; };
56A238781B9C75030082EB20 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = "<group>"; };
56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTableMapping.swift; sourceTree = "<group>"; };
56A238961B9C752B0082EB20 /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = "<group>"; };
56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
56A238981B9C752B0082EB20 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
@@ -501,13 +531,13 @@
path = TransactionObserver;
sourceTree = "<group>";
};
560B3FA41C19DFF800C58EC7 /* DatabasePersistable */ = {
560B3FA41C19DFF800C58EC7 /* Persistable */ = {
isa = PBXGroup;
children = (
560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */,
5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */,
560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */,
5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */,
);
path = DatabasePersistable;
path = Persistable;
sourceTree = "<group>";
};
560C97BF1BFD0B5B00BF8471 /* Function */ = {
@@ -527,6 +557,38 @@
name = Frameworks;
sourceTree = "<group>";
};
56300B5C1C53C38F005A543B /* FetchRequest */ = {
isa = PBXGroup;
children = (
56300B5D1C53C38F005A543B /* FetchRequestTests.swift */,
56300B841C54DC95005A543B /* Record+FetchRequestTests.swift */,
56300B601C53C42C005A543B /* RowConvertible+FetchRequestTests.swift */,
56300B671C53D25E005A543B /* SQLSupportTests.swift */,
56300B6A1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift */,
);
path = FetchRequest;
sourceTree = "<group>";
};
56300B6D1C53F592005A543B /* FetchRequest */ = {
isa = PBXGroup;
children = (
56300B6F1C53F592005A543B /* FetchRequest.swift */,
56300B711C53F592005A543B /* SQLSupport */,
);
path = FetchRequest;
sourceTree = "<group>";
};
56300B711C53F592005A543B /* SQLSupport */ = {
isa = PBXGroup;
children = (
56300B721C53F592005A543B /* Collation.swift */,
56300B731C53F592005A543B /* Function.swift */,
56300B741C53F592005A543B /* Operator.swift */,
56300B751C53F592005A543B /* SQLQuery.swift */,
);
path = SQLSupport;
sourceTree = "<group>";
};
564A50BF1BFF4B6E00B3A3A2 /* Collation */ = {
isa = PBXGroup;
children = (
@@ -549,6 +611,7 @@
56CB92EC1BA453E500DFD5FC /* CrashTests.swift */,
56A238111B9C74A90082EB20 /* Core */,
56B7F4281BE149F600E39BBF /* CoreGraphics */,
56300B5C1C53C38F005A543B /* FetchRequest */,
56F0B98C1B6001C600A2F135 /* Foundation */,
56A238231B9C74A90082EB20 /* Migrations */,
56A238251B9C74A90082EB20 /* Record */,
@@ -591,7 +654,7 @@
56AC8CCC1BA3F267009E4319 /* Concurrency */,
56A238121B9C74A90082EB20 /* Database */,
56A238151B9C74A90082EB20 /* DatabaseError */,
560B3FA41C19DFF800C58EC7 /* DatabasePersistable */,
560B3FA41C19DFF800C58EC7 /* Persistable */,
56A238171B9C74A90082EB20 /* DatabaseValue */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
560C97BF1BFD0B5B00BF8471 /* Function */,
@@ -702,7 +765,6 @@
56A2386F1B9C75030082EB20 /* Core */ = {
isa = PBXGroup;
children = (
56A238951B9C752B0082EB20 /* Protocols */,
56A238701B9C75030082EB20 /* Configuration.swift */,
56A238711B9C75030082EB20 /* Database.swift */,
56A238731B9C75030082EB20 /* DatabaseError.swift */,
@@ -711,6 +773,7 @@
56A238761B9C75030082EB20 /* Row.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
563445041C4A7FD7003D3DC6 /* Utils.swift */,
56A238951B9C752B0082EB20 /* Protocols */,
);
path = Core;
sourceTree = "<group>";
@@ -727,11 +790,11 @@
56A238951B9C752B0082EB20 /* Protocols */ = {
isa = PBXGroup;
children = (
56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */,
56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */,
56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */,
56437C831C180EDB007D6DB3 /* Persistable.swift */,
56A238981B9C752B0082EB20 /* RowConvertible.swift */,
5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */,
56A238961B9C752B0082EB20 /* TableMapping.swift */,
);
path = Protocols;
sourceTree = "<group>";
@@ -925,6 +988,7 @@
children = (
56A2386F1B9C75030082EB20 /* Core */,
56B7F4251BE148FE00E39BBF /* CoreGraphics */,
56300B6D1C53F592005A543B /* FetchRequest */,
56A238001B9C6A1E0082EB20 /* Foundation */,
56A238911B9C750B0082EB20 /* Migrations */,
56A2389F1B9C753B0082EB20 /* Record */,
@@ -1275,7 +1339,8 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56437C851C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */,
56300B791C53F592005A543B /* FetchRequest.swift in Sources */,
56437C851C180EDB007D6DB3 /* Persistable.swift in Sources */,
56E589201BBA5D5400CC0140 /* NSURL.swift in Sources */,
56A2380A1B9C6DD20082EB20 /* StandardLibraryTypes.swift in Sources */,
5614DEF11BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */,
@@ -1283,8 +1348,10 @@
563445061C4A7FD7003D3DC6 /* Utils.swift in Sources */,
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
56A238AB1B9C7E540082EB20 /* StatementArguments+Foundation.swift in Sources */,
56300B7F1C53F592005A543B /* Function.swift in Sources */,
56A2389E1B9C752B0082EB20 /* RowConvertible.swift in Sources */,
56A238031B9C6A650082EB20 /* DatabaseDateComponents.swift in Sources */,
56300B7D1C53F592005A543B /* Collation.swift in Sources */,
56A238A51B9C753B0082EB20 /* Record.swift in Sources */,
56A238101B9C74460082EB20 /* RawRepresentable.swift in Sources */,
56A238061B9C6D670082EB20 /* NSDate.swift in Sources */,
@@ -1296,14 +1363,16 @@
56B7F4271BE1491700E39BBF /* CGFloat.swift in Sources */,
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */,
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */,
56300B811C53F592005A543B /* Operator.swift in Sources */,
56A2389C1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */,
565D5D691BBC604000DC9BD4 /* Row+Foundation.swift in Sources */,
56A238AE1B9C90090082EB20 /* NSNull.swift in Sources */,
56A2389A1B9C752B0082EB20 /* DatabaseTableMapping.swift in Sources */,
56A2389A1B9C752B0082EB20 /* TableMapping.swift in Sources */,
56A238881B9C75030082EB20 /* Row.swift in Sources */,
56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */,
56B7F4351BE4BF1600E39BBF /* DatabaseCoder.swift in Sources */,
56300B831C53F592005A543B /* SQLQuery.swift in Sources */,
56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -1313,6 +1382,7 @@
buildActionMask = 2147483647;
files = (
56A238601B9C74A90082EB20 /* RecordDescriptionTests.swift in Sources */,
56300B861C54DC95005A543B /* Record+FetchRequestTests.swift in Sources */,
56A238561B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */,
56A238501B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
56AC8CCF1BA3F2AD009E4319 /* ConcurrencyTests.swift in Sources */,
@@ -1320,6 +1390,7 @@
56B7F4381BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */,
564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */,
56E8CE111BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift in Sources */,
56300B691C53D25E005A543B /* SQLSupportTests.swift in Sources */,
56A2384A1B9C74A90082EB20 /* SelectStatementTests.swift in Sources */,
56A2384C1B9C74A90082EB20 /* UpdateStatementTests.swift in Sources */,
56A2384E1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */,
@@ -1332,11 +1403,12 @@
56FDECE31BB32DFD009AD709 /* MetalRowTests.swift in Sources */,
56DE7B121C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */,
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
56300B621C53C42C005A543B /* RowConvertible+FetchRequestTests.swift in Sources */,
56EB0AB31BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */,
56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */,
56FC78691BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */,
56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */,
5658420F1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */,
5658420F1C1A1C820099FE88 /* MutablePersistableTests.swift in Sources */,
56FC78671BBAEB8C00CA1285 /* MappingTests.swift in Sources */,
56A238441B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */,
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */,
@@ -1354,9 +1426,11 @@
56CA21BB1BB3FCF7009A04C5 /* NSDataTests.swift in Sources */,
56A238B71B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */,
565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */,
560B3FAD1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */,
56300B6C1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift in Sources */,
560B3FAD1C19E01000C58EC7 /* PersistableTests.swift in Sources */,
56F0B9921B6001C600A2F135 /* NSDateTests.swift in Sources */,
56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */,
56300B5F1C53C38F005A543B /* FetchRequestTests.swift in Sources */,
56F0B9901B6001C600A2F135 /* NSDateComponentsTests.swift in Sources */,
560C97C81BFD0B8400BF8471 /* FunctionTests.swift in Sources */,
56A2383A1B9C74A90082EB20 /* InMemoryDatabaseTests.swift in Sources */,
@@ -1371,6 +1445,7 @@
buildActionMask = 2147483647;
files = (
5614DEF81BAA1B43003163B3 /* DatabaseValueConversionTests.swift in Sources */,
56300B851C54DC95005A543B /* Record+FetchRequestTests.swift in Sources */,
56A2385F1B9C74A90082EB20 /* RecordDescriptionTests.swift in Sources */,
56A238551B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */,
56A2384F1B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
@@ -1378,6 +1453,7 @@
56A238451B9C74A90082EB20 /* DictionaryRowTests.swift in Sources */,
56A238491B9C74A90082EB20 /* SelectStatementTests.swift in Sources */,
56B7F4371BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */,
56300B681C53D25E005A543B /* SQLSupportTests.swift in Sources */,
564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */,
56A2384B1B9C74A90082EB20 /* UpdateStatementTests.swift in Sources */,
56A2384D1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */,
@@ -1390,11 +1466,12 @@
56A238531B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift in Sources */,
56DE7B111C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */,
56A238671B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
56300B611C53C42C005A543B /* RowConvertible+FetchRequestTests.swift in Sources */,
56A2385D1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */,
56A238431B9C74A90082EB20 /* RawRepresentableTests.swift in Sources */,
56EB0AB21BCD787300A3DC55 /* NSDataMemoryTests.swift in Sources */,
56FC78681BBAEB8C00CA1285 /* ManagedDataControllerTests.swift in Sources */,
5658420E1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift in Sources */,
5658420E1C1A1C820099FE88 /* MutablePersistableTests.swift in Sources */,
56FC78661BBAEB8C00CA1285 /* MappingTests.swift in Sources */,
56A238691B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */,
5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */,
@@ -1412,9 +1489,11 @@
56CA21BA1BB3FCF7009A04C5 /* NSDataTests.swift in Sources */,
56A238B61B9CA2590082EB20 /* DatabaseTimestampTests.swift in Sources */,
565D5D741BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */,
560B3FAC1C19E01000C58EC7 /* DatabasePersistableTests.swift in Sources */,
56300B6B1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift in Sources */,
560B3FAC1C19E01000C58EC7 /* PersistableTests.swift in Sources */,
56F0B9911B6001C600A2F135 /* NSDateTests.swift in Sources */,
56A238371B9C74A90082EB20 /* DatabaseTests.swift in Sources */,
56300B661C53C8A7005A543B /* FetchRequestTests.swift in Sources */,
56F0B98F1B6001C600A2F135 /* NSDateComponentsTests.swift in Sources */,
560C97C71BFD0B8400BF8471 /* FunctionTests.swift in Sources */,
56A238391B9C74A90082EB20 /* InMemoryDatabaseTests.swift in Sources */,
@@ -1428,20 +1507,23 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56300B781C53F592005A543B /* FetchRequest.swift in Sources */,
56A238AD1B9C90090082EB20 /* NSNull.swift in Sources */,
56437C841C180EDB007D6DB3 /* DatabasePersistable.swift in Sources */,
56437C841C180EDB007D6DB3 /* Persistable.swift in Sources */,
56E5891F1BBA5D5400CC0140 /* NSURL.swift in Sources */,
56A2389D1B9C752B0082EB20 /* RowConvertible.swift in Sources */,
5614DEF01BA9DA15003163B3 /* SQLiteStatementConvertible.swift in Sources */,
563445051C4A7FD7003D3DC6 /* Utils.swift in Sources */,
56A238051B9C6D670082EB20 /* NSDate.swift in Sources */,
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
56300B7E1C53F592005A543B /* Function.swift in Sources */,
56B7F42E1BE14CD400E39BBF /* CGFloat.swift in Sources */,
56A2389B1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */,
56300B7C1C53F592005A543B /* Collation.swift in Sources */,
56A2380F1B9C74460082EB20 /* RawRepresentable.swift in Sources */,
56A238AA1B9C7E540082EB20 /* StatementArguments+Foundation.swift in Sources */,
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
56A238991B9C752B0082EB20 /* DatabaseTableMapping.swift in Sources */,
56A238991B9C752B0082EB20 /* TableMapping.swift in Sources */,
56CA0D411BF5D8E20019C023 /* DatabaseValue+Foundation.swift in Sources */,
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
56A238A41B9C753B0082EB20 /* Record.swift in Sources */,
@@ -1449,6 +1531,7 @@
56A238021B9C6A650082EB20 /* DatabaseDateComponents.swift in Sources */,
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */,
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */,
56300B801C53F592005A543B /* Operator.swift in Sources */,
56A238B31B9C919D0082EB20 /* NSNumber.swift in Sources */,
56A238B01B9C90BB0082EB20 /* NSString.swift in Sources */,
565D5D681BBC604000DC9BD4 /* Row+Foundation.swift in Sources */,
@@ -1457,6 +1540,7 @@
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
56A238871B9C75030082EB20 /* Row.swift in Sources */,
56B7F4341BE4BF1600E39BBF /* DatabaseCoder.swift in Sources */,
56300B821C53F592005A543B /* SQLQuery.swift in Sources */,
56A2380C1B9C6E440082EB20 /* NSData.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
/// Configuration are arguments to the DatabaseQueue initializers.
/// Configure a DatabaseQueue
public struct Configuration {
// MARK: - Misc options
+1 -1
View File
@@ -515,7 +515,7 @@ extension Database {
/// A Collation.
public class DatabaseCollation : Hashable {
let name: String
public let name: String
let function: (String, String) -> NSComparisonResult
/// The hash value.
@@ -14,7 +14,7 @@
/// String.fetchOne(statement, arguments:...) // String?
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public protocol DatabaseValueConvertible {
public protocol DatabaseValueConvertible : _SQLExpressionType {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
@@ -38,6 +38,9 @@ public protocol DatabaseValueConvertible {
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public extension DatabaseValueConvertible {
// MARK: - Fetching From SelectStatement
/// Returns a sequence of values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
@@ -58,6 +61,7 @@ public extension DatabaseValueConvertible {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
let sqliteStatement = statement.sqliteStatement
return statement.fetchSequence(arguments: arguments) {
@@ -73,6 +77,7 @@ public extension DatabaseValueConvertible {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
return Array(fetch(statement, arguments: arguments))
}
@@ -88,6 +93,7 @@ public extension DatabaseValueConvertible {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional value.
@warn_unused_result
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
let sequence = statement.fetchSequence(arguments: arguments) {
fromDatabaseValue(DatabaseValue(sqliteStatement: statement.sqliteStatement, index: 0))
@@ -98,6 +104,9 @@ public extension DatabaseValueConvertible {
return nil
}
// MARK: - Fetching From SQL
/// Returns a sequence of values fetched from an SQL query.
///
/// let names = String.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String>
@@ -118,6 +127,7 @@ public extension DatabaseValueConvertible {
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -130,6 +140,7 @@ public extension DatabaseValueConvertible {
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -145,6 +156,7 @@ public extension DatabaseValueConvertible {
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -164,6 +176,9 @@ public extension DatabaseValueConvertible {
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: - Fetching From SelectStatement
/// Returns a sequence of optional values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
@@ -184,6 +199,7 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of optional values.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Wrapped?> {
let sqliteStatement = statement.sqliteStatement
return statement.fetchSequence(arguments: arguments) {
@@ -199,10 +215,14 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of optional values.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Wrapped?] {
return Array(fetch(statement, arguments: arguments))
}
// MARK: - Fetching From SQL
/// Returns a sequence of optional values fetched from an SQL query.
///
/// let names = Optional<String>.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String?>
@@ -223,6 +243,7 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -235,6 +256,7 @@ public extension Optional where Wrapped: DatabaseValueConvertible {
/// - parameter sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of optional values.
@warn_unused_result
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Wrapped?] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
}
@@ -1,11 +1,11 @@
// MARK: - PersistenceError
/// An error thrown by a type that adopts DatabasePersistable.
/// An error thrown by a type that adopts Persistable.
public enum PersistenceError: ErrorType {
/// Thrown by MutableDatabasePersistable.update() when no matching row could be
/// Thrown by MutablePersistable.update() when no matching row could be
/// found in the database.
case NotFound(MutableDatabasePersistable)
case NotFound(MutablePersistable)
}
extension PersistenceError : CustomStringConvertible {
@@ -34,26 +34,25 @@ private func databaseValues(forColumns columns: [String], inDictionary dictionar
}
// MARK: - MutableDatabasePersistable
// MARK: - MutablePersistable
/// Types that adopt MutableDatabasePersistable can be inserted, updated,
/// and deleted.
/// Types that adopt MutablePersistable can be inserted, updated, and deleted.
///
/// 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.
///
/// The insert() and save() methods are mutating methods.
public protocol MutableDatabasePersistable : DatabaseTableMapping {
public protocol MutablePersistable : TableMapping {
/// Returns the values that should be stored in the database.
///
/// Keys of the returned dictionary must match the column names of the
/// target database table (see DatabaseTableMapping.databaseTableName()).
/// target database table (see TableMapping.databaseTableName()).
///
/// In particular, primary key columns, if any, must be included.
///
/// struct Person : MutableDatabasePersistable {
/// struct Person : MutablePersistable {
/// var id: Int64?
/// var name: String?
///
@@ -69,7 +68,7 @@ public protocol MutableDatabasePersistable : DatabaseTableMapping {
///
/// This method is optional: the default implementation does nothing.
///
/// struct Person : MutableDatabasePersistable {
/// struct Person : MutablePersistable {
/// var id: Int64?
/// var name: String?
///
@@ -160,7 +159,7 @@ public protocol MutableDatabasePersistable : DatabaseTableMapping {
func exists(db: Database) -> Bool
}
public extension MutableDatabasePersistable {
public extension MutablePersistable {
/// The default implementation does nothing.
mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
@@ -222,11 +221,11 @@ public extension MutableDatabasePersistable {
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutableDatabasePersistable.
/// that adopt MutablePersistable.
///
/// performInsert() provides the default implementation for insert(). Types
/// that adopt MutableDatabasePersistable can invoke performInsert() in
/// their implementation of insert(). They should not provide their own
/// that adopt MutablePersistable can invoke performInsert() in their
/// implementation of insert(). They should not provide their own
/// implementation of performInsert().
mutating func performInsert(db: Database) throws {
let dataMapper = DataMapper(db, self)
@@ -237,11 +236,11 @@ public extension MutableDatabasePersistable {
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutableDatabasePersistable.
/// that adopt MutablePersistable.
///
/// performUpdate() provides the default implementation for update(). Types
/// that adopt MutableDatabasePersistable can invoke performUpdate() in
/// their implementation of update(). They should not provide their own
/// that adopt MutablePersistable can invoke performUpdate() in their
/// implementation of update(). They should not provide their own
/// implementation of performUpdate().
func performUpdate(db: Database) throws {
let changes = try DataMapper(db, self).updateStatement().execute()
@@ -251,10 +250,10 @@ public extension MutableDatabasePersistable {
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutableDatabasePersistable.
/// that adopt MutablePersistable.
///
/// performSave() provides the default implementation for save(). Types
/// that adopt MutableDatabasePersistable can invoke performSave() in their
/// that adopt MutablePersistable can invoke performSave() in their
/// implementation of save(). They should not provide their own
/// implementation of performSave().
///
@@ -280,10 +279,10 @@ public extension MutableDatabasePersistable {
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutableDatabasePersistable.
/// that adopt MutablePersistable.
///
/// performDelete() provides the default implementation for deelte(). Types
/// that adopt MutableDatabasePersistable can invoke performDelete() in
/// 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 {
@@ -291,10 +290,10 @@ public extension MutableDatabasePersistable {
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt MutableDatabasePersistable.
/// that adopt MutablePersistable.
///
/// performExists() provides the default implementation for exists(). Types
/// that adopt MutableDatabasePersistable can invoke performExists() in
/// 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 {
@@ -304,15 +303,15 @@ public extension MutableDatabasePersistable {
}
// MARK: - DatabasePersistable
// MARK: - Persistable
/// Types that adopt DatabasePersistable can be inserted, updated, and deleted.
/// Types that adopt Persistable can be inserted, updated, and deleted.
///
/// This protocol is intented for types that don't have an INTEGER PRIMARY KEY.
///
/// Unlike MutableDatabasePersistable, the insert() and save() methods are not
/// Unlike MutablePersistable, the insert() and save() methods are not
/// mutating methods.
public protocol DatabasePersistable : MutableDatabasePersistable {
public protocol Persistable : MutablePersistable {
/// Don't call this method directly: it is called upon successful insertion,
/// with the inserted RowID and the eventual INTEGER PRIMARY KEY
@@ -321,7 +320,7 @@ public protocol DatabasePersistable : MutableDatabasePersistable {
/// This method is optional: the default implementation does nothing.
///
/// If you need a mutating variant of this method, adopt the
/// MutableDatabasePersistable protocol instead.
/// MutablePersistable protocol instead.
///
/// - parameter rowID: The inserted rowID.
/// - parameter column: The name of the eventual INTEGER PRIMARY KEY column.
@@ -365,7 +364,7 @@ public protocol DatabasePersistable : MutableDatabasePersistable {
func save(db: Database) throws
}
public extension DatabasePersistable {
public extension Persistable {
/// The default implementation does nothing.
func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
@@ -392,10 +391,10 @@ public extension DatabasePersistable {
// MARK: - Immutable CRUD Internals
/// Don't invoke this method directly: it is an internal method for types
/// that adopt DatabasePersistable.
/// that adopt Persistable.
///
/// performInsert() provides the default implementation for insert(). Types
/// that adopt DatabasePersistable can invoke performInsert() in their
/// 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 {
@@ -407,10 +406,10 @@ public extension DatabasePersistable {
}
/// Don't invoke this method directly: it is an internal method for types
/// that adopt DatabasePersistable.
/// that adopt Persistable.
///
/// performSave() provides the default implementation for save(). Types
/// that adopt DatabasePersistable can invoke performSave() in their
/// that adopt Persistable can invoke performSave() in their
/// implementation of save(). They should not provide their own
/// implementation of performSave().
///
@@ -440,14 +439,14 @@ public extension DatabasePersistable {
// MARK: - DataMapper
/// DataMapper takes care of DatabasePersistable CRUD
/// DataMapper takes care of Persistable CRUD
final class DataMapper {
/// The database
let db: Database
/// The persistable
let persistable: MutableDatabasePersistable
let persistable: MutablePersistable
/// DataMapper keeps a copy the persistable's persistentDictionary, so
/// that this dictionary is built once whatever the database operation.
@@ -460,7 +459,7 @@ final class DataMapper {
/// The table primary key
let primaryKey: PrimaryKey
init(_ db: Database, _ persistable: MutableDatabasePersistable) {
init(_ db: Database, _ persistable: MutablePersistable) {
// Fail early if database table does not exist.
let databaseTableName = persistable.dynamicType.databaseTableName()
let primaryKey = try! db.primaryKey(databaseTableName)
+7 -1
View File
@@ -61,6 +61,7 @@ extension RowConvertible {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
let row = Row(statement: statement)
let database = statement.database
@@ -79,6 +80,7 @@ extension RowConvertible {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
return Array(fetch(statement, arguments: arguments))
}
@@ -91,12 +93,13 @@ extension RowConvertible {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional value.
@warn_unused_result
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
return fetch(statement, arguments: arguments).generate().next()
}
// MARK: - Fetching From Database
// MARK: - Fetching From SQL
/// Returns a sequence of values fetched from an SQL query.
///
@@ -118,6 +121,7 @@ extension RowConvertible {
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -130,6 +134,7 @@ extension RowConvertible {
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -142,6 +147,7 @@ extension RowConvertible {
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -30,6 +30,9 @@ public protocol SQLiteStatementConvertible {
/// See DatabaseValueConvertible for more information.
public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible {
// MARK: - Fetching From SelectStatement
/// Returns a sequence of values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
@@ -50,6 +53,7 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of values.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
let sqliteStatement = statement.sqliteStatement
return statement.fetchSequence(arguments: arguments) {
@@ -68,6 +72,7 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of values.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
return Array(fetch(statement, arguments: arguments))
}
@@ -80,6 +85,7 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional value.
@warn_unused_result
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
let sqliteStatement = statement.sqliteStatement
let isNullSequence = statement.fetchSequence(arguments: arguments) {
@@ -91,6 +97,9 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
return nil
}
// MARK: - Fetching From SQL
/// Returns a sequence of values fetched from an SQL query.
///
/// let names = String.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String>
@@ -111,6 +120,7 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -123,6 +133,7 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -135,6 +146,7 @@ public extension DatabaseValueConvertible where Self: SQLiteStatementConvertible
/// - parameter sql: An SQL query.
/// - parameter 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)
}
@@ -1,19 +1,19 @@
/// Types that adopt DatabaseTableMapping declare a particular relationship with
/// Types that adopt TableMapping declare a particular relationship with
/// a database table.
///
/// Types that adopt both DatabaseTableMapping and RowConvertible are granted
/// with built-in methods that allow to fetch instances identified by key:
/// Types that adopt both TableMapping and RowConvertible are granted with
/// built-in methods that allow to fetch instances identified by key:
///
/// Person.fetchOne(db, key: 123) // Person?
/// Citizenship.fetchOne(db, key: ["personId": 12, "countryId": 45]) // Citizenship?
///
/// DatabaseTableMapping is adopted by Record.
public protocol DatabaseTableMapping {
/// TableMapping is adopted by Record.
public protocol TableMapping {
/// The name of the database table
static func databaseTableName() -> String
}
extension RowConvertible where Self: DatabaseTableMapping {
extension RowConvertible where Self: TableMapping {
// MARK: - Single-Column Primary Key
@@ -26,6 +26,7 @@ extension RowConvertible where Self: DatabaseTableMapping {
/// - parameter db: A Database.
/// - parameter keys: An array of primary keys.
/// - returns: A sequence.
@warn_unused_result
public static func fetch<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(db: Database, keys: Sequence) -> DatabaseSequence<Self> {
guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else {
return DatabaseSequence.emptySequence(db)
@@ -42,6 +43,7 @@ extension RowConvertible where Self: DatabaseTableMapping {
/// - parameter db: A Database.
/// - parameter keys: An array of primary keys.
/// - returns: An array.
@warn_unused_result
public static func fetchAll<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(db: Database, keys: Sequence) -> [Self] {
guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else {
return []
@@ -56,6 +58,7 @@ extension RowConvertible where Self: DatabaseTableMapping {
/// - parameter db: A Database.
/// - parameter key: A primary key value.
/// - returns: An optional value.
@warn_unused_result
public static func fetchOne<PrimaryKeyType: DatabaseValueConvertible>(db: Database, key: PrimaryKeyType?) -> Self? {
guard let key = key else {
return nil
@@ -66,6 +69,7 @@ extension RowConvertible where Self: DatabaseTableMapping {
// Returns "SELECT * FROM table WHERE id IN (?,?,?)"
//
// 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? {
// Fail early if database table does not exist.
let databaseTableName = self.databaseTableName()
@@ -109,6 +113,7 @@ extension RowConvertible where Self: DatabaseTableMapping {
/// - parameter db: A Database.
/// - parameter keys: An array of key dictionaries.
/// - returns: A sequence.
@warn_unused_result
public static func fetch(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> DatabaseSequence<Self> {
guard let statement = fetchByKeyStatement(db, keys: keys) else {
return DatabaseSequence.emptySequence(db)
@@ -125,6 +130,7 @@ extension RowConvertible where Self: DatabaseTableMapping {
/// - parameter db: A Database.
/// - parameter keys: An array of key dictionaries.
/// - returns: An array.
@warn_unused_result
public static func fetchAll(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> [Self] {
guard let statement = fetchByKeyStatement(db, keys: keys) else {
return []
@@ -139,6 +145,7 @@ extension RowConvertible where Self: DatabaseTableMapping {
/// - parameter db: A Database.
/// - parameter key: A dictionary of values.
/// - returns: An optional value.
@warn_unused_result
public static func fetchOne(db: Database, key: [String: DatabaseValueConvertible?]) -> Self? {
return fetchOne(fetchByKeyStatement(db, keys: [key])!)
}
@@ -146,6 +153,7 @@ extension RowConvertible where Self: DatabaseTableMapping {
// Returns "SELECT * FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
//
// Returns nil if keys is empty.
@warn_unused_result
private static func fetchByKeyStatement(db: Database, keys: [[String: DatabaseValueConvertible?]]) -> SelectStatement? {
// Avoid performing useless SELECT
guard keys.count > 0 else {
+17 -7
View File
@@ -391,13 +391,14 @@ public final class Row: CollectionType {
}
// MARK: - Fetch Rows
// MARK: - Fetching From SelectStatement
/// Returns a sequence of rows fetched from a prepared statement.
///
/// for row in Row.fetch(db, "SELECT id, name FROM persons") {
/// let id = row.int64(atIndex: 0)
/// let name = row.string(atIndex: 1)
/// let statement = db.selectStatement("SELECT ...")
/// for row in Row.fetch(statement) {
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// }
///
/// Fetched rows are reused during the sequence iteration: don't wrap a row
@@ -424,6 +425,7 @@ public final class Row: CollectionType {
/// - parameter sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of rows.
@warn_unused_result
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Row> {
// Metal rows can be reused. And reusing them yields better performance.
let row = Row(statement: statement)
@@ -438,6 +440,7 @@ public final class Row: CollectionType {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of rows.
@warn_unused_result
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Row] {
let sequence = statement.fetchSequence(arguments: arguments) {
Row(copiedFromStatement: statement)
@@ -453,6 +456,7 @@ public final class Row: CollectionType {
/// - parameter statement: The statement to run.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional row.
@warn_unused_result
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Row? {
let sequence = statement.fetchSequence(arguments: arguments) {
Row(copiedFromStatement: statement)
@@ -460,11 +464,14 @@ public final class Row: CollectionType {
return sequence.generate().next()
}
// MARK: - Fetching From SQL
/// Returns a sequence of rows fetched from an SQL query.
///
/// for row in Row.fetch(db, "SELECT id, name FROM persons") {
/// let id = row.int64(atIndex: 0)
/// let name = row.string(atIndex: 1)
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// }
///
/// Fetched rows are reused during the sequence iteration: don't wrap a row
@@ -491,6 +498,7 @@ public final class Row: CollectionType {
/// - parameter sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - returns: A sequence of rows.
@warn_unused_result
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Row> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
}
@@ -503,6 +511,7 @@ public final class Row: CollectionType {
/// - parameter sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - returns: An array of rows.
@warn_unused_result
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> [Row] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
}
@@ -515,10 +524,11 @@ public final class Row: CollectionType {
/// - parameter sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - returns: An optional row.
@warn_unused_result
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> Row? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments)
}
// MARK: - Not Public
+22 -10
View File
@@ -120,7 +120,7 @@ public class Statement {
}
}
private func setArgumentsWithValidation(arguments: StatementArguments) throws {
func setArgumentsWithValidation(arguments: StatementArguments) throws {
// Validate
let bindings = try validatedBindings(arguments)
_arguments = arguments
@@ -291,6 +291,7 @@ public final class SelectStatement : Statement {
}
/// The DatabaseSequence builder.
@warn_unused_result
func fetchSequence<T>(arguments arguments: StatementArguments?, element: () -> T) -> DatabaseSequence<T> {
// Force arguments validity. See UpdateStatement.execute(), and Database.execute()
try! prepareWithArguments(arguments)
@@ -479,6 +480,16 @@ public struct DatabaseChanges {
/// See https://www.sqlite.org/lang_expr.html#varparam for more information.
public struct StatementArguments {
public var isEmpty: Bool {
switch kind {
case .Values(let values):
return values.isEmpty
case .NamedValues(let namedValues):
return namedValues.isEmpty
}
}
// MARK: Positional Arguments
/// Initializes arguments from a sequence of optional values.
@@ -530,18 +541,19 @@ public struct StatementArguments {
kind = .NamedValues(Dictionary(sequence.map { (key, value) in return (key, value as DatabaseValueConvertible?) }))
}
public var isEmpty: Bool {
switch kind {
case .Values(let values):
return values.isEmpty
case .NamedValues(let namedValues):
return namedValues.isEmpty
}
}
// MARK: Not Public
/// Returns a double optional
func value(named name: String) -> DatabaseValueConvertible?? {
switch kind {
case .Values:
return nil
case .NamedValues(let dictionary):
return dictionary[name]
}
}
enum Kind {
case Values([DatabaseValueConvertible?])
case NamedValues(Dictionary<String, DatabaseValueConvertible?>)
+539
View File
@@ -0,0 +1,539 @@
/// A FetchRequest describes an SQL query.
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct FetchRequest<T> {
let query: _SQLQuery
/// Initializes a FetchRequest based on table *tableName*.
public init(tableName: String) {
self.init(_SQLQuery(select: [_SQLResultColumn.Star(nil)], from: .Table(name: tableName, alias: nil)))
}
/// Returns a prepared statement that is ready to be executed.
@warn_unused_result
public func selectStatement(db: Database) throws -> SelectStatement {
// TODO: split statement generation from arguments building
var bindings: [DatabaseValueConvertible?] = []
let sql = try query.sql(db, &bindings)
let statement = try db.selectStatement(sql)
try statement.setArgumentsWithValidation(StatementArguments(bindings))
return statement
}
init(_ query: _SQLQuery) {
self.query = query
}
}
extension FetchRequest {
// MARK: Request Derivation
/// Returns a new FetchRequest with a new net of selected columns.
@warn_unused_result
public func select(selection: _SQLSelectable...) -> FetchRequest<T> {
return select(selection)
}
/// Returns a new FetchRequest with a new net of selected columns.
@warn_unused_result
public func select(selection: [_SQLSelectable]) -> FetchRequest<T> {
return FetchRequest(query.select(selection))
}
/// Returns a new FetchRequest with a new net of selected columns.
@warn_unused_result
public func select(sql sql: String) -> FetchRequest<T> {
return select(SQLLiteral(sql))
}
/// Returns a new FetchRequest which returns distinct rows.
public var distinct: FetchRequest<T> {
var query = self.query
query.distinct = true
return FetchRequest(query)
}
/// Returns a new FetchRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
@warn_unused_result
public func filter(predicate: _SQLExpressionType) -> FetchRequest<T> {
return FetchRequest(query.filter(predicate.SQLExpression))
}
/// Returns a new FetchRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
@warn_unused_result
public func filter(sql sql: String) -> FetchRequest<T> {
return filter(SQLLiteral(sql))
}
/// Returns a new FetchRequest grouped according to *expressions*.
@warn_unused_result
public func group(expressions: _SQLExpressionType...) -> FetchRequest<T> {
return group(expressions)
}
/// Returns a new FetchRequest grouped according to *expressions*.
@warn_unused_result
public func group(expressions: [_SQLExpressionType]) -> FetchRequest<T> {
return FetchRequest(query.group(expressions.map { $0.SQLExpression }))
}
/// Returns a new FetchRequest with a new grouping.
@warn_unused_result
public func group(sql sql: String) -> FetchRequest<T> {
return group(SQLLiteral(sql))
}
/// Returns a new FetchRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
@warn_unused_result
public func having(predicate: _SQLExpressionType) -> FetchRequest<T> {
return FetchRequest(query.having(predicate.SQLExpression))
}
/// Returns a new FetchRequest with the provided *sql* added to
/// the eventual set of already applied predicates.
@warn_unused_result
public func having(sql sql: String) -> FetchRequest<T> {
return having(SQLLiteral(sql))
}
/// Returns a new FetchRequest with the provided *sortDescriptors* added to
/// the eventual set of already applied sort descriptors.
@warn_unused_result
public func order(sortDescriptors: _SQLSortDescriptorType...) -> FetchRequest<T> {
return order(sortDescriptors)
}
/// Returns a new FetchRequest with the provided *sortDescriptors* added to
/// the eventual set of already applied sort descriptors.
@warn_unused_result
public func order(sortDescriptors: [_SQLSortDescriptorType]) -> FetchRequest<T> {
return FetchRequest(query.order(sortDescriptors))
}
/// Returns a new FetchRequest with the provided *sql* added to the
/// eventual set of already applied sort descriptors.
@warn_unused_result
public func order(sql sql: String) -> FetchRequest<T> {
return order([SQLLiteral(sql)])
}
/// Returns a new FetchRequest sorted in reversed order.
@warn_unused_result
public func reverse() -> FetchRequest<T> {
var query = self.query
query.reversed = !query.reversed
return FetchRequest(query)
}
/// Returns a FetchRequest which fetches *limit* rows, starting at
/// *offset*.
@warn_unused_result
public func limit(limit: Int, offset: Int? = nil) -> FetchRequest<T> {
return FetchRequest(query.limit(limit, offset: offset))
}
}
extension FetchRequest {
// MARK: Counting
/// Returns the number of rows matched by the request.
@warn_unused_result
public func fetchCount(db: Database) -> Int {
return fetchAggregate(db, _SQLExpression.Count(_SQLResultColumn.Star(nil)))!
}
/// Returns the number of non-NULL values of *counted*.
@warn_unused_result
public func fetchCount(db: Database, _ counted: _SQLSelectable) -> Int {
return fetchAggregate(db, _SQLExpression.Count(counted ?? _SQLResultColumn.Star(nil)))!
}
/// Returns the number of distinct values of *counted*.
@warn_unused_result
public func fetchCount(db: Database, distinct counted: _SQLExpressionType) -> Int {
return fetchAggregate(db, count(distinct: counted.SQLExpression))!
}
@warn_unused_result
private func fetchAggregate<T: DatabaseValueConvertible>(db: Database, _ selection: _SQLSelectable) -> T? {
return T.fetchOne(db, FetchRequest<Void>(query.select([selection])))
}
}
extension FetchRequest where T: RowConvertible {
// MARK: Fetching Record and RowConvertible
/// Returns a sequence of values.
///
/// let request = Person.order(name)
/// let persons = request.fetch(db) // DatabaseSequence<Person>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let persons = request.fetch(db)
/// Array(persons).count // 3
/// db.execute("DELETE ...")
/// Array(persons).count // 2
///
/// 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> {
return try! T.fetch(selectStatement(db))
}
/// Returns an array of values fetched from a fetch request.
///
/// let request = Person.order(name)
/// let persons = request.fetchAll(db) // DatabaseSequence<Person>
@warn_unused_result
public func fetchAll(db: Database) -> [T] {
return Array(fetch(db))
}
/// Returns a single value fetched from a fetch request.
///
/// let request = Person.order(name)
/// let persons = request.fetchOne(db) // Person?
@warn_unused_result
public func fetchOne(db: Database) -> T? {
return fetch(db).generate().next()
}
}
extension TableMapping {
// MARK: Request Derivation
/// Returns a FetchRequest which fetches all rows in the table.
@warn_unused_result
public static func all() -> FetchRequest<Self> {
return FetchRequest(tableName: databaseTableName())
}
/// Returns a FetchRequest which selects *selection*.
@warn_unused_result
public static func select(selection: _SQLSelectable...) -> FetchRequest<Self> {
return all().select(selection)
}
/// Returns a FetchRequest which selects *selection*.
@warn_unused_result
public static func select(selection: [_SQLSelectable]) -> FetchRequest<Self> {
return all().select(selection)
}
/// Returns a FetchRequest which selects *sql*.
@warn_unused_result
public static func select(sql sql: String) -> FetchRequest<Self> {
return all().select(sql: sql)
}
/// Returns a FetchRequest with the provided *predicate*.
@warn_unused_result
public static func filter(predicate: _SQLExpressionType) -> FetchRequest<Self> {
return all().filter(predicate)
}
/// Returns a FetchRequest with the provided *predicate*.
@warn_unused_result
public static func filter(sql sql: String) -> FetchRequest<Self> {
return all().filter(sql: sql)
}
/// Returns a FetchRequest sorted according to the
/// provided *sortDescriptors*.
@warn_unused_result
public static func order(sortDescriptors: _SQLSortDescriptorType...) -> FetchRequest<Self> {
return all().order(sortDescriptors)
}
/// Returns a FetchRequest sorted according to the
/// provided *sortDescriptors*.
@warn_unused_result
public static func order(sortDescriptors: [_SQLSortDescriptorType]) -> FetchRequest<Self> {
return all().order(sortDescriptors)
}
/// Returns a FetchRequest sorted according to *sql*.
@warn_unused_result
public static func order(sql sql: String) -> FetchRequest<Self> {
return all().order(sql: sql)
}
/// Returns a FetchRequest which fetches *limit* rows, starting at
/// *offset*.
@warn_unused_result
public static func limit(limit: Int, offset: Int? = nil) -> FetchRequest<Self> {
return all().limit(limit, offset: offset)
}
}
extension TableMapping {
// MARK: Counting
/// Returns the number of rows.
@warn_unused_result
public static func fetchCount(db: Database) -> Int {
return all().fetchCount(db)
}
/// Returns the number of non-NULL values of *counted*.
@warn_unused_result
public static func fetchCount(db: Database, _ counted: _SQLSelectable) -> Int {
return all().fetchCount(db, counted)
}
/// Returns the number of distinct values of *counted*.
@warn_unused_result
public static func fetchCount(db: Database, distinct counted: _SQLExpressionType) -> Int {
return all().fetchCount(db, distinct: counted)
}
}
extension DatabaseValueConvertible {
// MARK: Fetching From FetchRequest
/// Returns a sequence of values fetched from a fetch request.
///
/// let request = Person.select(name)
/// let names = String.fetch(db, request) // DatabaseSequence<String>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = String.fetch(db, request)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public static func fetch<T>(db: Database, _ request: FetchRequest<T>) -> DatabaseSequence<Self> {
return try! fetch(request.selectStatement(db))
}
/// Returns an array of values fetched from a fetch request.
///
/// let request = Person.select(name)
/// let names = String.fetchAll(db, request) // [String]
@warn_unused_result
public static func fetchAll<T>(db: Database, _ request: FetchRequest<T>) -> [Self] {
return try! fetchAll(request.selectStatement(db))
}
/// Returns a single value fetched from a fetch request.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let request = Person.select(name)
/// let name = String.fetchOne(db, request) // String?
@warn_unused_result
public static func fetchOne<T>(db: Database, _ request: FetchRequest<T>) -> Self? {
return try! fetchOne(request.selectStatement(db))
}
}
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From FetchRequest
/// Returns a sequence of optional values fetched from a fetch request.
///
/// let request = Person.select(name)
/// let names = Optional<String>.fetch(db, request) // DatabaseSequence<String?>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = Optional<String>.fetch(db, request)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public static func fetch<T>(db: Database, _ request: FetchRequest<T>) -> DatabaseSequence<Wrapped?> {
return try! fetch(request.selectStatement(db))
}
/// Returns an array of optional values fetched from a fetch request.
///
/// let request = Person.select(name)
/// let names = Optional<String>.fetchAll(db, request) // [String?]
@warn_unused_result
public static func fetchAll<T>(db: Database, _ request: FetchRequest<T>) -> [Wrapped?] {
return try! fetchAll(request.selectStatement(db))
}
}
extension DatabaseValueConvertible where Self: SQLiteStatementConvertible {
// MARK: Fetching From FetchRequest
/// Returns a sequence of values fetched from a fetch request.
///
/// let request = Person.select(name)
/// let names = String.fetch(db, request) // DatabaseSequence<String>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = String.fetch(db, request)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public static func fetch<T>(db: Database, _ request: FetchRequest<T>) -> DatabaseSequence<Self> {
return try! fetch(request.selectStatement(db))
}
/// Returns an array of values fetched from a fetch request.
///
/// let request = Person.select(name)
/// let names = String.fetchAll(db, request) // [String]
@warn_unused_result
public static func fetchAll<T>(db: Database, _ request: FetchRequest<T>) -> [Self] {
return try! fetchAll(request.selectStatement(db))
}
/// Returns a single value fetched from a fetch request.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let request = Person.select(name)
/// let name = String.fetchOne(db, request) // String?
@warn_unused_result
public static func fetchOne<T>(db: Database, _ request: FetchRequest<T>) -> Self? {
return try! fetchOne(request.selectStatement(db))
}
}
extension RowConvertible {
// MARK: Fetching From FetchRequest
/// Returns a sequence of values fetched from a fetch request.
///
/// let request = Person.order(name)
/// let persons = Person.fetch(db, request) // DatabaseSequence<Person>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let persons = Person.fetch(db, request)
/// Array(persons).count // 3
/// db.execute("DELETE ...")
/// Array(persons).count // 2
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
@warn_unused_result
public static func fetch<T>(db: Database, _ request: FetchRequest<T>) -> DatabaseSequence<Self> {
return try! fetch(request.selectStatement(db))
}
/// Returns an array of values fetched from a fetch request.
///
/// let request = Person.order(name)
/// let persons = Person.fetchAll(db, request) // DatabaseSequence<Person>
@warn_unused_result
public static func fetchAll<T>(db: Database, _ request: FetchRequest<T>) -> [Self] {
return try! fetchAll(request.selectStatement(db))
}
/// Returns a single value fetched from a fetch request.
///
/// let request = Person.order(name)
/// let persons = Person.fetchOne(db, request) // Person?
@warn_unused_result
public static func fetchOne<T>(db: Database, _ request: FetchRequest<T>) -> Self? {
return try! fetchOne(request.selectStatement(db))
}
}
extension Row {
// MARK: Fetching From FetchRequest
/// Returns a sequence of rows fetched from a fetch request.
///
/// let request = Person.select(id, name)
/// for row in Row.fetch(db, request) {
/// let id: Int64 = row.value(atIndex: 0)
/// let name: String = row.value(atIndex: 1)
/// }
///
/// Fetched rows are reused during the sequence iteration: don't wrap a row
/// sequence in an array with `Array(rows)` or `rows.filter { ... }` since
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
/// instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let rows = Row.fetch(statement)
/// for row in rows { ... } // 3 steps
/// db.execute("DELETE ...")
/// for row in rows { ... } // 2 steps
///
/// 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<T>(db: Database, _ request: FetchRequest<T>) -> DatabaseSequence<Row> {
return try! fetch(request.selectStatement(db))
}
/// Returns an array of rows fetched from a fetch request.
///
/// let statement = db.selectStatement("SELECT ...")
/// let rows = Row.fetchAll(db, request)
@warn_unused_result
public static func fetchAll<T>(db: Database, _ request: FetchRequest<T>) -> [Row] {
return try! fetchAll(request.selectStatement(db))
}
/// Returns a single row fetched from a fetch request.
///
/// let statement = db.selectStatement("SELECT ...")
/// let row = Row.fetchOne(db, request)
@warn_unused_result
public static func fetchOne<T>(db: Database, _ request: FetchRequest<T>) -> Row? {
return try! fetchOne(request.selectStatement(db))
}
}
@@ -0,0 +1,326 @@
/// 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 struct _CollatedExpression {
let baseExpression: _SQLExpression
let collationName: String
}
extension _CollatedExpression : _SQLExpressionType {
/// 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)
}
}
extension _CollatedExpression : _SQLSortDescriptorType {
/// 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)
}
/// 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: _SQLSortDescriptorType {
return _SQLSortDescriptor.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: _SQLSortDescriptorType {
return _SQLSortDescriptor.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(inout bindings: [DatabaseValueConvertible?]) throws -> String {
return try SQLExpression.orderingSQL(&bindings)
}
}
extension _DerivedSQLExpressionType {
/// 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) -> _CollatedExpression {
return _CollatedExpression(baseExpression: SQLExpression, collationName: collationName)
}
/// 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(collation: DatabaseCollation) -> _CollatedExpression {
return collating(collation.name)
}
}
// MARK: - Operator = COLLATE
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _CollatedExpression, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.Equal(
lhs.baseExpression,
rhs.SQLExpression),
lhs.collationName)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _SQLExpressionType, rhs: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.Equal(
lhs.SQLExpression,
rhs.baseExpression),
rhs.collationName)
}
// MARK: - Operator != COLLATE
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _CollatedExpression, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.NotEqual(
lhs.baseExpression,
rhs.SQLExpression),
lhs.collationName)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _SQLExpressionType, rhs: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.NotEqual(
lhs.SQLExpression,
rhs.baseExpression),
rhs.collationName)
}
// MARK: - Operator < COLLATE
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _CollatedExpression, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.InfixOperator("<",
lhs.baseExpression,
rhs.SQLExpression),
lhs.collationName)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _SQLExpressionType, rhs: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.InfixOperator("<",
lhs.SQLExpression,
rhs.baseExpression),
rhs.collationName)
}
// MARK: - Operator <= COLLATE
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _CollatedExpression, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.InfixOperator("<=",
lhs.baseExpression,
rhs.SQLExpression),
lhs.collationName)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _SQLExpressionType, rhs: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.InfixOperator("<=",
lhs.SQLExpression,
rhs.baseExpression),
rhs.collationName)
}
// MARK: - Operator > COLLATE
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _CollatedExpression, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.InfixOperator(">",
lhs.baseExpression,
rhs.SQLExpression),
lhs.collationName)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _SQLExpressionType, rhs: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.InfixOperator(">",
lhs.SQLExpression,
rhs.baseExpression),
rhs.collationName)
}
// MARK: - Operator >= COLLATE
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _CollatedExpression, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.InfixOperator(">=",
lhs.baseExpression,
rhs.SQLExpression),
lhs.collationName)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _SQLExpressionType, rhs: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.InfixOperator(">=",
lhs.SQLExpression,
rhs.baseExpression),
rhs.collationName)
}
// MARK: - Operator BETWEEN COLLATE
extension ClosedInterval where Bound: _SQLExpressionType {
/// Returns a SQL expression that compares the inclusion of a value in
/// an interval.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.Between(
value: element.baseExpression,
min: start.SQLExpression,
max: end.SQLExpression),
element.collationName)
}
}
extension HalfOpenInterval where Bound: _SQLExpressionType {
/// Returns a SQL expression that compares the inclusion of a value in
/// an interval.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("AND",
.Collate(
.InfixOperator(">=",
element.baseExpression,
start.SQLExpression),
element.collationName),
.Collate(
.InfixOperator("<",
element.baseExpression,
end.SQLExpression),
element.collationName))
}
}
// MARK: - Operator IN COLLATE
extension SequenceType where Self.Generator.Element: _SQLExpressionType {
/// Returns a 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: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.In(
map { $0.SQLExpression },
element.baseExpression),
element.collationName)
}
}
// MARK: - Operator IS COLLATE
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _CollatedExpression, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.Is(
lhs.baseExpression,
rhs.SQLExpression),
lhs.collationName)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _SQLExpressionType, rhs: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.Is(
lhs.SQLExpression,
rhs.baseExpression),
rhs.collationName)
}
// MARK: - Operator IS NOT COLLATE
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _CollatedExpression, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.IsNot(
lhs.baseExpression,
rhs.SQLExpression),
lhs.collationName)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _SQLExpressionType, rhs: _CollatedExpression) -> _DerivedSQLExpressionType {
return _SQLExpression.Collate(
.IsNot(
lhs.SQLExpression,
rhs.baseExpression),
rhs.collationName)
}
+125
View File
@@ -0,0 +1,125 @@
// MARK: - Custom Functions
extension DatabaseFunction {
/// Returns an SQL expression that applies the function.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func apply(arguments: _SQLExpressionType...) -> _DerivedSQLExpressionType {
return _SQLExpression.Function(name, arguments.map { $0.SQLExpression })
}
}
// MARK: - ABS(...)
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func abs(value: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Function("ABS", [value.SQLExpression])
}
// MARK: - AVG(...)
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func average(value: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Function("AVG", [value.SQLExpression])
}
// MARK: - COUNT(...)
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func count(counted: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Count(counted)
}
// MARK: - COUNT(DISTINCT ...)
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func count(distinct value: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.CountDistinct(value.SQLExpression)
}
// MARK: - IFNULL(...)
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func ?? (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Function("IFNULL", [lhs.SQLExpression, rhs.SQLExpression])
}
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func ?? (lhs: _SQLExpressionType?, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
if let lhs = lhs {
return _SQLExpression.Function("IFNULL", [lhs.SQLExpression, rhs.SQLExpression])
} else {
return rhs.SQLExpression
}
}
// MARK: - LOWER(...)
extension _DerivedSQLExpressionType {
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public var lowercaseString: _DerivedSQLExpressionType {
return _SQLExpression.Function("LOWER", [SQLExpression])
}
}
// MARK: - MAX(...)
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func max(value: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Function("MAX", [value.SQLExpression])
}
// MARK: - MIN(...)
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func min(value: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Function("MIN", [value.SQLExpression])
}
// MARK: - SUM(...)
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func sum(value: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Function("SUM", [value.SQLExpression])
}
// MARK: - UPPER(...)
extension _DerivedSQLExpressionType {
/// Returns an SQL expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public var uppercaseString: _DerivedSQLExpressionType {
return _SQLExpression.Function("UPPER", [SQLExpression])
}
}
+400
View File
@@ -0,0 +1,400 @@
// MARK: - Operator =
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType?) -> _DerivedSQLExpressionType {
return _SQLExpression.Equal(lhs.SQLExpression, rhs?.SQLExpression ?? .Value(nil))
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _SQLExpressionType?, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Equal(lhs?.SQLExpression ?? .Value(nil), rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func == (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Equal(lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator !=
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType?) -> _DerivedSQLExpressionType {
return _SQLExpression.NotEqual(lhs.SQLExpression, rhs?.SQLExpression ?? .Value(nil))
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _SQLExpressionType?, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.NotEqual(lhs?.SQLExpression ?? .Value(nil), rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func != (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.NotEqual(lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator <
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("<", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("<", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func < (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("<", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator <=
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("<=", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("<=", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func <= (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("<=", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator >
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator(">", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator(">", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func > (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator(">", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator >=
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator(">=", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator(">=", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func >= (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator(">=", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator *
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func * (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("*", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func * (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _SQLExpression {
return .InfixOperator("*", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func * (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _SQLExpression {
return .InfixOperator("*", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator /
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func / (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("/", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func / (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _SQLExpression {
return .InfixOperator("/", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func / (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _SQLExpression {
return .InfixOperator("/", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator +
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func + (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("+", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func + (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _SQLExpression {
return .InfixOperator("+", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func + (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _SQLExpression {
return .InfixOperator("+", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator - (prefix)
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public prefix func - (value: _DerivedSQLExpressionType) -> _SQLExpression {
return .PrefixOperator("-", value.SQLExpression)
}
// MARK: - Operator - (infix)
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func - (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _SQLExpression {
return .InfixOperator("-", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func - (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _SQLExpression {
return .InfixOperator("-", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL arithmetic expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func - (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _SQLExpression {
return .InfixOperator("-", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator AND
/// Returns a SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func && (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("AND", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func && (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("AND", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func && (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("AND", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator BETWEEN
extension Range where Element: protocol<_SQLExpressionType, BidirectionalIndexType> {
/// Returns a 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: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Between(value: element.SQLExpression, min: startIndex.SQLExpression, max: endIndex.predecessor().SQLExpression)
}
}
extension ClosedInterval where Bound: _SQLExpressionType {
/// Returns a SQL expression that compares the inclusion of a value in
/// an interval.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Between(value: element.SQLExpression, min: start.SQLExpression, max: end.SQLExpression)
}
}
extension HalfOpenInterval where Bound: _SQLExpressionType {
/// Returns a SQL expression that compares the inclusion of a value in
/// an interval.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func contains(element: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("AND", .InfixOperator(">=", element.SQLExpression, start.SQLExpression), .InfixOperator("<", element.SQLExpression, end.SQLExpression))
}
}
// MARK: - Operator IN
extension SequenceType where Self.Generator.Element: _SQLExpressionType {
/// Returns a 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: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.In(map { $0.SQLExpression }, element.SQLExpression)
}
}
// MARK: - Operator IS
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType?) -> _DerivedSQLExpressionType {
return _SQLExpression.Is(lhs.SQLExpression, rhs?.SQLExpression ?? .Value(nil))
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _SQLExpressionType?, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Is(lhs?.SQLExpression ?? .Value(nil), rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func === (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Is(lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator IS NOT
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType?) -> _DerivedSQLExpressionType {
return _SQLExpression.IsNot(lhs.SQLExpression, rhs?.SQLExpression ?? .Value(nil))
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _SQLExpressionType?, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.IsNot(lhs?.SQLExpression ?? .Value(nil), rhs.SQLExpression)
}
/// Returns a SQL expression that compares two values.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func !== (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.IsNot(lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator OR
/// Returns a SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func || (lhs: _DerivedSQLExpressionType, rhs: _SQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("OR", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func || (lhs: _SQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("OR", lhs.SQLExpression, rhs.SQLExpression)
}
/// Returns a SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public func || (lhs: _DerivedSQLExpressionType, rhs: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.InfixOperator("OR", lhs.SQLExpression, rhs.SQLExpression)
}
// MARK: - Operator NOT
/// Returns a SQL logical expression.
///
/// See https://github.com/groue/GRDB.swift/#sql-operators
public prefix func ! (value: _DerivedSQLExpressionType) -> _DerivedSQLExpressionType {
return _SQLExpression.Not(value.SQLExpression)
}
+616
View File
@@ -0,0 +1,616 @@
// MARK: - _SQLQuery
struct _SQLQuery {
var selection: [_SQLSelectable]
var distinct: Bool
var source: _SQLSource?
var whereExpression: _SQLExpression?
var groupByExpressions: [_SQLExpression]
var sortDescriptors: [_SQLSortDescriptorType]
var reversed: Bool
var havingExpression: _SQLExpression?
var limit: _SQLLimit?
init(
select selection: [_SQLSelectable],
distinct: Bool = false,
from source: _SQLSource? = nil,
filter whereExpression: _SQLExpression? = nil,
groupBy groupByExpressions: [_SQLExpression] = [],
orderBy sortDescriptors: [_SQLSortDescriptorType] = [],
reversed: Bool = false,
having havingExpression: _SQLExpression? = nil,
limit: _SQLLimit? = nil)
{
self.selection = selection
self.distinct = distinct
self.source = source
self.whereExpression = whereExpression
self.groupByExpressions = groupByExpressions
self.sortDescriptors = sortDescriptors
self.reversed = reversed
self.havingExpression = havingExpression
self.limit = limit
}
func sql(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
var sql = "SELECT"
if distinct {
sql += " DISTINCT"
}
sql += try " " + selection.map { try $0.resultColumnSQL(&bindings) }.joinWithSeparator(", ")
if let source = source {
sql += try " FROM " + source.sql(db, &bindings)
}
if let whereExpression = whereExpression {
sql += try " WHERE " + whereExpression.sql(&bindings)
}
if !groupByExpressions.isEmpty {
sql += try " GROUP BY " + groupByExpressions.map { try $0.sql(&bindings) }.joinWithSeparator(", ")
}
if let havingExpression = havingExpression {
sql += try " HAVING " + havingExpression.sql(&bindings)
}
var sortDescriptors = self.sortDescriptors
if reversed {
if sortDescriptors.isEmpty {
guard let source = source, case .Table(let tableName, let alias) = source else {
throw DatabaseError(message: "can't reverse without a source table")
}
guard case let columns = try db.primaryKey(tableName).columns where !columns.isEmpty else {
throw DatabaseError(message: "can't reverse a table without primary key")
}
sortDescriptors = columns.map { _SQLSortDescriptor.Desc(_SQLExpression.Identifier(identifier: $0, sourceName: alias)) }
} else {
sortDescriptors = sortDescriptors.map { $0.reversedSortDescriptor }
}
}
if !sortDescriptors.isEmpty {
sql += try " ORDER BY " + sortDescriptors.map { try $0.orderingSQL(&bindings) }.joinWithSeparator(", ")
}
if let limit = limit {
sql += " LIMIT " + limit.sql
}
return sql
}
}
// MARK: - _SQLQuery derivation
extension _SQLQuery {
@warn_unused_result
func select(selection: [_SQLSelectable]) -> _SQLQuery {
var query = self
query.selection = selection
return query
}
@warn_unused_result
func filter(predicate: _SQLExpression) -> _SQLQuery {
var query = self
if let whereExpression = query.whereExpression {
query.whereExpression = .InfixOperator("AND", whereExpression, predicate)
} else {
query.whereExpression = predicate
}
return query
}
@warn_unused_result
func group(expressions: [_SQLExpression]) -> _SQLQuery {
var query = self
query.groupByExpressions = expressions
return query
}
@warn_unused_result
func having(predicate: _SQLExpression) -> _SQLQuery {
var query = self
if let havingExpression = query.havingExpression {
query.havingExpression = .InfixOperator("AND", havingExpression, predicate)
} else {
query.havingExpression = predicate
}
return query
}
@warn_unused_result
func order(sortDescriptors: [_SQLSortDescriptorType]) -> _SQLQuery {
var query = self
query.sortDescriptors.appendContentsOf(sortDescriptors)
return query
}
@warn_unused_result
func limit(limit: Int, offset: Int?) -> _SQLQuery {
var query = self
query.limit = _SQLLimit(limit: limit, offset: offset)
return query
}
}
// MARK: - _SQLSource
indirect enum _SQLSource {
case Table(name: String, alias: String?)
case Query(_SQLQuery, alias: String)
case Join(_SQLSource, _SQLExpression, _SQLSource)
// a JOIN b ON ab JOIN c ON abc
// ((a,b,ab), c, abc)
func sql(db: Database, inout _ bindings: [DatabaseValueConvertible?]) throws -> String {
switch self {
case .Table(let table, let alias):
if let alias = alias {
return table.quotedDatabaseIdentifier + " AS " + alias.quotedDatabaseIdentifier
} else {
return table.quotedDatabaseIdentifier
}
case .Query(let query, let alias):
return try "(" + query.sql(db, &bindings) + ") AS " + alias.quotedDatabaseIdentifier
case .Join(let first, let expression, let second):
switch second {
case .Join:
fatalError("WTF")
default:
break
}
return try first.sql(db, &bindings) + " JOIN " + second.sql(db, &bindings) + " ON " + expression.sql(&bindings)
}
}
}
// MARK: - _SQLSortDescriptorType
/// 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(inout bindings: [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)
}
extension _SQLSortDescriptor : _SQLSortDescriptorType {
/// 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 {
switch self {
case .Asc(let expression):
return .Desc(expression)
case .Desc(let expression):
return .Asc(expression)
}
}
/// 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(inout bindings: [DatabaseValueConvertible?]) throws -> String {
switch self {
case .Asc(let expression):
return try expression.sql(&bindings) + " ASC"
case .Desc(let expression):
return try expression.sql(&bindings) + " DESC"
}
}
}
// MARK: - _SQLLimit
struct _SQLLimit {
let limit: Int
let offset: Int?
var sql: String {
if let offset = offset {
return "\(limit) OFFSET \(offset)"
} else {
return "\(limit)"
}
}
}
// MARK: - _SQLExpressionType
public protocol _SQLExpressionType {
/// 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
var SQLExpression: _SQLExpression { get }
}
// Conformance to _SQLExpressionType
extension DatabaseValueConvertible {
/// 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 .Value(self)
}
}
/// 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 _DerivedSQLExpressionType : _SQLExpressionType, _SQLSortDescriptorType, _SQLSelectable {
}
// Conformance to _SQLSortDescriptorType
extension _DerivedSQLExpressionType {
/// 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)
}
/// 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(inout bindings: [DatabaseValueConvertible?]) throws -> String {
return try SQLExpression.sql(&bindings)
}
}
// Conformance to _SQLSelectable
extension _DerivedSQLExpressionType {
/// 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(inout bindings: [DatabaseValueConvertible?]) throws -> String {
return try SQLExpression.sql(&bindings)
}
/// 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 countedSQL(inout bindings: [DatabaseValueConvertible?]) throws -> String {
return try SQLExpression.sql(&bindings)
}
}
extension _DerivedSQLExpressionType {
/// 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: _SQLSortDescriptorType {
return _SQLSortDescriptor.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: _SQLSortDescriptorType {
return _SQLSortDescriptor.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(SQLExpression, alias)
}
}
/// 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 indirect enum _SQLExpression {
/// For example: `name || 'rrr' AS pirateName`
case Literal(String)
/// For example: `1` or `'foo'`
case Value(DatabaseValueConvertible?)
/// For example: `name`, `table.name`
case Identifier(identifier: String, sourceName: String?)
/// For example: `name = 'foo' COLLATE NOCASE`
case Collate(_SQLExpression, String)
/// For example: `NOT condition`
case Not(_SQLExpression)
/// For example: `name = 'foo'`
case Equal(_SQLExpression, _SQLExpression)
/// For example: `name <> 'foo'`
case NotEqual(_SQLExpression, _SQLExpression)
/// For example: `name IS NULL`
case Is(_SQLExpression, _SQLExpression)
/// For example: `name IS NOT NULL`
case IsNot(_SQLExpression, _SQLExpression)
/// For example: `-value`
case PrefixOperator(String, _SQLExpression)
/// For example: `age + 1`
case InfixOperator(String, _SQLExpression, _SQLExpression)
/// For example: `id IN (1,2,3)`
case In([_SQLExpression], _SQLExpression)
/// For example: `age BETWEEN 1 AND 2`
case Between(value: _SQLExpression, min: _SQLExpression, max: _SQLExpression)
/// For example: `LOWER(name)`
case Function(String, [_SQLExpression])
/// For example: `COUNT(*)`
case Count(_SQLSelectable)
/// For example: `COUNT(DISTINCT name)`
case CountDistinct(_SQLExpression)
///
func sql(inout bindings: [DatabaseValueConvertible?]) throws -> String {
switch self {
case .Literal(let sql):
return sql
case .Value(let value):
guard let value = value else {
return "NULL"
}
bindings.append(value)
return "?"
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):
let sql = try expression.sql(&bindings)
let chars = sql.characters
if chars.last! == ")" {
return String(chars.prefixUpTo(chars.endIndex.predecessor())) + " COLLATE " + collation + ")"
} else {
return sql + " COLLATE " + collation
}
case .Not(let condition):
switch condition {
case .Not(let expression):
return try expression.sql(&bindings)
case .In(let expressions, let expression):
if expressions.isEmpty {
return "1"
} else {
return try "(" + expression.sql(&bindings) + " NOT IN (" + expressions.map { try $0.sql(&bindings) }.joinWithSeparator(", ") + "))"
}
case .Equal(let lhs, let rhs):
return try _SQLExpression.NotEqual(lhs, rhs).sql(&bindings)
case .NotEqual(let lhs, let rhs):
return try _SQLExpression.Equal(lhs, rhs).sql(&bindings)
case .Is(let lhs, let rhs):
return try _SQLExpression.IsNot(lhs, rhs).sql(&bindings)
case .IsNot(let lhs, let rhs):
return try _SQLExpression.Is(lhs, rhs).sql(&bindings)
default:
return try "(NOT " + condition.sql(&bindings) + ")"
}
case .Equal(let lhs, let rhs):
switch (lhs, rhs) {
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(&bindings) + " IS NULL)"
case (.Value(let lhs), let rhs) where lhs == nil:
// Swiftism!
return try "(" + rhs.sql(&bindings) + " IS NULL)"
default:
return try "(" + lhs.sql(&bindings) + " = " + rhs.sql(&bindings) + ")"
}
case .NotEqual(let lhs, let rhs):
switch (lhs, rhs) {
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(&bindings) + " IS NOT NULL)"
case (.Value(let lhs), let rhs) where lhs == nil:
// Swiftism!
return try "(" + rhs.sql(&bindings) + " IS NOT NULL)"
default:
return try "(" + lhs.sql(&bindings) + " <> " + rhs.sql(&bindings) + ")"
}
case .Is(let lhs, let rhs):
switch (lhs, rhs) {
case (let lhs, .Value(let rhs)) where rhs == nil:
return try "(" + lhs.sql(&bindings) + " IS NULL)"
case (.Value(let lhs), let rhs) where lhs == nil:
return try "(" + rhs.sql(&bindings) + " IS NULL)"
default:
return try "(" + lhs.sql(&bindings) + " IS " + rhs.sql(&bindings) + ")"
}
case .IsNot(let lhs, let rhs):
switch (lhs, rhs) {
case (let lhs, .Value(let rhs)) where rhs == nil:
return try "(" + lhs.sql(&bindings) + " IS NOT NULL)"
case (.Value(let lhs), let rhs) where lhs == nil:
return try "(" + rhs.sql(&bindings) + " IS NOT NULL)"
default:
return try "(" + lhs.sql(&bindings) + " IS NOT " + rhs.sql(&bindings) + ")"
}
case .PrefixOperator(let SQLOperator, let value):
return try SQLOperator + value.sql(&bindings)
case .InfixOperator(let SQLOperator, let lhs, let rhs):
return try "(" + lhs.sql(&bindings) + " \(SQLOperator) " + rhs.sql(&bindings) + ")"
case .In(let expressions, let expression):
guard !expressions.isEmpty else {
return "0"
}
return try "(" + expression.sql(&bindings) + " IN (" + expressions.map { try $0.sql(&bindings) }.joinWithSeparator(", ") + "))"
case .Between(value: let value, min: let min, max: let max):
return try "(" + value.sql(&bindings) + " BETWEEN " + min.sql(&bindings) + " AND " + max.sql(&bindings) + ")"
case .Function(let functionName, let functionArguments):
return try functionName + "(" + functionArguments.map { try $0.sql(&bindings) }.joinWithSeparator(", ") + ")"
case .Count(let counted):
return try "COUNT(" + counted.countedSQL(&bindings) + ")"
case .CountDistinct(let expression):
return try "COUNT(DISTINCT " + expression.sql(&bindings) + ")"
}
}
}
extension _SQLExpression : _DerivedSQLExpressionType {
/// 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 self
}
}
// MARK: - _SQLSelectable
/// 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 _SQLSelectable {
func resultColumnSQL(inout bindings: [DatabaseValueConvertible?]) throws -> String
func countedSQL(inout bindings: [DatabaseValueConvertible?]) throws -> String
}
enum _SQLResultColumn {
case Star(String?)
case Expression(_SQLExpression, String)
}
extension _SQLResultColumn : _SQLSelectable {
func resultColumnSQL(inout bindings: [DatabaseValueConvertible?]) throws -> String {
switch self {
case .Star(let sourceName):
if let sourceName = sourceName {
return sourceName.quotedDatabaseIdentifier + ".*"
} else {
return "*"
}
case .Expression(let expression, let identifier):
return try expression.sql(&bindings) + " AS " + identifier.quotedDatabaseIdentifier
}
}
func countedSQL(inout bindings: [DatabaseValueConvertible?]) throws -> String {
switch self {
case .Star:
return "*"
case .Expression(let expression, _):
return try expression.sql(&bindings)
}
}
}
// MARK: SQLLiteral
struct SQLLiteral {
let sql: String
init(_ sql: String) {
self.sql = sql
}
}
extension SQLLiteral : _DerivedSQLExpressionType {
var SQLExpression: _SQLExpression {
return .Literal(sql)
}
}
// MARK: - SQLColumn
/// A column in the database
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct SQLColumn {
let name: String
let sourceName: String?
/// Initializes a column given its name.
public init(_ name: String) {
self.name = name
self.sourceName = nil
}
init(_ name: String, sourceName: String?) {
self.name = name
self.sourceName = sourceName
}
}
extension SQLColumn : _DerivedSQLExpressionType {
/// 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)
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
/// Record is a class that wraps a table row, or the result of any query. It is
/// designed to be subclassed.
public class Record : RowConvertible, DatabaseTableMapping, DatabasePersistable {
public class Record : RowConvertible, TableMapping, Persistable {
// MARK: - Initializers
+17 -4
View File
@@ -3,10 +3,14 @@
import GRDB
// ==============================================
// SETUP
// Create the databsae
var configuration = Configuration()
configuration.trace = { print($0) }
configuration.trace = { print($0) } // Log all SQL statements
let dbQueue = DatabaseQueue(configuration: configuration) // Memory database
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
@@ -37,6 +41,7 @@ class Person : Record {
super.init()
}
// Record overrides
override class func databaseTableName() -> String {
@@ -60,7 +65,16 @@ class Person : Record {
}
// Insert and fetch persons from the database
// Define colums
struct Col {
static let firstName = SQLColumn("firstName")
static let lastName = SQLColumn("lastName")
}
// END OF SETUP
// ==============================================
try! dbQueue.inTransaction { db in
try Person(firstName: "Arthur", lastName: "Miller").insert(db)
@@ -70,8 +84,7 @@ try! dbQueue.inTransaction { db in
}
let persons = dbQueue.inDatabase { db in
Person.fetchAll(db, "SELECT * FROM persons ORDER BY firstName, lastName")
Person.order(Col.firstName, Col.lastName).fetchAll(db)
}
print(persons)
print(persons.map { $0.fullName })
+992 -981
View File
File diff suppressed because it is too large. Load diff
+18 -1
View File
@@ -1,5 +1,22 @@
- [ ] How to have robust single writer/several readers?
- [ ] protocol DatabaseEquatable, with default implementation for MutableDatabasePersistable
- [ ] protocol DatabaseEquatable, with default implementation for MutablePersistable
- [ ] Query builder
- [ ] Minimal inline documentation
- [ ] Check for gross pollution (`1.SQLexpression`)
- [X] Remove typed expressions
- [ ] SELECT readers.*, books.* FROM ... JOIN ...
- [ ] date functions
- [ ] Document custom functions
- [ ] RANDOM() https://www.sqlite.org/lang_corefunc.html
- [ ] LIKE https://www.sqlite.org/lang_expr.html
- [ ] GLOB https://www.sqlite.org/lang_expr.html
- [ ] MATCH https://www.sqlite.org/lang_expr.html
- [ ] REGEXP https://www.sqlite.org/lang_expr.html
- [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html
- [ ] EXISTS https://www.sqlite.org/lang_expr.html
Not sure: