From a4a8b5c93bad5f3c023cf4f534f4d6cc1f9c6291 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 20 Jan 2016 18:08:21 +0100 Subject: [PATCH 01/26] Cleanup --- GRDB/Core/Database.swift | 24 +++--------- GRDB/Core/Protocols/DatabasePersistable.swift | 39 +++++++++---------- .../Core/Protocols/DatabaseTableMapping.swift | 34 ++++++++-------- GRDB/Core/Utils.swift | 27 ++++++++++++- GRDB/Migrations/DatabaseMigrator.swift | 14 +++---- 5 files changed, 71 insertions(+), 67 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 9a44e2a80..9ec4d0dd0 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -26,7 +26,6 @@ public final class Database { private var functions = Set() private var collations = Set() - private var columnInfosCache: [String: [ColumnInfo]] = [:] private var primaryKeyCache: [String: PrimaryKey] = [:] private var updateStatementCache: [String: UpdateStatement] = [:] private var selectStatementCache: [String: SelectStatement] = [:] @@ -560,7 +559,6 @@ extension Database { /// outside of a database migration performed by DatabaseMigrator. public func clearSchemaCache() { preconditionValidQueue() - columnInfosCache = [:] primaryKeyCache = [:] updateStatementCache = [:] selectStatementCache = [:] @@ -575,10 +573,10 @@ extension Database { } /// Return the primary key for table named `tableName`. - /// Crashes if table does not exist. + /// Throws if table does not exist. /// /// This method is not thread-safe. - func primaryKey(tableName: String) -> PrimaryKey { + func primaryKey(tableName: String) throws -> PrimaryKey { if let primaryKey = primaryKeyCache[tableName] { return primaryKey } @@ -607,9 +605,9 @@ extension Database { // 1 | firstName | TEXT | 0 | NULL | 0 | // 2 | lastName | TEXT | 0 | NULL | 0 | - let columnInfos = self.columnInfos(tableName) + let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") guard columnInfos.count > 0 else { - fatalError("no such table: \(tableName)") + throw DatabaseError(message: "no such table: \(tableName)") } let primaryKey: PrimaryKey @@ -686,16 +684,6 @@ extension Database { primaryKeyIndex:row.value(named: "pk")) } } - - private func columnInfos(tableName: String) -> [ColumnInfo] { - if let columnInfos = columnInfosCache[tableName] { - return columnInfos - } - - let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") - columnInfosCache[tableName] = columnInfos - return columnInfos - } } /// A primary key @@ -846,9 +834,7 @@ extension Database { public func removeTransactionObserver(transactionObserver: TransactionObserverType) { preconditionValidQueue() - if let index = transactionObservers.indexOf({ $0 === transactionObserver}) { - transactionObservers.removeAtIndex(index) - } + transactionObservers.removeFirst { $0 === transactionObserver } if transactionObservers.isEmpty { uninstallTransactionObserverHooks() } diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/DatabasePersistable.swift index d4e6e01ea..773cdf63e 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/DatabasePersistable.swift @@ -212,7 +212,7 @@ public extension MutableDatabasePersistable { private func canUpdateInDatabase(db: Database) -> Bool { // Fail early if database table does not exist. let databaseTableName = self.dynamicType.databaseTableName() - let primaryKey = db.primaryKey(databaseTableName) + let primaryKey = try! db.primaryKey(databaseTableName) let persistentDictionary = self.persistentDictionary for column in primaryKey.columns where !databaseValue(forColumn: column, inDictionary: persistentDictionary).isNull { @@ -463,7 +463,7 @@ final class DataMapper { init(_ db: Database, _ persistable: MutableDatabasePersistable) { // Fail early if database table does not exist. let databaseTableName = persistable.dynamicType.databaseTableName() - let primaryKey = db.primaryKey(databaseTableName) + let primaryKey = try! db.primaryKey(databaseTableName) // Fail early if persistentDictionary is empty let persistentDictionary = persistable.persistentDictionary @@ -477,11 +477,10 @@ final class DataMapper { } func insertStatement() -> UpdateStatement { - let sql = InsertQuery( + let query = InsertQuery( tableName: databaseTableName, insertedColumns: Array(persistentDictionary.keys)) - .sql - let statement = try! db.cachedUpdateStatement(sql) + let statement = try! db.cachedUpdateStatement(query.sql) statement.unsafeSetArguments(StatementArguments(persistentDictionary.values)) return statement } @@ -490,9 +489,10 @@ final class DataMapper { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary) - precondition(primaryKeyValues.indexOf({ !$0.isNull }) != nil, "invalid primary key in \(persistable)") + precondition(primaryKeyValues.contains { !$0.isNull }, "invalid primary key in \(persistable)") - var updatedColumns = Array(persistentDictionary.keys.filter { !primaryKeyColumns.contains($0) }) + // Update everything but primary key + var updatedColumns = persistentDictionary.keys.removingElementsOf(primaryKeyColumns) if updatedColumns.isEmpty { // IMPLEMENTATION NOTE // @@ -506,12 +506,11 @@ final class DataMapper { } let updatedValues = databaseValues(forColumns: updatedColumns, inDictionary: persistentDictionary) - let sql = UpdateQuery( + let query = UpdateQuery( tableName: databaseTableName, updatedColumns: updatedColumns, conditionColumns: primaryKeyColumns) - .sql - let statement = try! db.cachedUpdateStatement(sql) + let statement = try! db.cachedUpdateStatement(query.sql) statement.unsafeSetArguments(StatementArguments(updatedValues + primaryKeyValues)) return statement } @@ -520,13 +519,12 @@ final class DataMapper { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary) - precondition(primaryKeyValues.indexOf({ !$0.isNull }) != nil, "invalid primary key in \(persistable)") + precondition(primaryKeyValues.contains { !$0.isNull }, "invalid primary key in \(persistable)") - let sql = DeleteQuery( + let query = DeleteQuery( tableName: databaseTableName, conditionColumns: primaryKeyColumns) - .sql - let statement = try! db.cachedUpdateStatement(sql) + let statement = try! db.cachedUpdateStatement(query.sql) statement.unsafeSetArguments(StatementArguments(primaryKeyValues)) return statement } @@ -535,13 +533,12 @@ final class DataMapper { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary) - precondition(primaryKeyValues.indexOf({ !$0.isNull }) != nil, "invalid primary key in \(persistable)") + precondition(primaryKeyValues.contains { !$0.isNull }, "invalid primary key in \(persistable)") - let sql = ExistsQuery( + let query = ExistsQuery( tableName: databaseTableName, conditionColumns: primaryKeyColumns) - .sql - let statement = try! db.cachedSelectStatement(sql) + let statement = try! db.cachedSelectStatement(query.sql) statement.unsafeSetArguments(StatementArguments(primaryKeyValues)) return statement } @@ -570,9 +567,9 @@ extension InsertQuery { if let sql = InsertQuery.sqlCache[self] { return sql } - let columnSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joinWithSeparator(",") - let valuesSQL = Array(count: insertedColumns.count, repeatedValue: "?").joinWithSeparator(",") - let sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnSQL)) VALUES (\(valuesSQL))" + let columnsSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joinWithSeparator(",") + let valuesSQL = databaseQuestionMarks(count: insertedColumns.count) + let sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" InsertQuery.sqlCache[self] = sql return sql } diff --git a/GRDB/Core/Protocols/DatabaseTableMapping.swift b/GRDB/Core/Protocols/DatabaseTableMapping.swift index 8ab55ec17..54c308ec0 100644 --- a/GRDB/Core/Protocols/DatabaseTableMapping.swift +++ b/GRDB/Core/Protocols/DatabaseTableMapping.swift @@ -27,7 +27,7 @@ extension RowConvertible where Self: DatabaseTableMapping { /// - parameter keys: An array of primary keys. /// - returns: A sequence. public static func fetch(db: Database, keys: Sequence) -> DatabaseSequence { - guard let statement = fetchByPrimaryKeyStatement(db, keys: keys) else { + guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else { return DatabaseSequence.emptySequence(db) } return fetch(statement) @@ -43,7 +43,7 @@ extension RowConvertible where Self: DatabaseTableMapping { /// - parameter keys: An array of primary keys. /// - returns: An array. public static func fetchAll(db: Database, keys: Sequence) -> [Self] { - guard let statement = fetchByPrimaryKeyStatement(db, keys: keys) else { + guard let statement = fetchByPrimaryKeyStatement(db, values: keys) else { return [] } return fetchAll(statement) @@ -60,39 +60,39 @@ extension RowConvertible where Self: DatabaseTableMapping { guard let key = key else { return nil } - return fetchOne(fetchByPrimaryKeyStatement(db, keys: [key])!) + return fetchOne(fetchByPrimaryKeyStatement(db, values: [key])!) } // Returns "SELECT * FROM table WHERE id IN (?,?,?)" // - // Returns nil if keys is empty. - private static func fetchByPrimaryKeyStatement(db: Database, keys: Sequence) -> SelectStatement? { + // Returns nil if values is empty. + private static func fetchByPrimaryKeyStatement(db: Database, values: Sequence) -> SelectStatement? { // Fail early if database table does not exist. let databaseTableName = self.databaseTableName() - let primaryKey = db.primaryKey(databaseTableName) + let primaryKey = try! db.primaryKey(databaseTableName) // Fail early if database table has not one column in its primary key let columns = primaryKey.columns precondition(columns.count == 1, "expected single column primary key in table: \(databaseTableName)") + let column = columns.first! - let keys = keys.map { $0 as DatabaseValueConvertible? } - - switch keys.count { + let values = Array(values) + switch values.count { case 0: // Avoid performing useless SELECT return nil case 1: - // Use '=' in SQL query - let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(columns.first!.quotedDatabaseIdentifier) = ?" + // SELECT * FROM table WHERE id = ? + let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?" let statement = try! db.selectStatement(sql) - statement.arguments = StatementArguments(keys) + statement.arguments = StatementArguments(values) return statement - default: - // Use 'IN' - let questionMarks = Array(count: keys.count, repeatedValue: "?").joinWithSeparator(",") - let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(columns.first!.quotedDatabaseIdentifier) IN (\(questionMarks))" + case let count: + // SELECT * FROM table WHERE id IN (?,?,?) + let valuesSQL = databaseQuestionMarks(count: count) + let sql = "SELECT * FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(valuesSQL))" let statement = try! db.selectStatement(sql) - statement.arguments = StatementArguments(keys) + statement.arguments = StatementArguments(values) return statement } } diff --git a/GRDB/Core/Utils.swift b/GRDB/Core/Utils.swift index 4393c153a..89e55f592 100644 --- a/GRDB/Core/Utils.swift +++ b/GRDB/Core/Utils.swift @@ -14,6 +14,13 @@ extension String { } } +/// Return as many question marks separated with commas as the *count* argument. +/// +/// databaseQuestionMarks(count: 3) // "?,?,?" +public func databaseQuestionMarks(count count: Int) -> String { + return Array(count: count, repeatedValue: "?").joinWithSeparator(",") +} + // MARK: - Internal @@ -38,10 +45,18 @@ func dispatchSync(queue: dispatch_queue_t, block: () throws -> T) rethrows -> return try dispatchSyncImpl(queue, block: block, block2: { throw $0 }) } +extension Array { + /// Removesthe first object that matches *predicate*. + mutating func removeFirst(@noescape predicate: (Element) throws -> Bool) rethrows { + if let index = try indexOf(predicate) { + removeAtIndex(index) + } + } +} extension Dictionary { - /// Creates a dictionary with the keys and values in the given sequence. + /// Create a dictionary with the keys and values in the given sequence. init(_ sequence: Sequence) { self.init(minimumCapacity: sequence.underestimateCount()) for (key, value) in sequence { @@ -49,7 +64,7 @@ extension Dictionary { } } - /// Creates a dictionary from keys and a value builder. + /// Create a dictionary from keys and a value builder. init(keys: Sequence, value: Key -> Value) { self.init(minimumCapacity: keys.underestimateCount()) for key in keys { @@ -57,3 +72,11 @@ extension Dictionary { } } } + +extension SequenceType where Generator.Element: Equatable { + + /// Filter out elements contained in *removedElements*. + func removingElementsOf(removedElements: S) -> [Self.Generator.Element] { + return filter { element in !removedElements.contains(element) } + } +} diff --git a/GRDB/Migrations/DatabaseMigrator.swift b/GRDB/Migrations/DatabaseMigrator.swift index f9b6d7f9b..dd41567bd 100644 --- a/GRDB/Migrations/DatabaseMigrator.swift +++ b/GRDB/Migrations/DatabaseMigrator.swift @@ -92,7 +92,7 @@ public struct DatabaseMigrator { private var migrations: [Migration] = [] private mutating func registerMigration(migration: Migration) { - precondition(migrations.map({ $0.identifier }).contains(migration.identifier) == false, "already registered migration: \"\(migration.identifier)\"") + precondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \"\(migration.identifier)\"") migrations.append(migration) } @@ -101,12 +101,10 @@ public struct DatabaseMigrator { } private func runMigrations(db: Database) throws { - let appliedMigrationIdentifiers = String.fetchAll(db, "SELECT identifier FROM grdb_migrations") - try migrations - .filter { !appliedMigrationIdentifiers.contains($0.identifier) } - .forEach { - try $0.run(db) - db.clearSchemaCache() - } + let appliedIdentifiers = String.fetchAll(db, "SELECT identifier FROM grdb_migrations") + for migration in migrations where !appliedIdentifiers.contains(migration.identifier) { + try migration.run(db) + db.clearSchemaCache() + } } } \ No newline at end of file From 7c9d379aba04c130245c9c70a66208541e915962 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 20 Jan 2016 18:13:47 +0100 Subject: [PATCH 02/26] Cleanup --- GRDB/Core/Database.swift | 2 +- GRDB/Core/Statement.swift | 13 ++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 9ec4d0dd0..322db1548 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -50,7 +50,7 @@ public final class Database { var sqliteConnection = SQLiteConnection() let code = sqlite3_open_v2(path, &sqliteConnection, configuration.sqliteOpenFlags, nil) self.sqliteConnection = sqliteConnection - if code != SQLITE_OK { + guard code == SQLITE_OK else { throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index f80df71e8..4348fb25e 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -59,7 +59,7 @@ public class Statement { final func reset() throws { let code = sqlite3_reset(sqliteStatement) - if code != SQLITE_OK { + guard code == SQLITE_OK else { throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql) } } @@ -149,7 +149,7 @@ public class Statement { code = sqlite3_bind_blob(sqliteStatement, index, data.bytes, Int32(data.length), SQLITE_TRANSIENT) } - if code != SQLITE_OK { + guard code == SQLITE_OK else { throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql) } } @@ -235,7 +235,7 @@ public class Statement { // Don't make this one public unless we keep the arguments property in sync. private func clearBindings() throws { let code = sqlite3_clear_bindings(sqliteStatement) - if code != SQLITE_OK { + guard code == SQLITE_OK else { throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql) } } @@ -317,14 +317,13 @@ public struct DatabaseSequence: SequenceType { // Check that generator is used on a valid queue. preconditionValidQueue() - let code = sqlite3_step(sqliteStatement) - switch code { + switch sqlite3_step(sqliteStatement) { case SQLITE_DONE: return nil case SQLITE_ROW: return element() - default: - throw DatabaseError(code: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments) + case let errorCode: + throw DatabaseError(code: errorCode, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments) } } } From 3b3cb6bdecdfaac6e3d55bb7ecccf22f2749140f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 20 Jan 2016 19:49:58 +0100 Subject: [PATCH 03/26] 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 --- .../GRDBDemoiOS.xcodeproj/project.pbxproj | 34 + .../GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift | 36 +- .../GRDBDemoiOS/GRDBDemoiOS/Database.swift | 63 + .../GRDBDemoiOS/MasterViewController.swift | 2 +- DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift | 2 +- .../GRDBDemoiOS7.xcodeproj/project.pbxproj | 326 +-- .../GRDBDemoiOS7/AppDatabase.swift | 64 + .../GRDBDemoiOS7/AppDelegate.swift | 32 +- .../GRDBDemoiOS7/GRDBDemoiOS7/Person.swift | 2 +- .../GRDBDemoiOS7/PersonsViewController.swift | 7 +- GRDB Tests/GRDBTestCase.swift | 9 + .../Core/Concurrency/ConcurrencyTests.swift | 2 +- .../MutablePersistableTests.swift} | 8 +- .../PersistableTests.swift} | 10 +- .../FetchRequest/FetchRequestTests.swift | 361 +++ .../Record+FetchRequestTests.swift | 95 + .../RowConvertible+FetchRequestTests.swift | 140 ++ .../Public/FetchRequest/SQLSupportTests.swift | 752 +++++++ .../TableMapping+FetchRequestTests.swift | 191 ++ GRDB.xcodeproj/project.pbxproj | 140 +- GRDB/Core/Configuration.swift | 2 +- GRDB/Core/Database.swift | 2 +- .../Protocols/DatabaseValueConvertible.swift | 24 +- ...asePersistable.swift => Persistable.swift} | 71 +- GRDB/Core/Protocols/RowConvertible.swift | 8 +- .../SQLiteStatementConvertible.swift | 12 + ...eTableMapping.swift => TableMapping.swift} | 20 +- GRDB/Core/Row.swift | 24 +- GRDB/Core/Statement.swift | 32 +- GRDB/FetchRequest/FetchRequest.swift | 539 +++++ GRDB/FetchRequest/SQLSupport/Collation.swift | 326 +++ GRDB/FetchRequest/SQLSupport/Function.swift | 125 ++ GRDB/FetchRequest/SQLSupport/Operator.swift | 400 ++++ GRDB/FetchRequest/SQLSupport/SQLQuery.swift | 616 +++++ GRDB/Record/Record.swift | 2 +- Playgrounds/Record.playground/Contents.swift | 21 +- README.md | 1973 +++++++++-------- TODO.md | 19 +- 38 files changed, 5193 insertions(+), 1299 deletions(-) create mode 100644 DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift create mode 100644 DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/AppDatabase.swift rename GRDB Tests/Public/Core/{DatabasePersistable/MutableDatabasePersistableTests.swift => Persistable/MutablePersistableTests.swift} (98%) rename GRDB Tests/Public/Core/{DatabasePersistable/DatabasePersistableTests.swift => Persistable/PersistableTests.swift} (98%) create mode 100644 GRDB Tests/Public/FetchRequest/FetchRequestTests.swift create mode 100644 GRDB Tests/Public/FetchRequest/Record+FetchRequestTests.swift create mode 100644 GRDB Tests/Public/FetchRequest/RowConvertible+FetchRequestTests.swift create mode 100644 GRDB Tests/Public/FetchRequest/SQLSupportTests.swift create mode 100644 GRDB Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift rename GRDB/Core/Protocols/{DatabasePersistable.swift => Persistable.swift} (91%) rename GRDB/Core/Protocols/{DatabaseTableMapping.swift => TableMapping.swift} (92%) create mode 100644 GRDB/FetchRequest/FetchRequest.swift create mode 100644 GRDB/FetchRequest/SQLSupport/Collation.swift create mode 100644 GRDB/FetchRequest/SQLSupport/Function.swift create mode 100644 GRDB/FetchRequest/SQLSupport/Operator.swift create mode 100644 GRDB/FetchRequest/SQLSupport/SQLQuery.swift diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index 24527ab46..2bf6ceb3d 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -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 = ""; }; 56900E411BBFF7D500B815B5 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = ""; }; 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 = ""; }; @@ -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 */, diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index 04663e6b8..02fa87682 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -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 } } - diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift new file mode 100644 index 000000000..dd12a9ce7 --- /dev/null +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift @@ -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) +} \ No newline at end of file diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/MasterViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/MasterViewController.swift index d9e5e8cf3..7e7ceced5 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/MasterViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/MasterViewController.swift @@ -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) } } diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift index 9433e96e5..170155921 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift @@ -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) { diff --git a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7.xcodeproj/project.pbxproj b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7.xcodeproj/project.pbxproj index 8643d4917..b5c384c7a 100644 --- a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7.xcodeproj/project.pbxproj +++ b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7.xcodeproj/project.pbxproj @@ -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 = ""; }; 562FF9F11BCE914E00759400 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = ""; }; 562FF9F41BCE930C00759400 /* GRDBDemoiOS7-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBDemoiOS7-Bridging-Header.h"; sourceTree = ""; }; - 563445071C4A8060003D3DC6 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; - 56FCB3421C21210B00305D10 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = ""; }; - 56FCB3431C21210B00305D10 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = ""; }; - 56FCB3451C21210B00305D10 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = ""; }; - 56FCB3461C21210B00305D10 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = ""; }; - 56FCB3471C21210B00305D10 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = ""; }; - 56FCB3491C21210B00305D10 /* DatabasePersistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistable.swift; sourceTree = ""; }; - 56FCB34A1C21210B00305D10 /* DatabaseTableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTableMapping.swift; sourceTree = ""; }; - 56FCB34B1C21210B00305D10 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; - 56FCB34C1C21210B00305D10 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; - 56FCB34D1C21210B00305D10 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = ""; }; - 56FCB34E1C21210B00305D10 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = ""; }; - 56FCB3501C21210B00305D10 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = ""; }; - 56FCB3541C21210B00305D10 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = ""; }; - 56FCB3561C21210B00305D10 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = ""; }; - 56FCB3571C21210B00305D10 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = ""; }; - 56FCB3581C21210B00305D10 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = ""; }; - 56FCB3591C21210B00305D10 /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; - 56FCB35A1C21210B00305D10 /* NSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDate.swift; sourceTree = ""; }; - 56FCB35B1C21210B00305D10 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = ""; }; - 56FCB35C1C21210B00305D10 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = ""; }; - 56FCB35D1C21210B00305D10 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = ""; }; - 56FCB35E1C21210B00305D10 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = ""; }; - 56FCB35F1C21210B00305D10 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = ""; }; - 56FCB3601C21210B00305D10 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = ""; }; - 56FCB3621C21210B00305D10 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = ""; }; - 56FCB3631C21210B00305D10 /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; - 56FCB3651C21210B00305D10 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; - 56FCB3671C21210B00305D10 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = ""; }; - 56FCB3681C21210B00305D10 /* StandardLibraryTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibraryTypes.swift; sourceTree = ""; }; + 566A20F21C58A4B300C5A218 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; + 566A20F61C58A54F00C5A218 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = ""; }; + 566A20F71C58A54F00C5A218 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = ""; }; + 566A20F81C58A54F00C5A218 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = ""; }; + 566A20F91C58A54F00C5A218 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = ""; }; + 566A20FA1C58A54F00C5A218 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = ""; }; + 566A20FC1C58A54F00C5A218 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; + 566A20FD1C58A54F00C5A218 /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; + 566A20FE1C58A54F00C5A218 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; + 566A20FF1C58A54F00C5A218 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = ""; }; + 566A21001C58A54F00C5A218 /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; + 566A21011C58A54F00C5A218 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = ""; }; + 566A21021C58A54F00C5A218 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = ""; }; + 566A21031C58A54F00C5A218 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; + 566A21051C58A54F00C5A218 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = ""; }; + 566A21071C58A54F00C5A218 /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; + 566A21091C58A54F00C5A218 /* Collation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Collation.swift; sourceTree = ""; }; + 566A210A1C58A54F00C5A218 /* Function.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Function.swift; sourceTree = ""; }; + 566A210B1C58A54F00C5A218 /* Operator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Operator.swift; sourceTree = ""; }; + 566A210C1C58A54F00C5A218 /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = ""; }; + 566A210E1C58A54F00C5A218 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = ""; }; + 566A210F1C58A54F00C5A218 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = ""; }; + 566A21101C58A54F00C5A218 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = ""; }; + 566A21111C58A54F00C5A218 /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; + 566A21121C58A54F00C5A218 /* NSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDate.swift; sourceTree = ""; }; + 566A21131C58A54F00C5A218 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = ""; }; + 566A21141C58A54F00C5A218 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = ""; }; + 566A21151C58A54F00C5A218 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = ""; }; + 566A21161C58A54F00C5A218 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = ""; }; + 566A21171C58A54F00C5A218 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = ""; }; + 566A21181C58A54F00C5A218 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = ""; }; + 566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = ""; }; + 566A211F1C58A54F00C5A218 /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; + 566A21231C58A54F00C5A218 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; + 566A21251C58A54F00C5A218 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = ""; }; + 566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibraryTypes.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -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 = ""; }; - 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 = ""; @@ -191,82 +190,117 @@ name = Models; sourceTree = ""; }; - 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 = ""; + }; + 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 = ""; }; - 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 = ""; }; - 56FCB3531C21210B00305D10 /* CoreGraphics */ = { + 566A21041C58A54F00C5A218 /* CoreGraphics */ = { isa = PBXGroup; children = ( - 56FCB3541C21210B00305D10 /* CGFloat.swift */, + 566A21051C58A54F00C5A218 /* CGFloat.swift */, ); path = CoreGraphics; sourceTree = ""; }; - 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 = ""; + }; + 566A21081C58A54F00C5A218 /* SQLSupport */ = { + isa = PBXGroup; + children = ( + 566A21091C58A54F00C5A218 /* Collation.swift */, + 566A210A1C58A54F00C5A218 /* Function.swift */, + 566A210B1C58A54F00C5A218 /* Operator.swift */, + 566A210C1C58A54F00C5A218 /* SQLQuery.swift */, + ); + path = SQLSupport; + sourceTree = ""; + }; + 566A210D1C58A54F00C5A218 /* Foundation */ = { + isa = PBXGroup; + children = ( + 566A210E1C58A54F00C5A218 /* DatabaseCoder.swift */, + 566A210F1C58A54F00C5A218 /* DatabaseDateComponents.swift */, + 566A21101C58A54F00C5A218 /* DatabaseValue+Foundation.swift */, + 566A21111C58A54F00C5A218 /* NSData.swift */, + 566A21121C58A54F00C5A218 /* NSDate.swift */, + 566A21131C58A54F00C5A218 /* NSNull.swift */, + 566A21141C58A54F00C5A218 /* NSNumber.swift */, + 566A21151C58A54F00C5A218 /* NSString.swift */, + 566A21161C58A54F00C5A218 /* NSURL.swift */, + 566A21171C58A54F00C5A218 /* Row+Foundation.swift */, + 566A21181C58A54F00C5A218 /* StatementArguments+Foundation.swift */, ); path = Foundation; sourceTree = ""; }; - 56FCB3611C21210B00305D10 /* Migrations */ = { + 566A211D1C58A54F00C5A218 /* Migrations */ = { isa = PBXGroup; children = ( - 56FCB3621C21210B00305D10 /* DatabaseMigrator.swift */, - 56FCB3631C21210B00305D10 /* Migration.swift */, + 566A211E1C58A54F00C5A218 /* DatabaseMigrator.swift */, + 566A211F1C58A54F00C5A218 /* Migration.swift */, ); path = Migrations; sourceTree = ""; }; - 56FCB3641C21210B00305D10 /* Record */ = { + 566A21221C58A54F00C5A218 /* Record */ = { isa = PBXGroup; children = ( - 56FCB3651C21210B00305D10 /* Record.swift */, + 566A21231C58A54F00C5A218 /* Record.swift */, ); path = Record; sourceTree = ""; }; - 56FCB3661C21210B00305D10 /* Swift */ = { + 566A21241C58A54F00C5A218 /* Swift */ = { isa = PBXGroup; children = ( - 56FCB3671C21210B00305D10 /* RawRepresentable.swift */, - 56FCB3681C21210B00305D10 /* StandardLibraryTypes.swift */, + 566A21251C58A54F00C5A218 /* RawRepresentable.swift */, + 566A21261C58A54F00C5A218 /* StandardLibraryTypes.swift */, ); path = Swift; sourceTree = ""; @@ -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; }; diff --git a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/AppDatabase.swift b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/AppDatabase.swift new file mode 100644 index 000000000..6b2d82832 --- /dev/null +++ b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/AppDatabase.swift @@ -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) +} \ No newline at end of file diff --git a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/AppDelegate.swift b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/AppDelegate.swift index 4de4e5ccc..d5b26ac98 100644 --- a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/AppDelegate.swift +++ b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/AppDelegate.swift @@ -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 } } diff --git a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift index 165bb027d..b6e2ef5f0 100644 --- a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift +++ b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/Person.swift @@ -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) { diff --git a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/PersonsViewController.swift b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/PersonsViewController.swift index bc1e6027c..46e060ef4 100644 --- a/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/PersonsViewController.swift +++ b/DemoApps/GRDBDemoiOS7/GRDBDemoiOS7/PersonsViewController.swift @@ -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) + } + } diff --git a/GRDB Tests/GRDBTestCase.swift b/GRDB Tests/GRDBTestCase.swift index 417df0fc6..9270a6670 100644 --- a/GRDB Tests/GRDBTestCase.swift +++ b/GRDB Tests/GRDBTestCase.swift @@ -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(request: FetchRequest) -> String { + return dbQueue.inDatabase { db in + let _ = Row.fetchOne(db, request) + return self.lastSQLQuery + } + } } diff --git a/GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift b/GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift index 5783a5a29..bcce15195 100644 --- a/GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift +++ b/GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift @@ -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 diff --git a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift b/GRDB Tests/Public/Core/Persistable/MutablePersistableTests.swift similarity index 98% rename from GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift rename to GRDB Tests/Public/Core/Persistable/MutablePersistableTests.swift index 20868ca22..9a3c829ef 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/MutableDatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/Persistable/MutablePersistableTests.swift @@ -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() diff --git a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift b/GRDB Tests/Public/Core/Persistable/PersistableTests.swift similarity index 98% rename from GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift rename to GRDB Tests/Public/Core/Persistable/PersistableTests.swift index 3099c1476..340988e27 100644 --- a/GRDB Tests/Public/Core/DatabasePersistable/DatabasePersistableTests.swift +++ b/GRDB Tests/Public/Core/Persistable/PersistableTests.swift @@ -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() diff --git a/GRDB Tests/Public/FetchRequest/FetchRequestTests.swift b/GRDB Tests/Public/FetchRequest/FetchRequestTests.swift new file mode 100644 index 000000000..58738902f --- /dev/null +++ b/GRDB Tests/Public/FetchRequest/FetchRequestTests.swift @@ -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(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") + } +} diff --git a/GRDB Tests/Public/FetchRequest/Record+FetchRequestTests.swift b/GRDB Tests/Public/FetchRequest/Record+FetchRequestTests.swift new file mode 100644 index 000000000..b380eef18 --- /dev/null +++ b/GRDB Tests/Public/FetchRequest/Record+FetchRequestTests.swift @@ -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]) + } + } + } + } +} diff --git a/GRDB Tests/Public/FetchRequest/RowConvertible+FetchRequestTests.swift b/GRDB Tests/Public/FetchRequest/RowConvertible+FetchRequestTests.swift new file mode 100644 index 000000000..ef0690564 --- /dev/null +++ b/GRDB Tests/Public/FetchRequest/RowConvertible+FetchRequestTests.swift @@ -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]) + } + } + } + } +} diff --git a/GRDB Tests/Public/FetchRequest/SQLSupportTests.swift b/GRDB Tests/Public/FetchRequest/SQLSupportTests.swift new file mode 100644 index 000000000..559e367dd --- /dev/null +++ b/GRDB Tests/Public/FetchRequest/SQLSupportTests.swift @@ -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(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 = 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 = "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 = "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 = "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 = "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\"") + } +} diff --git a/GRDB Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift b/GRDB Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift new file mode 100644 index 000000000..825fe3ba8 --- /dev/null +++ b/GRDB Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift @@ -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") + } +} diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 0c958a857..a7cd54269 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -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 = ""; }; - 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistableTests.swift; sourceTree = ""; }; + 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = ""; }; 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionTests.swift; sourceTree = ""; }; 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5614DEEF1BA9DA15003163B3 /* SQLiteStatementConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteStatementConvertible.swift; sourceTree = ""; }; 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; + 56300B5D1C53C38F005A543B /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; + 56300B601C53C42C005A543B /* RowConvertible+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+FetchRequestTests.swift"; sourceTree = ""; }; + 56300B671C53D25E005A543B /* SQLSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSupportTests.swift; sourceTree = ""; }; + 56300B6A1C53D3E8005A543B /* TableMapping+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+FetchRequestTests.swift"; sourceTree = ""; }; + 56300B6F1C53F592005A543B /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; + 56300B721C53F592005A543B /* Collation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Collation.swift; sourceTree = ""; }; + 56300B731C53F592005A543B /* Function.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Function.swift; sourceTree = ""; }; + 56300B741C53F592005A543B /* Operator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Operator.swift; sourceTree = ""; }; + 56300B751C53F592005A543B /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = ""; }; + 56300B841C54DC95005A543B /* Record+FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+FetchRequestTests.swift"; sourceTree = ""; }; 563445041C4A7FD7003D3DC6 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; - 56437C831C180EDB007D6DB3 /* DatabasePersistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistable.swift; sourceTree = ""; }; + 56437C831C180EDB007D6DB3 /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollationTests.swift; sourceTree = ""; }; 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableDatabasePersistableTests.swift; sourceTree = ""; }; + 5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; 565D5D671BBC604000DC9BD4 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; @@ -362,7 +392,7 @@ 56A238761B9C75030082EB20 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = ""; }; 56A238781B9C75030082EB20 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = ""; }; 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = ""; }; - 56A238961B9C752B0082EB20 /* DatabaseTableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTableMapping.swift; sourceTree = ""; }; + 56A238961B9C752B0082EB20 /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; 56A238971B9C752B0082EB20 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 56A238981B9C752B0082EB20 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; 56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; @@ -501,13 +531,13 @@ path = TransactionObserver; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* DatabasePersistable */ = { + 560B3FA41C19DFF800C58EC7 /* Persistable */ = { isa = PBXGroup; children = ( - 560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */, - 5658420D1C1A1C820099FE88 /* MutableDatabasePersistableTests.swift */, + 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */, + 5658420D1C1A1C820099FE88 /* MutablePersistableTests.swift */, ); - path = DatabasePersistable; + path = Persistable; sourceTree = ""; }; 560C97BF1BFD0B5B00BF8471 /* Function */ = { @@ -527,6 +557,38 @@ name = Frameworks; sourceTree = ""; }; + 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 = ""; + }; + 56300B6D1C53F592005A543B /* FetchRequest */ = { + isa = PBXGroup; + children = ( + 56300B6F1C53F592005A543B /* FetchRequest.swift */, + 56300B711C53F592005A543B /* SQLSupport */, + ); + path = FetchRequest; + sourceTree = ""; + }; + 56300B711C53F592005A543B /* SQLSupport */ = { + isa = PBXGroup; + children = ( + 56300B721C53F592005A543B /* Collation.swift */, + 56300B731C53F592005A543B /* Function.swift */, + 56300B741C53F592005A543B /* Operator.swift */, + 56300B751C53F592005A543B /* SQLQuery.swift */, + ); + path = SQLSupport; + sourceTree = ""; + }; 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 = ""; @@ -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 = ""; @@ -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; diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index bbb832272..54bf5f3ef 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,6 +1,6 @@ import Foundation -/// Configuration are arguments to the DatabaseQueue initializers. +/// Configure a DatabaseQueue public struct Configuration { // MARK: - Misc options diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 322db1548..450692906 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -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. diff --git a/GRDB/Core/Protocols/DatabaseValueConvertible.swift b/GRDB/Core/Protocols/DatabaseValueConvertible.swift index 910b787fc..171cfc98a 100644 --- a/GRDB/Core/Protocols/DatabaseValueConvertible.swift +++ b/GRDB/Core/Protocols/DatabaseValueConvertible.swift @@ -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 { 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 @@ -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 { 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 { 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.fetch(db, "SELECT name FROM ...") // DatabaseSequence @@ -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 { 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) } diff --git a/GRDB/Core/Protocols/DatabasePersistable.swift b/GRDB/Core/Protocols/Persistable.swift similarity index 91% rename from GRDB/Core/Protocols/DatabasePersistable.swift rename to GRDB/Core/Protocols/Persistable.swift index 773cdf63e..1edc9292c 100644 --- a/GRDB/Core/Protocols/DatabasePersistable.swift +++ b/GRDB/Core/Protocols/Persistable.swift @@ -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) diff --git a/GRDB/Core/Protocols/RowConvertible.swift b/GRDB/Core/Protocols/RowConvertible.swift index 4324bb964..b02272acf 100644 --- a/GRDB/Core/Protocols/RowConvertible.swift +++ b/GRDB/Core/Protocols/RowConvertible.swift @@ -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 { 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 { 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) } diff --git a/GRDB/Core/Protocols/SQLiteStatementConvertible.swift b/GRDB/Core/Protocols/SQLiteStatementConvertible.swift index e267ccc13..06c9fbdee 100644 --- a/GRDB/Core/Protocols/SQLiteStatementConvertible.swift +++ b/GRDB/Core/Protocols/SQLiteStatementConvertible.swift @@ -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 { 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 @@ -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 { 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) } diff --git a/GRDB/Core/Protocols/DatabaseTableMapping.swift b/GRDB/Core/Protocols/TableMapping.swift similarity index 92% rename from GRDB/Core/Protocols/DatabaseTableMapping.swift rename to GRDB/Core/Protocols/TableMapping.swift index 54c308ec0..e6b764c5b 100644 --- a/GRDB/Core/Protocols/DatabaseTableMapping.swift +++ b/GRDB/Core/Protocols/TableMapping.swift @@ -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(db: Database, keys: Sequence) -> DatabaseSequence { 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(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(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(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 { 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 { diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index a04f2681b..3176f56d7 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -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 { // 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 { 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 diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 4348fb25e..087bb093b 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -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(arguments arguments: StatementArguments?, element: () -> T) -> DatabaseSequence { // 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) diff --git a/GRDB/FetchRequest/FetchRequest.swift b/GRDB/FetchRequest/FetchRequest.swift new file mode 100644 index 000000000..7c48293d9 --- /dev/null +++ b/GRDB/FetchRequest/FetchRequest.swift @@ -0,0 +1,539 @@ +/// A FetchRequest describes an SQL query. +/// +/// See https://github.com/groue/GRDB.swift#the-query-interface +public struct FetchRequest { + 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 { + return select(selection) + } + + /// Returns a new FetchRequest with a new net of selected columns. + @warn_unused_result + public func select(selection: [_SQLSelectable]) -> FetchRequest { + 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 { + return select(SQLLiteral(sql)) + } + + /// Returns a new FetchRequest which returns distinct rows. + public var distinct: FetchRequest { + 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 { + 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 { + return filter(SQLLiteral(sql)) + } + + /// Returns a new FetchRequest grouped according to *expressions*. + @warn_unused_result + public func group(expressions: _SQLExpressionType...) -> FetchRequest { + return group(expressions) + } + + /// Returns a new FetchRequest grouped according to *expressions*. + @warn_unused_result + public func group(expressions: [_SQLExpressionType]) -> FetchRequest { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + return order([SQLLiteral(sql)]) + } + + /// Returns a new FetchRequest sorted in reversed order. + @warn_unused_result + public func reverse() -> FetchRequest { + 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 { + 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(db: Database, _ selection: _SQLSelectable) -> T? { + return T.fetchOne(db, FetchRequest(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 + /// + /// 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 { + 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 + @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 { + return FetchRequest(tableName: databaseTableName()) + } + + /// Returns a FetchRequest which selects *selection*. + @warn_unused_result + public static func select(selection: _SQLSelectable...) -> FetchRequest { + return all().select(selection) + } + + /// Returns a FetchRequest which selects *selection*. + @warn_unused_result + public static func select(selection: [_SQLSelectable]) -> FetchRequest { + return all().select(selection) + } + + /// Returns a FetchRequest which selects *sql*. + @warn_unused_result + public static func select(sql sql: String) -> FetchRequest { + return all().select(sql: sql) + } + + /// Returns a FetchRequest with the provided *predicate*. + @warn_unused_result + public static func filter(predicate: _SQLExpressionType) -> FetchRequest { + return all().filter(predicate) + } + + /// Returns a FetchRequest with the provided *predicate*. + @warn_unused_result + public static func filter(sql sql: String) -> FetchRequest { + return all().filter(sql: sql) + } + + /// Returns a FetchRequest sorted according to the + /// provided *sortDescriptors*. + @warn_unused_result + public static func order(sortDescriptors: _SQLSortDescriptorType...) -> FetchRequest { + return all().order(sortDescriptors) + } + + /// Returns a FetchRequest sorted according to the + /// provided *sortDescriptors*. + @warn_unused_result + public static func order(sortDescriptors: [_SQLSortDescriptorType]) -> FetchRequest { + return all().order(sortDescriptors) + } + + /// Returns a FetchRequest sorted according to *sql*. + @warn_unused_result + public static func order(sql sql: String) -> FetchRequest { + 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 { + 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 + /// + /// 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(db: Database, _ request: FetchRequest) -> DatabaseSequence { + 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(db: Database, _ request: FetchRequest) -> [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(db: Database, _ request: FetchRequest) -> 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.fetch(db, request) // DatabaseSequence + /// + /// The returned sequence can be consumed several times, but it may yield + /// different results, should database changes have occurred between two + /// generations: + /// + /// let names = Optional.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(db: Database, _ request: FetchRequest) -> DatabaseSequence { + 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.fetchAll(db, request) // [String?] + @warn_unused_result + public static func fetchAll(db: Database, _ request: FetchRequest) -> [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 + /// + /// 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(db: Database, _ request: FetchRequest) -> DatabaseSequence { + 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(db: Database, _ request: FetchRequest) -> [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(db: Database, _ request: FetchRequest) -> 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 + /// + /// 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(db: Database, _ request: FetchRequest) -> DatabaseSequence { + 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 + @warn_unused_result + public static func fetchAll(db: Database, _ request: FetchRequest) -> [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(db: Database, _ request: FetchRequest) -> 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(db: Database, _ request: FetchRequest) -> DatabaseSequence { + 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(db: Database, _ request: FetchRequest) -> [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(db: Database, _ request: FetchRequest) -> Row? { + return try! fetchOne(request.selectStatement(db)) + } +} diff --git a/GRDB/FetchRequest/SQLSupport/Collation.swift b/GRDB/FetchRequest/SQLSupport/Collation.swift new file mode 100644 index 000000000..7a5d2f28d --- /dev/null +++ b/GRDB/FetchRequest/SQLSupport/Collation.swift @@ -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) +} diff --git a/GRDB/FetchRequest/SQLSupport/Function.swift b/GRDB/FetchRequest/SQLSupport/Function.swift new file mode 100644 index 000000000..08a38864a --- /dev/null +++ b/GRDB/FetchRequest/SQLSupport/Function.swift @@ -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]) + } +} diff --git a/GRDB/FetchRequest/SQLSupport/Operator.swift b/GRDB/FetchRequest/SQLSupport/Operator.swift new file mode 100644 index 000000000..d2e092dd4 --- /dev/null +++ b/GRDB/FetchRequest/SQLSupport/Operator.swift @@ -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) +} diff --git a/GRDB/FetchRequest/SQLSupport/SQLQuery.swift b/GRDB/FetchRequest/SQLSupport/SQLQuery.swift new file mode 100644 index 000000000..ce5aa1189 --- /dev/null +++ b/GRDB/FetchRequest/SQLSupport/SQLQuery.swift @@ -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) + } +} diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 75ed2f59c..2d40466e6 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -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 diff --git a/Playgrounds/Record.playground/Contents.swift b/Playgrounds/Record.playground/Contents.swift index ae7ae662e..be725c403 100644 --- a/Playgrounds/Record.playground/Contents.swift +++ b/Playgrounds/Record.playground/Contents.swift @@ -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 }) diff --git a/README.md b/README.md index a612140dd..9dc6caa68 100644 --- a/README.md +++ b/README.md @@ -1,72 +1,35 @@ GRDB.swift ========== -GRDB.swift is an SQLite toolkit for Swift 2. It is written for developers who want to leverage their SQL and SQLite skills. +GRDB.swift is an SQLite toolkit for Swift 2. -**Features** +It provides an SQL API and application tools. -- [SQLite API](#sqlite-api) -- [Protocols](#database-protocols-and-record) that provide fetching and persistence methods to your custom structs and class hierarchies -- Application tools, such as [migrations](#migrations) and [database observation hooks](#database-changes-observation) -- [Speed](https://github.com/groue/GRDB.swift/wiki/Performance) - -**January 17, 2016: GRDB.swift 0.41.0 is out** - [Release notes](CHANGELOG.md). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +**January 17, 2016: GRDB.swift 0.41.0 is out** ([changelog](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. **Requirements**: iOS 7.0+ / OSX 10.9+, Xcode 7+ -**Swift Package Manager**: Use the [Swift2.2 branch](https://github.com/groue/GRDB.swift/tree/Swift2.2). + +### Documentation + +- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.41.0/index.html) (on cocoadocs.org) +- [Installation](#installation) +- [SQLite API](#sqlite-api): SQL & SQLite +- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies. +- [Query Interface](#the-query-interface): A swift way to generate SQL. +- [Migrations](#migrations): Transform your database as your application evolves. +- [Database Changes Observation](#database-changes-observation): Perform post-commit and post-rollback actions. +- [Sample Code](#sample-code) -Documentation -============= +### Installation -- **[GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.41.0/index.html)** (on cocoadocs.org) - -- **[Installation](#installation)** - -- **[SQLite API](#sqlite-api)** - - [SQLite API Overview](#sqlite-api-overview) - - [Database Queues](#database-queues) - - [Executing Updates](#executing-updates) - - [Fetch Queries](#fetch-queries) - - [Row Queries](#row-queries) - - [Value Queries](#value-queries) - - [Values](#values) - - [NSData](#nsdata-and-memory-savings) - - [NSDate and NSDateComponents](#nsdate-and-nsdatecomponents) - - [Swift enums](#swift-enums) - - [Transactions](#transactions) - - [Error Handling](#error-handling) - - Advanced topics: - - [Custom Value Types](#custom-value-types) - - [Prepared Statements](#prepared-statements) - - [Concurrency](#concurrency) - - [Custom SQL Functions](#custom-sql-functions) - - [Custom Collations](#custom-collations) - - [Raw SQLite Pointers](#raw-sqlite-pointers) - - -- **[Migrations](#migrations)**: Transform your database as your application evolves. - -- **[Database Protocols, and Record](#database-protocols-and-record)** - - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. - - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with persistence methods. - - [Record](#record): The class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. - -- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. - -- **[Sample Code](#sample-code)** - - -Installation -============ - -### iOS7 +#### iOS7 You can use GRDB.swift in a project targetting iOS7. See [GRDBDemoiOS7](DemoApps/GRDBDemoiOS7) for more information. -### CocoaPods +#### CocoaPods [CocoaPods](http://cocoapods.org/) is a dependency manager for Xcode projects. @@ -80,7 +43,7 @@ pod 'GRDB.swift', '~> 0.41.0' ``` -### Carthage +#### Carthage [Carthage](https://github.com/Carthage/Carthage) is another dependency manager for Xcode projects. @@ -91,7 +54,7 @@ github "groue/GRDB.swift" ~> 0.41.0 ``` -### Manually +#### Manually 1. Download a copy of GRDB.swift. 2. Embed the `GRDB.xcodeproj` project in your own project. @@ -104,7 +67,7 @@ See [GRDBDemoiOS](DemoApps/GRDBDemoiOS) for an example of such integration. SQLite API ========== -## SQLite API Overview +**Overview** ```swift import GRDB @@ -135,6 +98,25 @@ try dbQueue.inDatabase { db in } ``` +- [Database Queues](#database-queues) +- [Executing Updates](#executing-updates) +- [Fetch Queries](#fetch-queries) + - [Row Queries](#row-queries) + - [Value Queries](#value-queries) +- [Values](#values) + - [NSData](#nsdata-and-memory-savings) + - [NSDate and NSDateComponents](#nsdate-and-nsdatecomponents) + - [Swift enums](#swift-enums) +- [String Comparison](#string-comparison) +- [Transactions](#transactions) +- [Error Handling](#error-handling) +- Advanced topics: + - [Custom Value Types](#custom-value-types) + - [Prepared Statements](#prepared-statements) + - [Concurrency](#concurrency) + - [Custom SQL Functions](#custom-sql-functions) + - [Raw SQLite Pointers](#raw-sqlite-pointers) + ## Database Queues @@ -190,6 +172,7 @@ let dbQueue = try DatabaseQueue( See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.41.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. +> :bowtie: **Tip**: see [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift) for a sample code that sets up a GRDB database. ## Executing Updates @@ -229,7 +212,7 @@ let personID = try db.execute( arguments: ["Arthur", 36]).insertedRowID ``` -Don't miss the [DatabasePersistable protocol](#databasepersistable-protocol) and the [Record class](#record), that provide classic **persistence methods**: +Don't miss the [Persistable](#persistable-protocol) protocol and the [Record](#record-class) class, that provide classic **persistence methods**: ```swift let person = Person(name: "Arthur", age: 36) @@ -240,7 +223,7 @@ print("Inserted \(person.id)") ## Fetch Queries -GRDB lets you fetch **rows**, **values**, and **custom models**. +GRDB lets you fetch **rows**, **values**, and custom models aka "**records**". **Rows** are the results of SQL queries (see [row queries](#row-queries)): @@ -250,7 +233,7 @@ dbQueue.inDatabase { db in Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row] Row.fetchOne(db, "SELECT ...", arguments: ...) // Row? - // Example: + // Example for row in Row.fetch(db, "SELECT * FROM wines") { let name: String = row.value(named: "name") let color: Color = row.value(named: "color") @@ -270,27 +253,32 @@ dbQueue.inDatabase { db in Optional.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence Optional.fetchAll(db, "SELECT ...", arguments: ...) // [Int?] - // Example: + // Example let wineCount = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! } ``` -**Custom models** are your application objects that can initialize themselves from rows (see the [RowConvertible protocol](#rowconvertible-protocol) and the [Record class](#record)): +**Records** are your application objects that can initialize themselves from rows (see [records](#records)). ```swift dbQueue.inDatabase { db in - // By SQL: + // Using the Query Interface + Wine.filter(name == "Pomerol").fetch(db) // DatabaseSequence + Wine.filter(name == "Pomerol").fetchAll(db) // [Wine] + Wine.filter(name == "Pomerol").fetchOne(db) // Wine? + + // By key + Wine.fetch(db, keys: [1, 2, 3]) // DatabaseSequence + Wine.fetchAll(db, keys: [1, 2, 3]) // [Wine] + Wine.fetchOne(db, key: 1) // Wine? + + // Using SQL Wine.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence Wine.fetchAll(db, "SELECT ...", arguments: ...) // [Wine] Wine.fetchOne(db, "SELECT ...", arguments: ...) // Wine? - // By key: - Wine.fetch(db, keys: ...) // DatabaseSequence - Wine.fetchAll(db, keys: ...) // [Wine] - Wine.fetchOne(db, key: ...) // Wine? - - // Example: - let wines = Wine.fetchAll(db, "SELECT * FROM wines ORDER BY name") + // Example + let wines = Wine.order(name).fetchAll(db) let favoriteWine = Wine.fetchOne(db, key: favoriteWineID) } ``` @@ -338,7 +326,7 @@ See [Values](#values) for more information on supported arguments types (Bool, I Both `fetch` and `fetchAll` let you iterate the full list of fetched rows. The differences are: - `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory. -- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). +- `fetch` returns a sequence that is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). The sequence fetches a new set of results each time it is iterated. > :point_up: **Don't turn a row sequence into an array** with `Array(rowSequence)` or `rowSequence.filter { ... }`: you would not get the distinct rows you expect. To get an array, use `Row.fetchAll(...)`. > @@ -533,7 +521,7 @@ dbQueue.inDatabase { db in Both `fetch` and `fetchAll` let you iterate the full list of fetched values. The differences are: - `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory. -- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). +- `fetch` returns a sequence that is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). The sequence fetches a new set of results each time it is iterated. `fetchOne` returns an optional value which is nil in two cases: either the SELECT statement yielded no row, or one row with a NULL value. @@ -573,7 +561,7 @@ They can be [directly fetched](#value-queries) from the database: let urls = NSURL.fetchAll(db, "SELECT url FROM links") // [NSURL] ``` -Use them in the `persistentDictionary` property of [DatabasePersistable protocol](#databasepersistable-protocol) and [Record subclasses](#record): +Use them in the `persistentDictionary` property of [Persistable](#persistable-protocol) protocol and [Record](#record-class) subclasses: ```swift class Link : Record { @@ -790,6 +778,59 @@ Color.fetchOne(db, "SELECT ...", arguments: ...) // Color? See [Column Values](#column-values) and [Value Queries](#value-queries) for more information. +## String Comparison + +SQLite compares strings in many occasions: when you sort rows according to a string column, or when you use a comparison operator such as `=` and `<=`. + +The comparison result comes from a *collating function*, or *collation*. SQLite comes with [three built-in collations](https://www.sqlite.org/datatype3.html#collation): + +- `binary`, the default, which considers "Foo" and "foo" to be inequal, and "Jérôme" and "Jerome" to be inequal because it has no Unicode support. +- `nocase`, which considers "Foo" and "foo" to be equal, but "Jérôme" and "Jerome" to be inequal because it has no Unicode support. +- `rtrim`: the same as `binary`, except that trailing space characters are ignored. + +**You can define your own collations**, based on the rich set of Swift string comparisons: + +```swift +let collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in + return (lhs as NSString).localizedCaseInsensitiveCompare(rhs) +} + +dbQueue.inDatabase { db in + db.addCollation(collation) +} +``` + +Once defined, the custom collation can be applied to a table column. All comparisons involving this column will automatically trigger your comparison function: + +```swift +dbQueue.inDatabase { db in + // Apply the custom collation to the `name` column + try db.execute( + "CREATE TABLE persons (" + + "name TEXT COLLATE localized_case_insensitive" + // The name of the collation + ")") + + // Persons are sorted as expected: + let persons = Person.order(name).fetchAll(db) + + // Matches "Jérôme", "jerome", etc. + let persons = Person.filter(name == "Jérôme").fetchAll(db) +} +``` + +If you can't or don't want to define the comparison behavior of a column, you can still use an explicit collation on particular requests: + +```swift +// SELECT * FROM "persons" WHERE ("name" = 'foo' COLLATE NOCASE) +let persons = Person.filter(name.collating("NOCASE") == "foo").fetchAll(db) + +// SELECT * FROM "persons" WHERE ("name" = 'Jérôme' COLLATE localized_case_insensitive) +let persons = Person.filter(name.collating(collation) == "Jérôme").fetchAll(db) +``` + +See the [query interface](#the-query-interface) for more information. + + ## Transactions The `DatabaseQueue.inTransaction()` method opens an SQLite transaction: @@ -1096,31 +1137,6 @@ dbQueue.inDatabase { db in See [Error Handling](#error-handling) for more information on database errors. -## Custom Collations - -**When SQLite compares two strings, it uses a collating function** to determine which string is greater or if the two strings are equal. - -SQLite lets you define your own collating functions. This is how you can bring support for unicode or localization when comparing strings: - -```swift -dbQueue.inDatabase { db in - // Define the localized_case_insensitive collation: - let collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in - return (lhs as NSString).localizedCaseInsensitiveCompare(rhs) - } - db.addCollation(collation) - - // Put it to some use: - try db.execute("CREATE TABLE persons (lastName TEXT COLLATE LOCALIZED_CASE_INSENSITIVE)") - - // Persons are sorted as expected: - Person.fetchAll(db, "SELECT * FROM persons ORDER BY lastName") -} -``` - -Check https://www.sqlite.org/datatype3.html#collation for more information. - - ## Raw SQLite Pointers Not all SQLite APIs are exposed in GRDB. @@ -1154,7 +1170,7 @@ Before jumping in the low-level wagon, here is a reminder of SQLite APIs support - [sqlite3_changes](https://www.sqlite.org/c3ref/changes.html) - Custom SQL functions (see [Custom SQL Functions](#custom-sql-functions)) - [sqlite3_create_function_v2](https://www.sqlite.org/c3ref/create_function.html) -- Custom collations (see [Custom Collations](#custom-collations)) +- Custom collations (see [String Comparison](#string-comparison)) - [sqlite3_create_collation_v2](https://www.sqlite.org/c3ref/create_collation.html) - Busy mode (see [Concurrency](#concurrency)). - [sqlite3_busy_handler](https://www.sqlite.org/c3ref/busy_handler.html) @@ -1170,12 +1186,883 @@ Application Tools On top of the SQLite API described above, GRDB provides a toolkit for applications. While none of those are mandatory, all of them help dealing with the database: -- **[Migrations](#migrations)**: Transform your database as your application evolves. -- **[Database Protocols, and Record](#database-protocols-and-record)** - - [RowConvertible Protocol](#rowconvertible-protocol): Don't fetch rows, fetch your custom types instead. - - [DatabasePersistable Protocol](#databasepersistable-protocol): Grant any type with persistence methods. - - [Record](#record): The class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. -- **[Database Changes Observation](#database-changes-observation)**: A robust way to perform post-commit and post-rollback actions. +- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies. +- [Query Interface](#the-query-interface): A swift way to generate SQL. +- [Migrations](#migrations): Transform your database as your application evolves. +- [Database Changes Observation](#database-changes-observation): Perform post-commit and post-rollback actions. + + +## Records + +**On top of the [SQLite API](#sqlite-api), GRDB provides protocols and a class** that help manipulating database rows as regular objects named "records". + +Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the `Record` class, and get the full toolkit in one go: fetching methods, persistence methods, and changes tracking. + + +#### Inserting Records + +To insert a record in the database, subclass the [Record](#record-class) class or adopt the [Persistable](#persistable-protocol) protocol, and call the `insert` method: + +```swift +class Person : Record { ... } + +let person = Person(name: "Arthur", email: "arthur@example.com") +try dbQueue.inDatabase { db in + try person.insert(db) +} +``` + +Of course, you need to open a [database connection](#database-queues), and [create a database table](#executing-updates) first. + + +#### Fetching Records + +[Record](#record-class) subclasses and types that adopt the [RowConvertible](#rowconvertible-protocol) protocol can be fetched from the database: + +```swift +class Person : Record { ... } + +dbQueue.inDatabase { db in + // Using the Query Interface + let persons = Person.filter(email != nil).order(name).fetchAll(db) + + // By key + let person = Person.fetchOne(db, key: 1) + + // Using SQL + let persons = Person.fetchAll(db, "SELECT ...", arguments: ...) +} +``` + +To learn more about querying records, check the [query interface](#the-query-interface). + + +#### Updating Records + +[Record](#record-class) subclasses and types that adopt the [Persistable](#persistable-protocol) protocol can be updated in the database: + +```swift +try dbQueue.inDatabase { db in + let person = Person.fetchOne(db, key: 1)! + person.name = "Arthur" + try person.update(db) +} +``` + +For batch updates, you have to execute an [SQL query](#executing-updates): + +```swift +try dbQueue.inDatabase { db in + try db.execute("UPDATE persons SET synchronized = 1") +} +``` + + +#### Deleting Records + +[Record](#record-class) subclasses and types that adopt the [Persistable](#persistable-protocol) protocol can be deleted from the database: + +```swift +try dbQueue.inDatabase { db in + let person = Person.fetchOne(db, key: 1)! + try person.delete(db) +} +``` + +For batch deletions, you have to execute an [SQL query](#executing-updates): + +```swift +try dbQueue.inDatabase { db in + try db.execute("DELETE FROM persons") +} +``` + + +#### Counting Records + +[Record](#record-class) subclasses and types that adopt the [TableMapping](#tablemapping-protocol) protocol can be counted: + +```swift +let personWithEmailCount = dbQueue.inDatabase { db in + Person.filter(email != nil).fetchCount(db) // Int +} +``` + +You can generally fetch the average, count, min, max and sum of any column. See the [query interface](#the-query-interface) for more details. + +You can now jump to: + +- [RowConvertible Protocol](#rowconvertible-protocol) +- [TableMapping Protocol](#tablemapping-protocol) +- [Persistable Protocol](#persistable-protocol) +- [Record Class](#record-class) +- [The Query Interface](#the-query-interface) + + +### RowConvertible Protocol + +**The `RowConvertible` protocol grants fetching methods to any type** that can be built from a database row: + +```swift +public protocol RowConvertible { + /// Returns a value initialized from `row`. + static func fromRow(row: Row) -> Self + + /// Optional method which gives adopting types an opportunity to complete + /// their initialization after being fetched. Do not call it directly. + mutating func awakeFromFetch(row row: Row, database: Database) +} +``` + +**To use RowConvertible**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: + +```swift +struct PointOfInterest { + var id: Int64? + var title: String? + var coordinate: CLLocationCoordinate2D +} + +extension PointOfInterest : RowConvertible { + static func fromRow(row: Row) -> PointOfInterest { + return PointOfInterest( + id: row.value(named: "id"), + title: row.value(named: "title"), + coordinate: CLLocationCoordinate2DMake( + row.value(named: "latitude"), + row.value(named: "longitude"))) + } +} +``` + +See [Column Values](#column-values) for more information about the `row.value()` method. + +> :point_up: **Note**: For performance reasons, the same row argument to `fromRow(:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. + +RowConvertible allows adopting types to be fetched: + +- From SQL queries: + + ```swift + PointOfInterest.fetch(db, "SELECT ...", arguments:...) // DatabaseSequence + PointOfInterest.fetchAll(db, "SELECT ...", arguments:...) // [PointOfInterest] + PointOfInterest.fetchOne(db, "SELECT ...", arguments:...) // PointOfInterest? + ``` + + See [Fetching Rows](#fetching-rows) for more information about the query arguments. + +- From primary key: + + ```swift + PointOfInterest.fetch(db, keys: ...) // DatabaseSequence + PointOfInterest.fetchAll(db, keys: ...) // [PointOfInterest] + PointOfInterest.fetchOne(db, key: ...) // PointOfInterest? + ``` + + Any single-column primary key is OK: + + ```swift + // SELECT * FROM pointOfInterests WHERE id IN (1, 2, 3) + PointOfInterest.fetchAll(db, keys: [1, 2, 3]) + + // SELECT * FROM pointOfInterests WHERE id = 1 + PointOfInterest.fetchOne(db, key: 1) + + // SELECT * FROM countries WHERE isoCode = 'FR' + Country.fetchOne(db, key: "FR") + ``` + +Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are: + +- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory. +- `fetch` returns a sequence that is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). The sequence fetches a new set of results each time it is iterated. + + +### TableMapping Protocol + +**Adopt the `TableMapping` protocol** on top of `RowConvertible`, and you are granted with the full [query interface](#the-query-interface). + +```swift +public protocol TableMapping { + static func databaseTableName() -> String +} +``` + +**To use TableMapping**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: + +```swift +extension PointOfInterest : TableMapping { + static func databaseTableName() -> String { + return "pointOfInterests" + } +} + +let paris = dbQueue.inDatabase { db in + PointOfInterest.filter(name == "Paris").fetchOne(db)? +} +``` + + +### Persistable Protocol + +**GRDB provides two protocols that let adopting types store themselves in the database:** + +```swift +public protocol MutablePersistable : TableMapping { + /// The name of the database table (from TableMapping) + static func databaseTableName() -> String + + /// The values persisted in the database + var persistentDictionary: [String: DatabaseValueConvertible?] { get } + + /// Optional method that lets your adopting type store its rowID upon + /// successful insertion. Don't call it directly: it is called for you. + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) +} +``` + +```swift +public protocol Persistable : MutablePersistable { + /// Non-mutating version of the optional didInsertWithRowID(:forColumn:) + func didInsertWithRowID(rowID: Int64, forColumn column: String?) +} +``` + +Yes, two protocols instead of one. Both grant exactly the same advantages. Here is how you pick one or the other: + +- *If your type is a struct that mutates on insertion*, choose `MutablePersistable`. For example, your table has an INTEGER PRIMARY KEY and you want to store the inserted id on successful insertion. Or your table has a UUID primary key, and you want to automatically generate one on insertion. +- Otherwise, stick with `Persistable`. Particularly if your type is a class. + +The `persistentDictionary` property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information. + +**To use those protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitely. For example: + +```swift +extension PointOfInterest : MutablePersistable { + + /// The values persisted in the database + var persistentDictionary: [String: DatabaseValueConvertible?] { + return [ + "id": id, + "title": title, + "latitude": coordinate.latitude, + "longitude": coordinate.longitude] + } + + // Update id upon successful insertion: + mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + id = rowID + } +} + +var paris = PointOfInterest( + id: nil, + title: "Paris", + coordinate: CLLocationCoordinate2DMake(48.8534100, 2.3488000)) + +try dbQueue.inDatabase { db in + try paris.insert(db) + paris.id // some value +} +``` + + +#### Persistence Methods + +[Record](#record-class) subclasses and types that adopt [Persistable](#persistable-protocol) are given default implementations for methods that insert, update, and delete: + +```swift +try object.insert(db) // INSERT +try object.update(db) // UPDATE +try object.save(db) // Inserts or updates +try object.delete(db) // DELETE +object.exists(db) // Bool +``` + +- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. + +- `update` can also throw a PersistenceError of type NotFound, should the update fail because there is no matching row in the database. + + When saving an object that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. + +- `delete` returns whether a database row was deleted or not. + + +#### Customizing the Persistence Methods + +Your custom type may want to perform extra work when the persistence methods are invoked. + +For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving. + +When you subclass [Record](#record-class), you simply have to override the customized method, and call `super`: + +```swift +class Person : Record { + var uuid: String? + + override func insert(db: Database) throws { + if uuid == nil { + uuid = NSUUID().UUIDString + } + try super.insert(db) + } +} +``` + +If you use the raw [Persistable](#persistable-protocol) protocol, use one of the *special methods* `performInsert`, `performUpdate`, `performSave`, `performDelete`, or `performExists`: + +```swift +struct Link : Persistable { + var url: NSURL + + func insert(db: Database) throws { + try validate() + try performInsert(db) + } + + func update(db: Database) throws { + try validate() + try performUpdate(db) + } + + func validate() throws { + if url.host == nil { + throw ValidationError("url must be absolute.") + } + } +} +``` + +> :point_up: **Note**: The special methods `performInsert`, `performUpdate`, etc. are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. +> +> :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`. + + +### Record Class + +**Record** is a class that builds on top of the [RowConvertible](#rowconvertible-protocol), [TableMapping](#tablemapping-protocol) and [Persistable](#persistable-protocol) protocols, and is designed to be subclassed. + +It provides [persistence methods](#persistence-methods), [changes tracking](#changes-tracking), and the [query interface](#the-query-interface): + +```swift +class PointOfInterest : Record { ... } + +// Persistence +let paris = PointOfInterest( + name: "Paris", + coordinate: CLLocationCoordinate2DMake(48.8534100, 2.3488000)) +try paris.insert(db) + +// Changes tracking +paris.hasPersistentChangedValues // false + +// Query interface +for poi in PointOfInterest.order(name).fetch(db) { poi in + print(poi.name) +} +``` + + +**Record subclasses override the four core methods that define their relationship with the database:** + +```swift +class Record { + /// The table name + class func databaseTableName() -> String + + /// Initialize from a database row + required init(_ row: Row) + + /// The values persisted in the database + var persistentDictionary: [String: DatabaseValueConvertible?] + + /// Optionally update record ID after a successful insertion + func didInsertWithRowID(rowID: Int64, forColumn column: String?) +} +``` + +For example: + +```swift +class PointOfInterest : Record { + var id: Int64? + var title: String? + var coordinate: CLLocationCoordinate2D + + /// The table name + override class func databaseTableName() -> String { + return "pointOfInterests" + } + + /// Initialize from a database row + required init(_ row: Row) { + self.id = row.value(named: "id") + self.title = row.value(named: "title") + self.coordinate = CLLocationCoordinate2DMake( + row.value(named: "latitude"), + row.value(named: "longitude")) + } + + /// The values persisted in the database + override var persistentDictionary: [String: DatabaseValueConvertible?] { + return [ + "id": id, + "title": title, + "latitude": coordinate.latitude, + "longitude": coordinate.longitude] + } + + /// Update record ID after a successful insertion + func didInsertWithRowID(rowID: Int64, forColumn column: String?) { + id = rowID + } +} +``` + + +#### Changes Tracking + +**[Record](#record-class) provides changes tracking.** + +The `update()` method always executes an UPDATE statement. When the record has not been edited, this database access is generally useless. + +Avoid it with the `hasPersistentChangedValues` property, which returns whether the record has changes that have not been saved: + +```swift +// Saves the person if it has changes that have not been saved: +if person.hasPersistentChangedValues { + try person.save(db) +} +``` + +The `hasPersistentChangedValues` flag is false after a record has been fetched or saved into the database. Subsequent modifications may set it: `hasPersistentChangedValues` is based on value comparison. **Setting a property to the same value does not set the changed flag**: + +```swift +let person = Person.fetchOne(db, key: 1) // Barbara, aged 35 + +person.name = "Barbara" +person.hasPersistentChangedValues // false + +person.age = 36 +person.hasPersistentChangedValues // true +person.persistentChangedValues // ["age": 35] +``` + +For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check this [sample code](https://gist.github.com/groue/dcdd3784461747874f41). + + +## The Query Interface + +**The query interface lets you write pure Swift instead of SQL:** + +```swift +let wines = Wine.filter(origin == "Burgundy").order(price).fetchAll(db) +``` + +Please bear in mind that the query interface can not generate all possible SQL queries. You may also *prefer* writing SQL. Don't miss the [SQL API](#fetch-queries). + +- [Requests](#requests) +- [Expressions](#expressions) + - [SQL Operators](#sql-operators) + - [SQL Functions](#sql-functions) +- [Fetching from Requests](#fetching-from-requests) +- [Counting with Requests](#counting-with-requests) + + +### Requests + +Everything starts from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): + +```swift +class Person: Record { + static func databaseTableName() -> String { + return "persons" + } +} +``` + +Define **columns** that represent SQL columns: + +```swift +let id = SQLColumn("id") +let name = SQLColumn("name") +``` + +> :bowtie: **Tip**: you don't want to lock a variable such as `name` for GRDB's fancy API, do you? My own practice is to declare a dedicated `Col` struct as below (see [sample code](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift)): +> +> ```swift +> struct Col { +> static let id = SQLColumn("id") +> static let name = SQLColumn("name") +> static let age = SQLColumn("age") +> } +> ``` + +You can now derive requests with the following methods: + +- `all` +- `select` +- `distinct` +- `filter` +- `group` +- `having` +- `order` +- `reverse` +- `limit` + +All the methods above return another request, which you can further refine by applying another derivation method. + +- `all()`: the request for all rows. + + ```swift + // SELECT * FROM "persons" + Person.all() + ``` + +- `select(expression, ...)` defines the selected columns. + + ```swift + // SELECT "id", "name" FROM "persons" + Person.select(Col.id, Col.name) + + // SELECT UPPER("name") FROM "persons" + Person.select(Col.name.uppercaseString) + + // SELECT UPPER("name") AS "uppercaseName" FROM "persons" + Person.select(Col.name.uppercaseString.aliased("uppercaseName")) + ``` + +- `distinct` performs uniquing: + + ```swift + // SELECT DISTINCT "name" FROM "persons" + Person.select(Col.name).distinct + ``` + +- `filter(expression)` applies conditions. + + ```swift + // SELECT * FROM "persons" WHERE ("id" IN (1, 2, 3)) + Person.filter([1,2,3].contains(Col.id)) + + // SELECT * FROM "persons" WHERE (("name" IS NOT NULL) AND ("height" > 1.75)) + Person.filter(Col.name != nil && Col.height > 1.75) + ``` + +- `group(expression, ...)` groups rows. + + ```swift + // SELECT "name", MAX("age") FROM "persons" GROUP BY "name" + Person + .select(Col.name, max(Col.age)) + .group(Col.name) + ``` + +- `having(expression)` applies conditions on grouped rows. + + ```swift + // SELECT "name", MAX("age") FROM "persons" GROUP BY "name" HAVING MIN("age") >= 18 + Person + .select(Col.name, max(Col.age)) + .group(Col.name) + .having(min(Col.age) >= 18) + ``` + +- `order(sortDescriptor, ...)` sorts. + + ```swift + // SELECT * FROM "persons" ORDER BY "name" + Person.order(Col.name) + + // SELECT * FROM "persons" ORDER BY UPPER("name") DESC, "email" ASC + Person.order(Col.name.uppercaseString.desc, Col.email.asc) + ``` + +- `reverse()` reverses the eventual sort descriptors. + + ```swift + // SELECT * FROM "persons" ORDER BY "name" DESC + Person.order(Col.name).reverse() + + // SELECT * FROM "persons" ORDER BY UPPER("name") ASC, "email" DESC + Person.order(Col.name.uppercaseString.desc, Col.email.asc)reverse() + ``` + + If no ordering was specified, the result is ordered by the primary key in reverse order. + + ```swift + // SELECT * FROM "persons" ORDER BY "id" DESC + Person.all().reverse() + ``` + +- `limit(limit, offset: offset)` limits and pages results. + + ```swift + // SELECT * FROM "persons" LIMIT 5 + Person.limit(5) + + // SELECT * FROM "persons" LIMIT 5 OFFSET 10 + Person.limit(5, offset: 10) + ``` + +You can refine requests by chaining those methods, in any order. + +```swift +// SELECT * FROM "persons" WHERE ("email" IS NOT NULL) ORDER BY "name" +Person.order(Col.name).filter(Col.email != nil) +``` + +The `select`, `group` and `limit` methods ignore and replace previously applied selection, grouping and limits. On the opposite, `filter`, `having`, and `order` methods augment the query: + +```swift +Person // SELECT * FROM "persons" + .filter(Col.name != nil) // WHERE (("name" IS NOT NULL) + .filter(Col.email != nil) // AND ("email IS NOT NULL")) + .order(Col.name) // ORDER BY "name" + .limit(20, offset: 40) // - ignored - + .limit(10) // LIMIT 10 +``` + + +Raw SQL snippets are also accepted: + +```swift +// SELECT DATE(creationDate), COUNT(*) FROM "persons" GROUP BY date(creationDate) +Person + .select(sql: "DATE(creationDate), COUNT(*)") + .group(sql: "DATE(creationDate)") +``` + + +### Expressions + +Feed [requests](#requests) with SQL expressions built from your Swift code: + + +#### SQL Operators + +- `=`, `<>`, `<`, `<=`, `>`, `>=`, `IS`, `IS NOT` + + Comparison operators are based on the Swift operators `==`, `!=`, `===`, `!==`, `<`, `<=`, `>`, `>=`: + + ```swift + // SELECT * FROM "persons" WHERE ("name" = 'Arthur') + Person.filter(Col.name == "Arthur") + + // SELECT * FROM "persons" WHERE ("name" IS NULL) + Person.filter(Col.name == nil) + + // SELECT * FROM "persons" WHERE ("age" <> 18) + Person.filter(Col.age != 18) + + // SELECT * FROM "persons" WHERE ("age" IS NOT 18) + Person.filter(Col.age !== 18) + + // SELECT * FROM "rectangles" WHERE ("width" < "height") + Rectangle.filter(Col.width < Col.height) + ``` + + > :point_up: **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [String Comparison](#string-comparison) if you need more control. + + +- `*`, `/`, `+`, `-` + + SQLite arithmetic operators are derived from their Swift equivalent: + + ```swift + // SELECT (("temperature" * 1.8) + 32) AS "farenheit" FROM "persons" + Planet.select((Col.temperature * 1.8 + 32).aliased("farenheit")) + ``` + + > :point_up: **Note**: an expression like `Col.name + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. + +- `AND`, `OR`, `NOT` + + The SQL logical operators are derived from the Swift `&&`, `||` and `!`: + + ```swift + // SELECT * FROM "persons" WHERE ((NOT "verified") OR ("age" < 18)) + Person.filter(!Col.verified || Col.age < 18) + ``` + +- `BETWEEN`, `IN`, `NOT IN` + + To check inclusion in a collection, call the `contains` method on any Swift sequence: + + ```swift + // SELECT * FROM "persons" WHERE ("id" IN (1, 2, 3)) + Person.filter([1, 2, 3].contains(Col.id)) + + // SELECT * FROM "persons" WHERE ("id" NOT IN (1, 2, 3)) + Person.filter(![1, 2, 3].contains(Col.id)) + + // SELECT * FROM "persons" WHERE ("age" BETWEEN 0 AND 17) + Person.filter((0..<18).contains(Col.age)) + + // SELECT * FROM "persons" WHERE ("age" BETWEEN 0 AND 17) + Person.filter((0...17).contains(Col.age)) + + // SELECT * FROM "persons" WHERE ("name" BETWEEN 'A' AND 'z') + Person.filter(("A"..."z").contains(Col.name)) + + // SELECT * FROM "persons" WHERE (("name" >= 'A') AND ("name" < 'z')) + Person.filter(("A"..<"z").contains(Col.name)) + ``` + + > :point_up: **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [String Comparison](#string-comparison) if you need more control. + + +#### SQL Functions + +- `ABS`, `AVG`, `COUNT`, `MAX`, `MIN`, `SUM`: + + Those are based on the `abs`, `average`, `count`, `max`, `min` and `sum` Swift functions: + + ```swift + // SELECT MIN("age"), MAX("age") FROM persons + Person.select(min(Col.age), max(Col.age)) + + // SELECT COUNT("name") FROM persons + Person.select(count(Col.name)) + + // SELECT COUNT(DISTINCT "name") FROM persons + Person.select(count(distinct: Col.name)) + ``` + +- `IFNULL` + + Use the Swift `??` operator: + + ```swift + // SELECT IFNULL("name", 'Anonymous') FROM persons + Person.select(Col.name ?? "Anonymous") + + // SELECT IFNULL("name", "email") FROM persons + Person.select(Col.name ?? Col.email) + ``` + +- `LOWER`, `UPPER` + + Use the `lowercaseString` and `uppercaseString` methods: + + ```swift + // SELECT * FROM persons WHERE LOWER(name) = 'arthur' + Person.filter(Col.name.lowercaseString == 'arthur) + ``` + + > :point_up: **Note**: SQLite support for case translation is limited to ASCII characters. When comparing strings as in the example abobe, you may prefer a [custom comparison function](#string-comparison). When you actually want to transform strings in an Unicode-aware fashion, use a [custom SQL function](#custom-sql-functions). + + +### Fetching from Requests + +Once you have a request, you can fetch the records at the origin of the request: + +```swift +dbQueue.inDatabase { db in + // Some request based on `Person` + let request = Person.filter(...)... + + // Fetch persons: + request.fetch(db) // DatabaseSequence + request.fetchAll(db) // [Person] + request.fetchOne(db) // Person? +} +``` + +For example: + +```swift +let persons = Person.order(name).fetchAll(db) // [Persons] +``` + +Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are: + +- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory. +- `fetch` returns a sequence that is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). The sequence fetches a new set of results each time it is iterated. + +**When the selected columns don't fit the source type**, you just have to change your target: any other type that adopts the [RowConvertible](#rowconvertible-protocol) protocol, plain [database rows](#column-values), and even [values](#values): + +```swift +dbQueue.inDatabase { db in + let request = Person.... + + // Alternative records: + Other.fetch(db, request) // DatabaseSequence + Other.fetchAll(db, request) // [Other] + Other.fetchOne(db, request) // Other? + + // Rows: + Row.fetch(db, request) // DatabaseSequence + Row.fetchAll(db, request) // [Row] + Row.fetchOne(db, request) // Row? + + // Values: + Int.fetch(db, request) // DatabaseSequence + Int.fetchAll(db, request) // [Int] + Int.fetchOne(db, request) // Int? +} +``` + +For example: + +```swift +// Int +let request = Person.select(min(Col.height)) +let minHeight = Int.fetchOne(db, request)! + +// Row +let request = Person.select(min(Col.height), max(Col.height)) +let row = Row.fetchOne(db, request)! +let minHeight = row.value(atIndex: 0) as Int +let maxHeight = row.value(atIndex: 1) as Int +``` + +See [Column Values](#column-values) for more information about the `row.value()` method. + +**Fetching records according to their primary key** is a very common task. It has a shortcut which accepts any single-column primary key: + +```swift +// SELECT * FROM persons WHERE id = 1 +Person.fetchOne(db, key: 1)! + +// SELECT * FROM persons WHERE id IN (1, 2, 3) +Person.fetchAll(db, keys: [1, 2, 3])! + +// SELECT * FROM persons WHERE isoCode = 'FR' +Country.fetchOne(db, key: "FR")! + +// SELECT * FROM countries WHERE isoCode IN ('FR', 'US') +Country.fetchAll(db, keys: ["FR", "US"])! +``` + + +### Counting with Requests + +**Requests can count:** + +```swift +dbQueue.inDatabase { db in + + // SELECT COUNT(*) FROM "persons" ... + request.fetchCount(db) // Int + + // SELECT COUNT(name) FROM "persons" ... + request.fetchCount(db, Col.name) // Int + + // SELECT COUNT(DISTINCT name) FROM "persons" ... + request.fetchCount(db, distinct: Col.name) // Int +} +``` + +You can also fetch other aggregated values (average, sum, min, max, etc.) For example: + +```swift +dbQueue.inDatabase { db in + // SELECT MIN("age") FROM "persons" WHERE email IS NOT NULL + let request = Person.select(min(Col.age)) + let minAge = Int.fetchOne(db, request) // Int? +} +``` ## Migrations @@ -1231,882 +2118,6 @@ migrator.registerMigration("AddNotNullCheckOnName", withDisabledForeignKeyChecks While your migration code runs with disabled foreign key checks, those are re-enabled and checked at the end of the migration, regardless of eventual errors. -## Database Protocols, and Record - -**GRDB provides protocols and a Record class** that help isolating database management code into database layer types, and avoid cluterring the rest of your application. - -- The [RowConvertible protocol](#rowconvertible-protocol) grants adopting types with **fetching methods**: - - ```swift - struct Person : RowConvertible { ... } - let persons = Person.fetchAll(db, "SELECT * FROM persons") - let person = let Person.fetchOne(db, key: 1)! - print(person.name) - ``` - -- The [DatabasePersistable protocol](#databasepersistable-protocol) grants adopting types with **persistence methods**: - - ```swift - struct Person : DatabasePersistable { ... } - try Person(name: "Arthur").insert(db) - ``` - -- The [Record class](#record) grants its subclasses with fetching methods, persistence methods, and **changes tracking**: - - ```swift - class Person : Record { ... } - let person = Person.fetchOne(db, key: 1)! - person.name = "Barbara" - if person.hasPersistentChangedValues { - try person.update(db) - } - ``` - - -### RowConvertible Protocol - -**The `RowConvertible` protocol grants fetching methods to any type** that can be built from a database row: - -```swift -public protocol RowConvertible { - /// Returns a value initialized from `row`. - static func fromRow(row: Row) -> Self - - /// Optional method which gives adopting types an opportunity to complete - /// their initialization after being fetched. Do not call it directly. - mutating func awakeFromFetch(row row: Row, database: Database) -} -``` - -Adopting types can be fetched just like rows: - -```swift -struct PointOfInterest : RowConvertible { - var coordinate: CLLocationCoordinate2D - var title: String? - - static func fromRow(row: Row) -> PointOfInterest { - return PointOfInterest( - coordinate: CLLocationCoordinate2DMake( - row.value(named: "latitude"), - row.value(named: "longitude")), - title: row.value(named: "title")) - } -} - -PointOfInterest.fetch(db, "SELECT ...", arguments:...) // DatabaseSequence -PointOfInterest.fetchAll(db, "SELECT ...", arguments:...) // [PointOfInterest] -PointOfInterest.fetchOne(db, "SELECT ...", arguments:...) // PointOfInterest? -``` - -See [Column Values](#column-values) for more information about the `row.value()` method, and [Fetching Rows](#fetching-rows) about the query arguments. - -Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are: - -- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory. -- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). - -> :point_up: **Note**: For performance reasons, the same row argument to `fromRow(:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. - -See also the [Record](#record) class, which builds on top of RowConvertible and adds a few extra features like persistence methods, and changes tracking. - - -#### Fetching by Key - -**Adopt the `DatabaseTableMapping` protocol** on top of `RowConvertible`: - -```swift -public protocol DatabaseTableMapping { - /// The name of the database table - static func databaseTableName() -> String -} -``` - -For example: - -```swift -// CREATE TABLE persons ( -// id INTEGER PRIMARY KEY, -// name TEXT, -// email TEXT UNIQUE COLLATE NOCASE -// ) -struct Person : RowConvertible, DatabaseTableMapping { - var id: Int64? - var name: String? - var email: String? - - static func databaseTableName() -> String { - return "persons" - } - - static func fromRow(row: Row) -> Person { - return Person( - id: row.value(named: "id"), - name: row.value(named: "name"), - email: row.value(named: "email")) - } -} -``` - -You are then granted with fetching methods based on database keys: - -```swift -Person.fetch(db, keys: ...) // DatabaseSequence -Person.fetchAll(db, keys: ...) // [Person] -Person.fetchOne(db, key: ...) // Person? -``` - -Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are: - -- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory. -- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). - -The order of sequences and arrays returned by the key-based methods is undefined. To specify the order of returned elements, use a raw SQL query. - - -**When the database table has a single column primary key**, you can fetch given key values: - -```swift -// SELECT * FROM persons WHERE id = 1 -Person.fetchOne(db, key: 1) - -// SELECT * FROM persons WHERE id IN (1,2,3) -Person.fetch(db, keys: [1,2,3]) - -// SELECT * FROM countries WHERE isoCode = 'FR' -Country.fetchOne(db, key: "FR") - -// SELECT * FROM countries WHERE isoCode IN ('FR', 'ES', 'US') -Country.fetchAll(db, keys: ["FR", "ES", "US"]) -``` - -**For multi-column primary keys and secondary keys**, use a key dictionary: - -```swift -// SELECT * FROM persons WHERE email = 'me@example.com' -Person.fetchOne(db, key: ["email": "me@example.com"]) - -// SELECT * FROM citizenships WHERE personId = 1 AND countryIsoCode = 'FR' -Citizenship.fetchOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) -``` - - -#### Optional Columns - -**Your RowConvertible type can accept rows that do not always contain the same columns.** - -This allows you to load only a subset of a table columns, or to load extra columns joined from other tables. For example: - -```swift -struct Person : RowConvertible { - let id: Int64? - let name: String - let bookCount: Int? // Only set when person is fetched from fetchAllWithBookCount() - - static func fromRow(row: Row) -> Person { - return Person( - id: row.value(named: "id"), - name: row.value(named: "name"), - bookCount: row.value(named: "bookCount")) // nil if column is missing - } - - // The returned persons have a value in their bookCount property: - static func fetchAllWithBookCount(db: Database) -> [Person] { - return fetchAll(db, - "SELECT persons.*, COUNT(books.id) AS bookCount " + - "FROM persons " + - "LEFT JOIN books ON books.ownerId = persons.id " + - "GROUP BY persons.id") - } -} -``` - -See [Column Values](#column-values) for more information about the `row.value()` method. - - -### DatabasePersistable Protocol - -**GRDB provides two protocols that let adopting types store themselves in the database:** - -```swift -public protocol MutableDatabasePersistable : DatabaseTableMapping { - /// The name of the database table (from DatabaseTableMapping) - static func databaseTableName() -> String - - /// Returns the values that should be persisted in the database. - var persistentDictionary: [String: DatabaseValueConvertible?] { get } - - /// Optional method that lets your adopting type store its rowID upon - /// successful insertion. Don't call it directly: it is called for you. - mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) -} - -public protocol DatabasePersistable : MutableDatabasePersistable { - /// Non-mutating version of the optional didInsertWithRowID(:forColumn:) - func didInsertWithRowID(rowID: Int64, forColumn column: String?) -} -``` - -That's one more protocol that one could expect, and `MutableDatabasePersistable` may sound intimidating. - -Yet, here is the rule: - -- If your type is a struct that mutates on insertion, choose `MutableDatabasePersistable`. For example, if your table has an INTEGER PRIMARY KEY, you want to store the inserted id on successful insertion. -- Otherwise, stick with `DatabasePersistable`. - -For example, the Country struct below has no INTEGER PRIMARY KEY, and is not mutated on insertion: - -```swift -// CREATE TABLE countries ( -// isoCode TEXT NOT NULL PRIMARY KEY, -// name TEXT NOT NULL -// ) -struct Country : DatabasePersistable { - let isoCode: String - let name: String - - static func databaseTableName() -> String { - return "countries" - } - - var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["isoCode": isoCode, "name": name] - } -} - -// Declare the country as `let`, since its insertion does not mutate it: -let country = Country(isoCode: "FR", name: "France") -try country.insert(db) -``` - -On the other side, the Person struct is interested in its rowID, and mutates itself on insertion: - -```swift -// CREATE TABLE persons ( -// id INTEGER PRIMARY KEY, -// name TEXT -// ) -struct Person : MutableDatabasePersistable { - let id: Int64? - let name: String? - - static func databaseTableName() -> String { - return "persons" - } - - var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["id": id, "name": name] - } - - // Update person ID upon successful insertion: - mutating func didInsertWithRowID(rowID: Int64, forColumn column: String?) { - id = rowID - } -} - -// Declare the person as `var`, since its insertion mutates it: -var person = Person(id: nil, name: "Arthur") -person.id // nil -try person.insert(db) -person.id // some value -``` - -The `persistentDictionary` property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information. - -> :point_up: **Note**: Classes should always prefer adopting `DatabasePersistable` over `MutableDatabasePersistable`, even if they mutate on insertion. This will prevent strange compiler errors when they insert an instance stored in a `let` variable (see [SR-142](https://bugs.swift.org/browse/SR-142)). - - -#### Persistence Methods - -Types that adopt DatabasePersistable or MutableDatabasePersistable are given default implementations for methods that insert, update, and delete: - -```swift -try object.insert(db) // INSERT -try object.update(db) // UPDATE -try object.save(db) // Inserts or updates -try object.delete(db) // DELETE -object.exists(db) // Bool -``` - -- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. - -- `update` can also throw a PersistenceError of type NotFound, should the update fail because there is no matching row in the database. - - When saving an object that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. - -- `delete` returns whether a database row was deleted or not. - - -#### Customizing the Persistence Methods - -Your custom type may want to perform extra work when the persistence methods are invoked. - -For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving. - -The protocol exposes *special methods* for this exact purpose: `performInsert`, `performUpdate`, `performSave`, `performDelete`, and `performExists`. - -```swift -struct Person : MutableDatabasePersistable { - var uuid: String? - - mutating func insert(db: Database) throws { - if uuid == nil { - uuid = NSUUID().UUIDString - } - try performInsert(db) - } -} - -struct Link : DatabasePersistable { - var url: NSURL - - func insert(db: Database) throws { - try validate() - try performInsert(db) - } - - func update(db: Database) throws { - try validate() - try performUpdate(db) - } - - func validate() throws { - if url.host == nil { - throw ValidationError("url must be absolute.") - } - } -} -``` - -> :point_up: **Note**: The special methods `performInsert`, `performUpdate`, etc. are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods. -> -> :point_up: **Note**: It is recommended that you do not implement your own version of the `save` method. Its default implementation forwards the job to `update` or `insert`: these are the methods that may need customization, not `save`. - - -### Record - -- [Overview](#record-overview) -- [Subclassing Record](#subclassing-record) -- [Fetching Records](#fetching-records) -- [Record Persistence Methods](#record-persistence-methods) -- [Changes Tracking](#changes-tracking) -- [Advice](#advice) - - -#### Record Overview - -**Record** is a class that wraps a table row or the result of any query, provides persistence methods, and changes tracking. It builds on top of the [RowConvertible](#rowconvertible-protocol) and [DatabasePersistable](#databasepersistable-protocol) protocols, and is designed to be subclassed. - -```swift -// Define Record subclass -class Person : Record { ... } - -try dbQueue.inDatabase { db in - // Store - let person = Person(name: "Arthur") - try person.save(db) - - // Fetch - for person in Person.fetch(db, "SELECT * FROM persons") { - print(person.name) - } -} -``` - -**Record is not a smart class.** It is no replacement for Core Data’s NSManagedObject, [Realm](https://realm.io)’s Object, or for an Active Record pattern. It does not provide any uniquing, automatic refresh, or synthesized properties. It has no knowledge of external references and table relationships, and will not generate JOIN queries for you. - -Yet, it does a few things well: - -- **Records can be used from any thread**. Not being a replacement for NSManagedObject comes with advantages. - -- **It eats any SQL query.** A Record subclass is often tied to a database table, but this is not a requirement at all. - - ```swift - let persons = Person.fetchAll(db, - "SELECT persons.*, COUNT(citizenships.isoCode) AS citizenshipsCount " + - "FROM persons " + - "LEFT JOIN citizenships ON citizenships.personId = persons.id " + - "GROUP BY persons.id") - let person = persons.first! - (person.name, person.citizenshipsCount) - ``` - -- **It provides the classic CRUD persistence methods.** All primary keys are supported (auto-incremented INTEGER PRIMARY KEY, single column, multiple columns). - - ```swift - let person = Person(...) - try person.insert(db) // INSERT - try person.update(db) // UPDATE - try person.save(db) // Inserts or updates - try person.delete(db) // DELETE - ``` - -- **It tracks changes. Real changes**: setting a column to the same value does not constitute a change. - - ```swift - person = Person.fetch... - person.name = "Barbara" - person.age = 41 - person.persistentChangedValues.keys // ["age"] - if person.hasPersistentChangedValues { - try person.save(db) - } - ``` - - -#### Subclassing Record - -**Record subclasses override the four core methods that define their relationship with the database:** - -```swift -class Record { - /// The table name - class func databaseTableName() -> String - - /// Initialize a record from a database row - required init(_ row: Row) - - /// The values persisted in the database - var persistentDictionary: [String: DatabaseValueConvertible?] - - /// Optionally update record ID after a successful insertion - func didInsertWithRowID(rowID: Int64, forColumn column: String?) -} -``` - -**Given an implementation of those core methods, you are granted with the full Record toolkit:** - -```swift -class Person { - // Copy - func copy() -> Self - - // Change Tracking - var hasPersistentChangedValues: Bool - var persistentChangedValues: [String: DatabaseValue?] - - // Persistence - func insert(db: Database) throws - func update(db: Database) throws - func save(db: Database) throws - func delete(db: Database) throws -> Bool - func exists(db: Database) -> Bool - - // Fetching - static func fetch(...) -> DatabaseSequence - static func fetchAll(...) -> [Self] - static func fetchOne(...) -> Self? - - // Events - func awakeFromFetch(row row: Row, database: Database) - func didInsertWithRowID(rowID: Int64, forColumn column: String?) - - // Description (from the CustomStringConvertible protocol) - var description: String -} -``` - -For example, given the following table: - -```sql -CREATE TABLE countries ( - isoCode TEXT NOT NULL PRIMARY KEY, - name TEXT NOT NULL -) -``` - -The Country class freely defines its properties and initializers. Here we have chosen non optional properties that directly map database columns: - -```swift -struct Country : Record { - let isoCode: String - let name: String - - init(isoCode: String, name: String) { - self.isoCode = isoCode - self.name = name - super.init() - } -``` - -Country overrides `databaseTableName()` to return the name of the table that should be used when fetching countries: - -```swift - /// The table name - override class func databaseTableName() -> String { - return "countries" - } -``` - -Country overrides `persistentDictionary` and returns a dictionary whose keys are column names, and values any `DatabaseValueConvertible` value (Bool, Int, String, NSDate, Swift enums, etc.) See [Values](#values) for more information: - -```swift - /// The values persisted in the database - override var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["isoCode": isoCode, "name": name] - } -``` - -Country overrides `init(row:)` so that it can be fetched: - -```swift - /// Initialize a Country from a row - required init(_ row: Row) { - isoCode = row.value(named: "isoCode") - name = row.value(named: "name") - super.init(row) - } -} -``` - -See [Column Values](#column-values) for more information about the `row.value()` method. - -> :point_up: **Note**: For performance reasons, the same row argument to `init(row:)` is reused for all records during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. - -The Country class is now ready: - -```swift -try dbQueue.inDatabase { db in - let unitedStates = Country.fetchOne(db, key: "US")! - let country = Country(isoCode: "FR", name: "France") - try country.insert(db) -} -``` - -When the database table has an INTEGER PRIMARY KEY, make sure to override the `didInsertWithRowID` method so that your record stores its id upon successful insertion: - -```swift -// CREATE TABLE persons ( -// id INTEGER PRIMARY KEY, -// name TEXT -// ) -class Person : Record { - let id: Int64? - let name: String? - - init(name: String) { - self.id = nil - self.name = name - super.init() - } - - // Record overrides - - /// The table name - override class func databaseTableName() -> String { - return "persons" - } - - /// The values persisted in the database - override var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["id": id, "name": name] - } - - /// Initialize a Person from a row - required init(_ row: Row) { - id = row.value(named: "id") - name = row.value(named: "name") - super.init(row) - } - - /// Update person ID after a successful insertion - override func didInsertWithRowID(rowID: Int64, forColumn column: String?) { - id = rowID - } -} - -let person = Person(...) -person.id // nil -try person.insert(db) -person.id // some value -``` - - -#### Fetching Records - -You can fetch **sequences**, **arrays**, or **single** records with raw SQL queries, or by key: - -```swift -dbQueue.inDatabase { db in - // SQL - Person.fetch(db, "SELECT ...", arguments:...) // DatabaseSequence - Person.fetchAll(db, "SELECT ...", arguments:...) // [Person] - Person.fetchOne(db, "SELECT ...", arguments:...) // Person? - - // When database table has a single column primary key - Person.fetch(db, keys: [1,2,3]) // DatabaseSequence - Person.fetchAll(db, keys: [1,2,3]) // [Person] - Person.fetchOne(db, key: 1) // Person? - - // For multi-column primary keys and secondary keys - Person.fetch(db, keys: [["name": "Joe"], ...]) // DatabaseSequence - Person.fetchAll(db, keys: [["name": "Joe"], ...]) // [Person] - Person.fetchOne(db, key: ["name": "Joe"]) // Person? -} -``` - -Both `fetch` and `fetchAll` let you iterate the full list of fetched records. The differences are: - -- `fetchAll` performs a single request, and returns an array that can be iterated on any thread. It can take a lot of memory. -- `fetch` returns a sequence that performs a new request each time it is iterated. It is memory efficient, but must be consumed in the database queue (you'll get a fatal error if you do otherwise). - -For example: - -```swift -dbQueue.inDatabase { db in - // All persons with an email ending in @example.com: - Person.fetchAll(db, - "SELECT * FROM persons WHERE email LIKE ?", - arguments: ["%@example.com"]) - - // All persons who have a single citizenship: - Person.fetch(db, - "SELECT persons.* " + - "FROM persons " + - "JOIN citizenships ON citizenships.personId = persons.id " + - "GROUP BY persons.id " + - "HAVING COUNT(citizenships.id) = 1") - - // SELECT * FROM persons WHERE id = 1 - Person.fetchOne(db, key: 1) - - // SELECT * FROM persons WHERE id IN (1,2,3) - Person.fetch(db, keys: [1,2,3]) - - // SELECT * FROM countries WHERE isoCode = 'FR' - Country.fetchOne(db, key: "FR") - - // SELECT * FROM countries WHERE isoCode IN ('FR', 'ES', 'US') - Country.fetchAll(db, keys: ["FR", "ES", "US"]) - - // SELECT * FROM persons WHERE email = 'me@example.com' - Person.fetchOne(db, key: ["email": "me@example.com"]) - - // SELECT * FROM citizenships WHERE personId = 1 AND countryIsoCode = 'FR' - Citizenship.fetchOne(db, key: ["personId": 1, "countryIsoCode": "FR"]) -} -``` - -The order of sequences and arrays returned by the key-based methods is undefined. To specify the order of returned elements, use a raw SQL query. - - -#### Record Persistence Methods - -Records can store themselves in the database through the `persistentDictionary` core property: - -```swift -class Person : Record { - /// The values stored in the database - override var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["id": id, "url": url, "name": name, "email": email] - } -} - -try dbQueue.inDatabase { db in - let person = Person(...) - try person.insert(db) // INSERT - try person.update(db) // UPDATE - try person.save(db) // Inserts or updates - try person.delete(db) // DELETE - person.exists(db) // Bool -} -``` - -- `insert` automatically sets the primary key of record whose primary key is declared as "INTEGER PRIMARY KEY", if you override the `didInsertWithRowID` method: - - ```swift - let person = Person() - person.id // nil - try person.insert(db) - person.id // some value - ``` - - Other primary keys (single or multiple columns) are not managed by GRDB: you have to manage them yourself. For example, you can override the `insert` primitive method, and generate an UUID before calling `super.insert`. - -- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling) whenever an SQLite integrity check fails. - -- `update` can also throw a PersistenceError of type NotFound, should the update fail because the record does not exist in the database. - - When saving a record that may or may not already exist in the database, prefer the `save` method: it performs the UPDATE or INSERT statement that makes sure your values are saved in the database. - -- `delete` returns whether a database row was deleted or not. - - -#### Changes Tracking - -The `update()` method always executes an UPDATE statement. When the record has not been edited, this database access is generally useless. - -Avoid it with the `hasPersistentChangedValues` property, which returns whether the record has changes that have not been saved: - -```swift -// Saves the person if it has changes that have not been saved: -if person.hasPersistentChangedValues { - try person.save(db) -} -``` - -Note that `hasPersistentChangedValues` is based on value comparison: **setting a property to the same value does not set the edited flag**. - -For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check this [sample code](https://gist.github.com/groue/dcdd3784461747874f41). - - -#### Advice - -- [Ad Hoc Subclasses](#ad-hoc-subclasses) -- [Validation](#validation) -- [Default Values](#default-values) -- [INSERT OR REPLACE](#insert-or-replace) - - -##### Ad Hoc Subclasses - -Don't hesitate deriving subclasses from your base records when you have a need for a specific query. - -For example, if a view controller needs to display a list of persons along with the number of books they own, it would be unreasonable to fetch the list of persons, and then, for each of them, fetch the number of books they own. That would perform N+1 requests, and [this is a well known issue](http://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue). - -Instead, subclass Person: - -```swift -class PersonsViewController: UITableViewController { - - // An ad-hoc Person subclass that fits the need of this view controller: - private class PersonWithBookCount : Person { - var bookCount: Int? - - required init(_ row: Row) { - bookCount = row.value(named: "bookCount") - super.init(row) - } - } -``` - -Perform a single request: - -```swift - var persons: [PersonWithBookCount]! - - override func viewWillAppear(animated: Bool) { - super.viewWillAppear(animated) - - persons = dbQueue.inDatabase { db in - PersonWithBookCount.fetchAll(db, - "SELECT persons.*, COUNT(books.id) AS bookCount " + - "FROM persons " + - "LEFT JOIN books ON books.ownerId = persons.id " + - "GROUP BY persons.id") - } - - tableView.reloadData() - } -``` - -Other application objects that expect a Person will gently accept the private subclass: - -```swift - override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { - if segue.identifier == "showPerson" { - let personVC: PersonViewController = segue... - personVC.person = persons[tableView.indexPathForSelectedRow!.row] - } - } -} -``` - - -##### Validation - -Record does not provide any built-in validation. - -You can use some external library such as [GRValidation](https://github.com/groue/GRValidation) in the update() and insert() methods: - -```swift -class Person : Record, Validable { - var name: String? - - override func update(db: Database) throws { - // Validate before update - try validate() - try super.update(db) - } - - override func insert(db: Database) throws { - // Validate before insert - try validate() - try super.insert(db) - } - - func validate() throws { - // Name should not be nil - try validate(property: "name", with: name >>> ValidationNotNil()) - } -} - -// fatal error: 'try!' expression unexpectedly raised an error: -// Invalid : name should not be nil. -try! Person(name: nil).save(db) -``` - - -##### Default Values - -**Avoid default values in table declarations.** Record doesn't know about them, and those default values won't be present in a record after it has been inserted. - -For example, avoid the table below: - -```sql -CREATE TABLE persons ( - id INTEGER PRIMARY KEY, - creationDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Avoid - ... -) -``` - -Instead, override `insert()` and provide the default value there: - -```sql -CREATE TABLE persons ( - id INTEGER PRIMARY KEY, - creationDate DATETIME NOT NULL, -- OK - ... -) -``` - -```swift -class Person : Record { - var creationDate: NSDate? - - override var persistentDictionary: [String: DatabaseValueConvertible?] { - return ["creationDate": creationDate, ...] - } - - override func insert(db: Database) throws { - if creationDate == nil { - creationDate = NSDate() - } - try super.insert(db) - } -} -``` - - -##### INSERT OR REPLACE - -**Record does not provide any API which executes a INSERT OR REPLACE query.** Instead, consider adding an ON CONFLICT clause to your table definition, and let the simple insert() method perform the eventual replacement: - -```sql -CREATE TABLE persons ( - id INTEGER PRIMARY KEY, - name TEXT UNIQUE ON CONFLICT REPLACE, - ... -) -``` - -```swift -let person = Person(name: "Arthur") -person.insert(db) // Replace any existing person named "Arthur" -``` - - ## Database Changes Observation The `TransactionObserverType` protocol lets you **observe database changes**: diff --git a/TODO.md b/TODO.md index 76c035cbf..4703c59f5 100644 --- a/TODO.md +++ b/TODO.md @@ -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: From 0bb852a51c1dca3fd3925d84964fd59fc7d0c1e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jan 2016 04:56:51 +0100 Subject: [PATCH 04/26] Project organization --- GRDB.xcodeproj/project.pbxproj | 19 +++++++++++-------- GRDB/GRDB.xcconfig | 1 - {GRDB => Support}/GRDB-Bridging.h | 0 {GRDB => Support}/GRDB.h | 0 Support/GRDB.xcconfig | 1 + {GRDB => Support}/Info.plist | 0 {GRDB => Support}/README.md | 0 {GRDB => Support}/module.modulemap | 0 8 files changed, 12 insertions(+), 9 deletions(-) delete mode 100644 GRDB/GRDB.xcconfig rename {GRDB => Support}/GRDB-Bridging.h (100%) rename {GRDB => Support}/GRDB.h (100%) create mode 100644 Support/GRDB.xcconfig rename {GRDB => Support}/Info.plist (100%) rename {GRDB => Support}/README.md (100%) rename {GRDB => Support}/module.modulemap (100%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index a7cd54269..7b2b9973c 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -457,8 +457,8 @@ 56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalRowTests.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = ../GRDB/Info.plist; sourceTree = ""; }; - DC3773F819C8CBB3004FCF85 /* GRDB.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = GRDB.h; path = ../GRDB/GRDB.h; sourceTree = ""; }; + DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + DC3773F819C8CBB3004FCF85 /* GRDB.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GRDB.h; sourceTree = ""; }; DC37740419C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; DC37744219C8DC91004FCF85 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; }; DC37744719C8F50B004FCF85 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; @@ -1010,6 +1010,7 @@ DC3773F719C8CBB3004FCF85 /* Info.plist */, ); name = "Supporting Files"; + path = ../Support; sourceTree = ""; }; /* End PBXGroup section */ @@ -1647,6 +1648,7 @@ }; 56E5D7DC1B4D3FEE00430942 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -1656,7 +1658,7 @@ DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = GRDB/Info.plist; + INFOPLIST_FILE = Support/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1670,6 +1672,7 @@ }; 56E5D7DD1B4D3FEE00430942 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -1680,7 +1683,7 @@ DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = GRDB/Info.plist; + INFOPLIST_FILE = Support/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1759,7 +1762,6 @@ }; DC37740719C8CBB3004FCF85 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; @@ -1803,7 +1805,6 @@ }; DC37740819C8CBB3004FCF85 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; @@ -1839,6 +1840,7 @@ }; DC37740A19C8CBB3004FCF85 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; CLANG_ENABLE_MODULES = YES; @@ -1847,7 +1849,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = GRDB/Info.plist; + INFOPLIST_FILE = Support/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.9; @@ -1859,6 +1861,7 @@ }; DC37740B19C8CBB3004FCF85 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; CLANG_ENABLE_MODULES = YES; @@ -1867,7 +1870,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = GRDB/Info.plist; + INFOPLIST_FILE = Support/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.9; diff --git a/GRDB/GRDB.xcconfig b/GRDB/GRDB.xcconfig deleted file mode 100644 index 88b58bf51..000000000 --- a/GRDB/GRDB.xcconfig +++ /dev/null @@ -1 +0,0 @@ -MODULEMAP_FILE = $(SRCROOT)/GRDB/module.modulemap diff --git a/GRDB/GRDB-Bridging.h b/Support/GRDB-Bridging.h similarity index 100% rename from GRDB/GRDB-Bridging.h rename to Support/GRDB-Bridging.h diff --git a/GRDB/GRDB.h b/Support/GRDB.h similarity index 100% rename from GRDB/GRDB.h rename to Support/GRDB.h diff --git a/Support/GRDB.xcconfig b/Support/GRDB.xcconfig new file mode 100644 index 000000000..c7d9ddbc0 --- /dev/null +++ b/Support/GRDB.xcconfig @@ -0,0 +1 @@ +MODULEMAP_FILE = $(SRCROOT)/Support/module.modulemap diff --git a/GRDB/Info.plist b/Support/Info.plist similarity index 100% rename from GRDB/Info.plist rename to Support/Info.plist diff --git a/GRDB/README.md b/Support/README.md similarity index 100% rename from GRDB/README.md rename to Support/README.md diff --git a/GRDB/module.modulemap b/Support/module.modulemap similarity index 100% rename from GRDB/module.modulemap rename to Support/module.modulemap From f44ae2848fc95ae704123559c3ebb82c556680c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jan 2016 05:18:29 +0100 Subject: [PATCH 05/26] Project organization Project organization README.md WIP QueryBuilder documentation README.md WIP QueryBuilder documentation WIP QueryBuilder documentation TODO.md --- .gitmodules | 8 +- DESIGN.md | 70 ------------------ GRDB Tests/Performance/SQLite.swift | 1 - GRDB.xcodeproj/project.pbxproj | 29 ++++---- GRDB.xcworkspace/contents.xcworkspacedata | 2 +- GRDB/FetchRequest/SQLSupport/SQLQuery.swift | 4 +- README.md | 68 ++++++++--------- Support/README.md | 22 ------ TODO.md | 3 - .../iOS/iOS.xcodeproj/project.pbxproj | 0 .../contents.xcworkspacedata | 0 .../Carthage/iOS/iOS/AppDelegate.swift | 0 .../AppIcon.appiconset/Contents.json | 0 .../iOS/Base.lproj/LaunchScreen.storyboard | 0 .../iOS/iOS/Base.lproj/Main.storyboard | 0 .../iOS/iOS/DetailViewController.swift | 0 .../Carthage/iOS/iOS/Info.plist | 0 .../iOS/iOS/MasterViewController.swift | 0 .../Carthage/iOS/iOS/Person.swift | 0 .../Carthage/iOS/iOSTests/Info.plist | 0 .../Carthage/iOS/iOSTests/iOSTests.swift | 0 .../Carthage/iOS/iOSUITests/Info.plist | 0 .../Carthage/iOS/iOSUITests/iOSUITests.swift | 0 .../ManagedDataControllerTests.swift | 0 .../Experimental/MappingTests.swift | 0 .../GRDBPerformanceTests-Bridging.h | 0 .../GRDBProfiling.xcodeproj/project.pbxproj | 0 .../contents.xcworkspacedata | 0 .../GRDBProfiling/AppDelegate.swift | 0 .../AppIcon.appiconset/Contents.json | 0 .../GRDBProfiling/Base.lproj/Main.storyboard | 0 .../GRDBProfiling/GRDBProfiling/Info.plist | 0 .../GRDBProfiling/ProfilingDatabase.sqlite | Bin .../GRDBProfiling/ViewController.swift | 0 {GRDB Tests => Tests}/GRDBTestCase.swift | 0 {GRDB Tests => Tests}/Info.plist | 0 .../Performance/FetchNamedValuesTests.swift | 0 .../FetchPositionalValuesTests.swift | 0 .../Performance/FetchRecordTests.swift | 0 .../Performance/InsertNamedValuesTests.swift | 0 .../InsertPositionalValuesTests.swift | 0 .../Performance/InsertRecordTests.swift | 0 .../PerformanceCoreDataTests.sqlite | Bin .../PerformanceModel.xcdatamodel/contents | 0 .../Performance/PerformanceTests.sqlite | Bin .../Performance/PerformanceTests.swift | 0 Tests/Performance/SQLite.swift | 1 + {GRDB Tests => Tests}/Performance/fmdb | 0 .../Private/NSDataMemoryTests.swift | 0 .../Core/Collation/CollationTests.swift | 0 .../Core/Concurrency/ConcurrencyTests.swift | 0 .../Public/Core/Database/DatabaseTests.swift | 0 .../Core/Database/InMemoryDatabaseTests.swift | 0 .../DatabaseError/DatabaseErrorTests.swift | 0 .../DatabaseValue/DatabaseValueTests.swift | 0 .../DatabaseTimestampTests.swift | 0 .../DatabaseValueConversionTests.swift | 0 .../DatabaseValueConvertibleFetchTests.swift | 0 ...atabaseValueConvertibleSubclassTests.swift | 0 .../NSDataTests.swift | 0 .../RawRepresentableTests.swift | 0 .../Public/Core/Function/FunctionTests.swift | 0 .../Persistable/MutablePersistableTests.swift | 0 .../Core/Persistable/PersistableTests.swift | 0 .../Public/Core/Row/DetachedRowTests.swift | 0 .../Public/Core/Row/DictionaryRowTests.swift | 0 .../Public/Core/Row/MetalRowTests.swift | 0 .../Public/Core/Row/RowConvertibleTests.swift | 0 .../SQLiteStatementConversionTests.swift | 0 ...SQLiteStatementConvertibleFetchTests.swift | 0 .../Core/Statement/SelectStatementTests.swift | 0 .../Statement/StatementArgumentsTests.swift | 0 .../Core/Statement/UpdateStatementTests.swift | 0 .../TransactionObserverTests.swift | 0 .../Public/CoreGraphics/CGFloatTests.swift | 0 {GRDB Tests => Tests}/Public/CrashTests.swift | 0 .../FetchRequest/FetchRequestTests.swift | 0 .../Record+FetchRequestTests.swift | 0 .../RowConvertible+FetchRequestTests.swift | 0 .../Public/FetchRequest/SQLSupportTests.swift | 0 .../TableMapping+FetchRequestTests.swift | 0 .../Foundation/DatabaseCoderTests.swift | 0 .../Foundation/NSDateComponentsTests.swift | 0 .../Public/Foundation/NSDateTests.swift | 0 .../Foundation/Row+FoundationTests.swift | 0 .../StatementArguments+FoundationTests.swift | 0 .../Migrations/DatabaseMigratorTests.swift | 0 .../Record/MinimalPrimaryKeyRowIDTests.swift | 0 .../Record/MinimalPrimaryKeySingleTests.swift | 0 .../Record/PrimaryKeyMultipleTests.swift | 0 .../Public/Record/PrimaryKeyNoneTests.swift | 0 .../Public/Record/PrimaryKeyRowIDTests.swift | 0 .../Public/Record/PrimaryKeySingleTests.swift | 0 ...leWithReplaceConflictResolutionTests.swift | 0 .../Record/RecordAwakeFromFetchTests.swift | 0 .../Public/Record/RecordCopyTests.swift | 0 .../Record/RecordDescriptionTests.swift | 0 .../Public/Record/RecordEditedTests.swift | 0 .../Public/Record/RecordFetchTests.swift | 0 .../Record/RecordInitializersTests.swift | 0 .../Public/Record/RecordSubClassTests.swift | 0 .../RecordWithColumnNameManglingTests.swift | 0 {GRDB Tests => Tests}/README.md | 4 +- 103 files changed, 59 insertions(+), 153 deletions(-) delete mode 100644 DESIGN.md delete mode 160000 GRDB Tests/Performance/SQLite.swift delete mode 100644 Support/README.md rename {GRDB Tests => Tests}/Carthage/iOS/iOS.xcodeproj/project.pbxproj (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOS/AppDelegate.swift (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOS/Assets.xcassets/AppIcon.appiconset/Contents.json (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOS/Base.lproj/LaunchScreen.storyboard (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOS/Base.lproj/Main.storyboard (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOS/DetailViewController.swift (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOS/Info.plist (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOS/MasterViewController.swift (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOS/Person.swift (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOSTests/Info.plist (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOSTests/iOSTests.swift (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOSUITests/Info.plist (100%) rename {GRDB Tests => Tests}/Carthage/iOS/iOSUITests/iOSUITests.swift (100%) rename {GRDB Tests => Tests}/Experimental/ManagedDataControllerTests.swift (100%) rename {GRDB Tests => Tests}/Experimental/MappingTests.swift (100%) rename {GRDB Tests => Tests}/GRDBPerformanceTests-Bridging.h (100%) rename {GRDB Tests => Tests}/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj (100%) rename {GRDB Tests => Tests}/GRDBProfiling/GRDBProfiling.xcodeproj/project.xcworkspace/contents.xcworkspacedata (100%) rename {GRDB Tests => Tests}/GRDBProfiling/GRDBProfiling/AppDelegate.swift (100%) rename {GRDB Tests => Tests}/GRDBProfiling/GRDBProfiling/Assets.xcassets/AppIcon.appiconset/Contents.json (100%) rename {GRDB Tests => Tests}/GRDBProfiling/GRDBProfiling/Base.lproj/Main.storyboard (100%) rename {GRDB Tests => Tests}/GRDBProfiling/GRDBProfiling/Info.plist (100%) rename {GRDB Tests => Tests}/GRDBProfiling/GRDBProfiling/ProfilingDatabase.sqlite (100%) rename {GRDB Tests => Tests}/GRDBProfiling/GRDBProfiling/ViewController.swift (100%) rename {GRDB Tests => Tests}/GRDBTestCase.swift (100%) rename {GRDB Tests => Tests}/Info.plist (100%) rename {GRDB Tests => Tests}/Performance/FetchNamedValuesTests.swift (100%) rename {GRDB Tests => Tests}/Performance/FetchPositionalValuesTests.swift (100%) rename {GRDB Tests => Tests}/Performance/FetchRecordTests.swift (100%) rename {GRDB Tests => Tests}/Performance/InsertNamedValuesTests.swift (100%) rename {GRDB Tests => Tests}/Performance/InsertPositionalValuesTests.swift (100%) rename {GRDB Tests => Tests}/Performance/InsertRecordTests.swift (100%) rename {GRDB Tests => Tests}/Performance/PerformanceCoreDataTests.sqlite (100%) rename {GRDB Tests => Tests}/Performance/PerformanceModel.xcdatamodeld/PerformanceModel.xcdatamodel/contents (100%) rename {GRDB Tests => Tests}/Performance/PerformanceTests.sqlite (100%) rename {GRDB Tests => Tests}/Performance/PerformanceTests.swift (100%) create mode 160000 Tests/Performance/SQLite.swift rename {GRDB Tests => Tests}/Performance/fmdb (100%) rename {GRDB Tests => Tests}/Private/NSDataMemoryTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Collation/CollationTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Concurrency/ConcurrencyTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Database/DatabaseTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Database/InMemoryDatabaseTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/DatabaseError/DatabaseErrorTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/DatabaseValue/DatabaseValueTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/DatabaseValueConvertible/DatabaseTimestampTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/DatabaseValueConvertible/DatabaseValueConversionTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleFetchTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleSubclassTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/DatabaseValueConvertible/NSDataTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Function/FunctionTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Persistable/MutablePersistableTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Persistable/PersistableTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Row/DetachedRowTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Row/DictionaryRowTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Row/MetalRowTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Row/RowConvertibleTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/SQLiteStatementConvertible/SQLiteStatementConversionTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Statement/SelectStatementTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Statement/StatementArgumentsTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/Statement/UpdateStatementTests.swift (100%) rename {GRDB Tests => Tests}/Public/Core/TransactionObserver/TransactionObserverTests.swift (100%) rename {GRDB Tests => Tests}/Public/CoreGraphics/CGFloatTests.swift (100%) rename {GRDB Tests => Tests}/Public/CrashTests.swift (100%) rename {GRDB Tests => Tests}/Public/FetchRequest/FetchRequestTests.swift (100%) rename {GRDB Tests => Tests}/Public/FetchRequest/Record+FetchRequestTests.swift (100%) rename {GRDB Tests => Tests}/Public/FetchRequest/RowConvertible+FetchRequestTests.swift (100%) rename {GRDB Tests => Tests}/Public/FetchRequest/SQLSupportTests.swift (100%) rename {GRDB Tests => Tests}/Public/FetchRequest/TableMapping+FetchRequestTests.swift (100%) rename {GRDB Tests => Tests}/Public/Foundation/DatabaseCoderTests.swift (100%) rename {GRDB Tests => Tests}/Public/Foundation/NSDateComponentsTests.swift (100%) rename {GRDB Tests => Tests}/Public/Foundation/NSDateTests.swift (100%) rename {GRDB Tests => Tests}/Public/Foundation/Row+FoundationTests.swift (100%) rename {GRDB Tests => Tests}/Public/Foundation/StatementArguments+FoundationTests.swift (100%) rename {GRDB Tests => Tests}/Public/Migrations/DatabaseMigratorTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/MinimalPrimaryKeyRowIDTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/MinimalPrimaryKeySingleTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/PrimaryKeyMultipleTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/PrimaryKeyNoneTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/PrimaryKeyRowIDTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/PrimaryKeySingleTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/RecordAwakeFromFetchTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/RecordCopyTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/RecordDescriptionTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/RecordEditedTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/RecordFetchTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/RecordInitializersTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/RecordSubClassTests.swift (100%) rename {GRDB Tests => Tests}/Public/Record/RecordWithColumnNameManglingTests.swift (100%) rename {GRDB Tests => Tests}/README.md (91%) diff --git a/.gitmodules b/.gitmodules index 1dc870c5e..532218518 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ -[submodule "GRDB Tests/Performance/fmdb"] - path = GRDB Tests/Performance/fmdb +[submodule "Tests/Performance/fmdb"] + path = Tests/Performance/fmdb url = https://github.com/ccgus/fmdb.git -[submodule "GRDB Tests/Performance/SQLite.swift"] - path = GRDB Tests/Performance/SQLite.swift +[submodule "Tests/Performance/SQLite.swift"] + path = Tests/Performance/SQLite.swift url = https://github.com/stephencelis/SQLite.swift.git diff --git a/DESIGN.md b/DESIGN.md deleted file mode 100644 index 5b0ee3598..000000000 --- a/DESIGN.md +++ /dev/null @@ -1,70 +0,0 @@ -The Design of GRDB.swift -======================== - -More than caveats or defects, there are a few glitches, or surprises in the GRDB.swift API. We try to explain them here. The interested readers can take them as Swift challenges! - - -### Why must we provide query arguments in an Array, when Swift provides variadic method parameters? - -I admit that the array argument below looks odd: - -```swift -Int.fetch(db, - "SELECT COUNT(*) FROM persons WHERE name = ?", - arguments: ["Arthur"]) -``` - -Well, GRDB provides three fetching methods for each fetchable type: - -```swift -// Row -Row.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence -Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row] -Row.fetchOne(db, "SELECT ...", arguments: ...) // Row? - -// DatabaseValueConvertible -String.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence -String.fetchAll(db, "SELECT ...", arguments: ...) // [String] -String.fetchOne(db, "SELECT ...", arguments: ...) // String? - -// Record (via RowConvertible) -Person.fetch(db, "SELECT ...", arguments: ...) // DatabaseSequence -Person.fetchAll(db, "SELECT ...", arguments: ...) // [Person] -Person.fetchOne(db, "SELECT ...", arguments: ...) // Person? -``` - -The `arguments` parameter type is StatementArguments, which is both ArrayLiteralConvertible and DictionaryLiteralConvertible, so that you can write both: - -```swift -Int.fetch(db, - "SELECT COUNT(*) FROM persons WHERE name = ?", - arguments: ["Arthur"]) -Int.fetch(db, - "SELECT COUNT(*) FROM persons WHERE name = :name", - arguments: ["name": "Arthur"]) -``` - -Without StatementArguments, that number would be six (three for Array and three for Dictionary), or even nine (three more for variadic parameters). I prefer limiting the API footprint: three methods per fetchable type is just quite fine. - -Moreover, one of my pet peeves with SQLite is that it is a pain to write an SQL query with the `IN` operator. SQLite won't natively feed a single `?` placeholder with an array of values, and this forces users to build their own `IN(?,?,?,...)` SQL snippets: - -```swift -// Let's load persons whose name is in names: -let names = ["Arthur", "Barbara"] -let questionMarks = Array(count: names.count, repeatedValue: "?").joinWithSeparator(",") // OMG Swift come on -let sql = "SELECT * FROM persons WHERE name IN (\(questionMarks))" -let persons = Person.fetchAll(db, sql, arguments: StatementArguments(names)) -``` - -I wish that in a future version of GRDB we can write instead: - -```swift -Person.fetchAll(db, - "SELECT * FROM persons WHERE name IN (?)", - arguments: [["Arthur", "Barbara"]]) // one array argument -Person.fetchAll(db, - "SELECT * FROM persons WHERE name = ? OR name = ?", - arguments: ["Arthur", "Barbara"]) // two string arguments -``` - -This will require to distinguish arrays of values from arrays of arrays of values. diff --git a/GRDB Tests/Performance/SQLite.swift b/GRDB Tests/Performance/SQLite.swift deleted file mode 160000 index 5638f1f79..000000000 --- a/GRDB Tests/Performance/SQLite.swift +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5638f1f791e60713fdee06f267107f21a5ad9b59 diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 7b2b9973c..6d0a194ed 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -931,7 +931,7 @@ path = Experimental; sourceTree = ""; }; - DC10500F19C904DD00D8CA30 /* GRDB Tests */ = { + DC10500F19C904DD00D8CA30 /* Tests */ = { isa = PBXGroup; children = ( 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, @@ -942,7 +942,7 @@ DC37740319C8CBB3004FCF85 /* Supporting Files */, 5614DEEE1BA9D6F9003163B3 /* Frameworks */, ); - path = "GRDB Tests"; + path = Tests; sourceTree = ""; }; DC3773E919C8CBB3004FCF85 = { @@ -952,7 +952,7 @@ DC37744719C8F50B004FCF85 /* README.md */, 56E1524B1B43FD5B00EE27AA /* TODO.md */, DC37742D19C8CC90004FCF85 /* GRDB */, - DC10500F19C904DD00D8CA30 /* GRDB Tests */, + DC10500F19C904DD00D8CA30 /* Tests */, DC3773F419C8CBB3004FCF85 /* Products */, ); indentWidth = 4; @@ -980,7 +980,6 @@ 56BB862D1BA98933001F9168 /* GRDBPerformanceTests-Bridging.h */, ); name = "Supporting Files"; - path = "../GRDB Tests"; sourceTree = ""; }; DC37742D19C8CC90004FCF85 /* GRDB */ = { @@ -1588,13 +1587,13 @@ COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "GRDB Tests/Info.plist"; + INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_OBJC_BRIDGING_HEADER = "GRDB Tests/GRDBPerformanceTests-Bridging.h"; + SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBPerformanceTests-Bridging.h"; }; name = Debug; }; @@ -1605,13 +1604,13 @@ COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "GRDB Tests/Info.plist"; + INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_OBJC_BRIDGING_HEADER = "GRDB Tests/GRDBPerformanceTests-Bridging.h"; + SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBPerformanceTests-Bridging.h"; }; name = Release; }; @@ -1621,7 +1620,7 @@ COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "GRDB Tests/Info.plist"; + INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; @@ -1637,7 +1636,7 @@ COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "GRDB Tests/Info.plist"; + INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; @@ -1702,13 +1701,12 @@ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "GRDB Tests/Info.plist"; + INFOPLIST_FILE = Tests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOSTests; PRODUCT_NAME = GRDBTests; SDKROOT = iphoneos; - SWIFT_OBJC_BRIDGING_HEADER = "GRDB Tests/GRDBTests-Bridging.h"; }; name = Debug; }; @@ -1719,13 +1717,12 @@ COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "GRDB Tests/Info.plist"; + INFOPLIST_FILE = Tests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOSTests; PRODUCT_NAME = GRDBTests; SDKROOT = iphoneos; - SWIFT_OBJC_BRIDGING_HEADER = "GRDB Tests/GRDBTests-Bridging.h"; }; name = Release; }; @@ -1735,7 +1732,7 @@ COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "GRDB Tests/Info.plist"; + INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; @@ -1751,7 +1748,7 @@ COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "GRDB Tests/Info.plist"; + INFOPLIST_FILE = Tests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; diff --git a/GRDB.xcworkspace/contents.xcworkspacedata b/GRDB.xcworkspace/contents.xcworkspacedata index 9c44df313..745a11ebd 100644 --- a/GRDB.xcworkspace/contents.xcworkspacedata +++ b/GRDB.xcworkspace/contents.xcworkspacedata @@ -21,7 +21,7 @@ location = "group:GRDB.xcodeproj"> + location = "group:Tests/GRDBProfiling/GRDBProfiling.xcodeproj"> diff --git a/GRDB/FetchRequest/SQLSupport/SQLQuery.swift b/GRDB/FetchRequest/SQLSupport/SQLQuery.swift index ce5aa1189..639db4daa 100644 --- a/GRDB/FetchRequest/SQLSupport/SQLQuery.swift +++ b/GRDB/FetchRequest/SQLSupport/SQLQuery.swift @@ -589,9 +589,11 @@ extension SQLLiteral : _DerivedSQLExpressionType { /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct SQLColumn { - let name: String let sourceName: String? + /// The name of the column + public let name: String + /// Initializes a column given its name. public init(_ name: String) { self.name = name diff --git a/README.md b/README.md index 9dc6caa68..bb430a704 100644 --- a/README.md +++ b/README.md @@ -1301,7 +1301,7 @@ You can now jump to: ### RowConvertible Protocol -**The `RowConvertible` protocol grants fetching methods to any type** that can be built from a database row: +**The RowConvertible protocol grants fetching methods to any type** that can be built from a database row: ```swift public protocol RowConvertible { @@ -1339,38 +1339,15 @@ See [Column Values](#column-values) for more information about the `row.value()` > :point_up: **Note**: For performance reasons, the same row argument to `fromRow(:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. -RowConvertible allows adopting types to be fetched: +RowConvertible allows adopting types to be fetched from SQL queries: -- From SQL queries: +```swift +PointOfInterest.fetch(db, "SELECT ...", arguments:...) // DatabaseSequence +PointOfInterest.fetchAll(db, "SELECT ...", arguments:...) // [PointOfInterest] +PointOfInterest.fetchOne(db, "SELECT ...", arguments:...) // PointOfInterest? +``` - ```swift - PointOfInterest.fetch(db, "SELECT ...", arguments:...) // DatabaseSequence - PointOfInterest.fetchAll(db, "SELECT ...", arguments:...) // [PointOfInterest] - PointOfInterest.fetchOne(db, "SELECT ...", arguments:...) // PointOfInterest? - ``` - - See [Fetching Rows](#fetching-rows) for more information about the query arguments. - -- From primary key: - - ```swift - PointOfInterest.fetch(db, keys: ...) // DatabaseSequence - PointOfInterest.fetchAll(db, keys: ...) // [PointOfInterest] - PointOfInterest.fetchOne(db, key: ...) // PointOfInterest? - ``` - - Any single-column primary key is OK: - - ```swift - // SELECT * FROM pointOfInterests WHERE id IN (1, 2, 3) - PointOfInterest.fetchAll(db, keys: [1, 2, 3]) - - // SELECT * FROM pointOfInterests WHERE id = 1 - PointOfInterest.fetchOne(db, key: 1) - - // SELECT * FROM countries WHERE isoCode = 'FR' - Country.fetchOne(db, key: "FR") - ``` +See [Fetching Rows](#fetching-rows) for more information about the query arguments. Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are: @@ -1380,7 +1357,7 @@ Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. Th ### TableMapping Protocol -**Adopt the `TableMapping` protocol** on top of `RowConvertible`, and you are granted with the full [query interface](#the-query-interface). +**Adopt the TableMapping protocol** on top of [RowConvertible](#rowconvertible-protocol), and you are granted with the full [query interface](#the-query-interface). ```swift public protocol TableMapping { @@ -1396,12 +1373,37 @@ extension PointOfInterest : TableMapping { return "pointOfInterests" } } +``` +Adopting types can be fetched using the [query interface](#the-query-interface): + +```swift let paris = dbQueue.inDatabase { db in PointOfInterest.filter(name == "Paris").fetchOne(db)? } ``` +You can also fetch records according to their primary key: + +```swift +PointOfInterest.fetch(db, keys: ...) // DatabaseSequence +PointOfInterest.fetchAll(db, keys: ...) // [PointOfInterest] +PointOfInterest.fetchOne(db, key: ...) // PointOfInterest? +``` + +Any single-column primary key is OK: + +```swift +// SELECT * FROM pointOfInterests WHERE id IN (1, 2, 3) +PointOfInterest.fetchAll(db, keys: [1, 2, 3]) + +// SELECT * FROM pointOfInterests WHERE id = 1 +PointOfInterest.fetchOne(db, key: 1) + +// SELECT * FROM countries WHERE isoCode = 'FR' +Country.fetchOne(db, key: "FR") +``` + ### Persistable Protocol @@ -1622,7 +1624,7 @@ class PointOfInterest : Record { #### Changes Tracking -**[Record](#record-class) provides changes tracking.** +**The [Record](#record-class) class provides changes tracking.** The `update()` method always executes an UPDATE statement. When the record has not been edited, this database access is generally useless. diff --git a/Support/README.md b/Support/README.md deleted file mode 100644 index 592474efb..000000000 --- a/Support/README.md +++ /dev/null @@ -1,22 +0,0 @@ -GRDB Sources -============ - -- [Core](Core): - - The core of the SQLite API: database, configuration, statements, rows, values, and basic protocols. - -- [Foundation](Foundation): - - The GRDB additions that support Foundation types: NSDate, NSDateComponents, NSNumber, etc. - -- [Migrations](Migrations): - - Ditto - -- [Record](Record): - - The Record class. - -- [Swift](Swift): - - The GRDB additions that support the Swift standard library: Int, String, Bool, enums, etc. diff --git a/TODO.md b/TODO.md index 4703c59f5..8fae2df8d 100644 --- a/TODO.md +++ b/TODO.md @@ -1,10 +1,7 @@ - [ ] How to have robust single writer/several readers? - [ ] 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 diff --git a/GRDB Tests/Carthage/iOS/iOS.xcodeproj/project.pbxproj b/Tests/Carthage/iOS/iOS.xcodeproj/project.pbxproj similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS.xcodeproj/project.pbxproj rename to Tests/Carthage/iOS/iOS.xcodeproj/project.pbxproj diff --git a/GRDB Tests/Carthage/iOS/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/Carthage/iOS/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Tests/Carthage/iOS/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata diff --git a/GRDB Tests/Carthage/iOS/iOS/AppDelegate.swift b/Tests/Carthage/iOS/iOS/AppDelegate.swift similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS/AppDelegate.swift rename to Tests/Carthage/iOS/iOS/AppDelegate.swift diff --git a/GRDB Tests/Carthage/iOS/iOS/Assets.xcassets/AppIcon.appiconset/Contents.json b/Tests/Carthage/iOS/iOS/Assets.xcassets/AppIcon.appiconset/Contents.json similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS/Assets.xcassets/AppIcon.appiconset/Contents.json rename to Tests/Carthage/iOS/iOS/Assets.xcassets/AppIcon.appiconset/Contents.json diff --git a/GRDB Tests/Carthage/iOS/iOS/Base.lproj/LaunchScreen.storyboard b/Tests/Carthage/iOS/iOS/Base.lproj/LaunchScreen.storyboard similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS/Base.lproj/LaunchScreen.storyboard rename to Tests/Carthage/iOS/iOS/Base.lproj/LaunchScreen.storyboard diff --git a/GRDB Tests/Carthage/iOS/iOS/Base.lproj/Main.storyboard b/Tests/Carthage/iOS/iOS/Base.lproj/Main.storyboard similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS/Base.lproj/Main.storyboard rename to Tests/Carthage/iOS/iOS/Base.lproj/Main.storyboard diff --git a/GRDB Tests/Carthage/iOS/iOS/DetailViewController.swift b/Tests/Carthage/iOS/iOS/DetailViewController.swift similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS/DetailViewController.swift rename to Tests/Carthage/iOS/iOS/DetailViewController.swift diff --git a/GRDB Tests/Carthage/iOS/iOS/Info.plist b/Tests/Carthage/iOS/iOS/Info.plist similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS/Info.plist rename to Tests/Carthage/iOS/iOS/Info.plist diff --git a/GRDB Tests/Carthage/iOS/iOS/MasterViewController.swift b/Tests/Carthage/iOS/iOS/MasterViewController.swift similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS/MasterViewController.swift rename to Tests/Carthage/iOS/iOS/MasterViewController.swift diff --git a/GRDB Tests/Carthage/iOS/iOS/Person.swift b/Tests/Carthage/iOS/iOS/Person.swift similarity index 100% rename from GRDB Tests/Carthage/iOS/iOS/Person.swift rename to Tests/Carthage/iOS/iOS/Person.swift diff --git a/GRDB Tests/Carthage/iOS/iOSTests/Info.plist b/Tests/Carthage/iOS/iOSTests/Info.plist similarity index 100% rename from GRDB Tests/Carthage/iOS/iOSTests/Info.plist rename to Tests/Carthage/iOS/iOSTests/Info.plist diff --git a/GRDB Tests/Carthage/iOS/iOSTests/iOSTests.swift b/Tests/Carthage/iOS/iOSTests/iOSTests.swift similarity index 100% rename from GRDB Tests/Carthage/iOS/iOSTests/iOSTests.swift rename to Tests/Carthage/iOS/iOSTests/iOSTests.swift diff --git a/GRDB Tests/Carthage/iOS/iOSUITests/Info.plist b/Tests/Carthage/iOS/iOSUITests/Info.plist similarity index 100% rename from GRDB Tests/Carthage/iOS/iOSUITests/Info.plist rename to Tests/Carthage/iOS/iOSUITests/Info.plist diff --git a/GRDB Tests/Carthage/iOS/iOSUITests/iOSUITests.swift b/Tests/Carthage/iOS/iOSUITests/iOSUITests.swift similarity index 100% rename from GRDB Tests/Carthage/iOS/iOSUITests/iOSUITests.swift rename to Tests/Carthage/iOS/iOSUITests/iOSUITests.swift diff --git a/GRDB Tests/Experimental/ManagedDataControllerTests.swift b/Tests/Experimental/ManagedDataControllerTests.swift similarity index 100% rename from GRDB Tests/Experimental/ManagedDataControllerTests.swift rename to Tests/Experimental/ManagedDataControllerTests.swift diff --git a/GRDB Tests/Experimental/MappingTests.swift b/Tests/Experimental/MappingTests.swift similarity index 100% rename from GRDB Tests/Experimental/MappingTests.swift rename to Tests/Experimental/MappingTests.swift diff --git a/GRDB Tests/GRDBPerformanceTests-Bridging.h b/Tests/GRDBPerformanceTests-Bridging.h similarity index 100% rename from GRDB Tests/GRDBPerformanceTests-Bridging.h rename to Tests/GRDBPerformanceTests-Bridging.h diff --git a/GRDB Tests/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj b/Tests/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj similarity index 100% rename from GRDB Tests/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj rename to Tests/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj diff --git a/GRDB Tests/GRDBProfiling/GRDBProfiling.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/GRDBProfiling/GRDBProfiling.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 100% rename from GRDB Tests/GRDBProfiling/GRDBProfiling.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Tests/GRDBProfiling/GRDBProfiling.xcodeproj/project.xcworkspace/contents.xcworkspacedata diff --git a/GRDB Tests/GRDBProfiling/GRDBProfiling/AppDelegate.swift b/Tests/GRDBProfiling/GRDBProfiling/AppDelegate.swift similarity index 100% rename from GRDB Tests/GRDBProfiling/GRDBProfiling/AppDelegate.swift rename to Tests/GRDBProfiling/GRDBProfiling/AppDelegate.swift diff --git a/GRDB Tests/GRDBProfiling/GRDBProfiling/Assets.xcassets/AppIcon.appiconset/Contents.json b/Tests/GRDBProfiling/GRDBProfiling/Assets.xcassets/AppIcon.appiconset/Contents.json similarity index 100% rename from GRDB Tests/GRDBProfiling/GRDBProfiling/Assets.xcassets/AppIcon.appiconset/Contents.json rename to Tests/GRDBProfiling/GRDBProfiling/Assets.xcassets/AppIcon.appiconset/Contents.json diff --git a/GRDB Tests/GRDBProfiling/GRDBProfiling/Base.lproj/Main.storyboard b/Tests/GRDBProfiling/GRDBProfiling/Base.lproj/Main.storyboard similarity index 100% rename from GRDB Tests/GRDBProfiling/GRDBProfiling/Base.lproj/Main.storyboard rename to Tests/GRDBProfiling/GRDBProfiling/Base.lproj/Main.storyboard diff --git a/GRDB Tests/GRDBProfiling/GRDBProfiling/Info.plist b/Tests/GRDBProfiling/GRDBProfiling/Info.plist similarity index 100% rename from GRDB Tests/GRDBProfiling/GRDBProfiling/Info.plist rename to Tests/GRDBProfiling/GRDBProfiling/Info.plist diff --git a/GRDB Tests/GRDBProfiling/GRDBProfiling/ProfilingDatabase.sqlite b/Tests/GRDBProfiling/GRDBProfiling/ProfilingDatabase.sqlite similarity index 100% rename from GRDB Tests/GRDBProfiling/GRDBProfiling/ProfilingDatabase.sqlite rename to Tests/GRDBProfiling/GRDBProfiling/ProfilingDatabase.sqlite diff --git a/GRDB Tests/GRDBProfiling/GRDBProfiling/ViewController.swift b/Tests/GRDBProfiling/GRDBProfiling/ViewController.swift similarity index 100% rename from GRDB Tests/GRDBProfiling/GRDBProfiling/ViewController.swift rename to Tests/GRDBProfiling/GRDBProfiling/ViewController.swift diff --git a/GRDB Tests/GRDBTestCase.swift b/Tests/GRDBTestCase.swift similarity index 100% rename from GRDB Tests/GRDBTestCase.swift rename to Tests/GRDBTestCase.swift diff --git a/GRDB Tests/Info.plist b/Tests/Info.plist similarity index 100% rename from GRDB Tests/Info.plist rename to Tests/Info.plist diff --git a/GRDB Tests/Performance/FetchNamedValuesTests.swift b/Tests/Performance/FetchNamedValuesTests.swift similarity index 100% rename from GRDB Tests/Performance/FetchNamedValuesTests.swift rename to Tests/Performance/FetchNamedValuesTests.swift diff --git a/GRDB Tests/Performance/FetchPositionalValuesTests.swift b/Tests/Performance/FetchPositionalValuesTests.swift similarity index 100% rename from GRDB Tests/Performance/FetchPositionalValuesTests.swift rename to Tests/Performance/FetchPositionalValuesTests.swift diff --git a/GRDB Tests/Performance/FetchRecordTests.swift b/Tests/Performance/FetchRecordTests.swift similarity index 100% rename from GRDB Tests/Performance/FetchRecordTests.swift rename to Tests/Performance/FetchRecordTests.swift diff --git a/GRDB Tests/Performance/InsertNamedValuesTests.swift b/Tests/Performance/InsertNamedValuesTests.swift similarity index 100% rename from GRDB Tests/Performance/InsertNamedValuesTests.swift rename to Tests/Performance/InsertNamedValuesTests.swift diff --git a/GRDB Tests/Performance/InsertPositionalValuesTests.swift b/Tests/Performance/InsertPositionalValuesTests.swift similarity index 100% rename from GRDB Tests/Performance/InsertPositionalValuesTests.swift rename to Tests/Performance/InsertPositionalValuesTests.swift diff --git a/GRDB Tests/Performance/InsertRecordTests.swift b/Tests/Performance/InsertRecordTests.swift similarity index 100% rename from GRDB Tests/Performance/InsertRecordTests.swift rename to Tests/Performance/InsertRecordTests.swift diff --git a/GRDB Tests/Performance/PerformanceCoreDataTests.sqlite b/Tests/Performance/PerformanceCoreDataTests.sqlite similarity index 100% rename from GRDB Tests/Performance/PerformanceCoreDataTests.sqlite rename to Tests/Performance/PerformanceCoreDataTests.sqlite diff --git a/GRDB Tests/Performance/PerformanceModel.xcdatamodeld/PerformanceModel.xcdatamodel/contents b/Tests/Performance/PerformanceModel.xcdatamodeld/PerformanceModel.xcdatamodel/contents similarity index 100% rename from GRDB Tests/Performance/PerformanceModel.xcdatamodeld/PerformanceModel.xcdatamodel/contents rename to Tests/Performance/PerformanceModel.xcdatamodeld/PerformanceModel.xcdatamodel/contents diff --git a/GRDB Tests/Performance/PerformanceTests.sqlite b/Tests/Performance/PerformanceTests.sqlite similarity index 100% rename from GRDB Tests/Performance/PerformanceTests.sqlite rename to Tests/Performance/PerformanceTests.sqlite diff --git a/GRDB Tests/Performance/PerformanceTests.swift b/Tests/Performance/PerformanceTests.swift similarity index 100% rename from GRDB Tests/Performance/PerformanceTests.swift rename to Tests/Performance/PerformanceTests.swift diff --git a/Tests/Performance/SQLite.swift b/Tests/Performance/SQLite.swift new file mode 160000 index 000000000..d304343f5 --- /dev/null +++ b/Tests/Performance/SQLite.swift @@ -0,0 +1 @@ +Subproject commit d304343f5e9243d17197365d4ce8249e9b7ce84e diff --git a/GRDB Tests/Performance/fmdb b/Tests/Performance/fmdb similarity index 100% rename from GRDB Tests/Performance/fmdb rename to Tests/Performance/fmdb diff --git a/GRDB Tests/Private/NSDataMemoryTests.swift b/Tests/Private/NSDataMemoryTests.swift similarity index 100% rename from GRDB Tests/Private/NSDataMemoryTests.swift rename to Tests/Private/NSDataMemoryTests.swift diff --git a/GRDB Tests/Public/Core/Collation/CollationTests.swift b/Tests/Public/Core/Collation/CollationTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Collation/CollationTests.swift rename to Tests/Public/Core/Collation/CollationTests.swift diff --git a/GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift b/Tests/Public/Core/Concurrency/ConcurrencyTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift rename to Tests/Public/Core/Concurrency/ConcurrencyTests.swift diff --git a/GRDB Tests/Public/Core/Database/DatabaseTests.swift b/Tests/Public/Core/Database/DatabaseTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Database/DatabaseTests.swift rename to Tests/Public/Core/Database/DatabaseTests.swift diff --git a/GRDB Tests/Public/Core/Database/InMemoryDatabaseTests.swift b/Tests/Public/Core/Database/InMemoryDatabaseTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Database/InMemoryDatabaseTests.swift rename to Tests/Public/Core/Database/InMemoryDatabaseTests.swift diff --git a/GRDB Tests/Public/Core/DatabaseError/DatabaseErrorTests.swift b/Tests/Public/Core/DatabaseError/DatabaseErrorTests.swift similarity index 100% rename from GRDB Tests/Public/Core/DatabaseError/DatabaseErrorTests.swift rename to Tests/Public/Core/DatabaseError/DatabaseErrorTests.swift diff --git a/GRDB Tests/Public/Core/DatabaseValue/DatabaseValueTests.swift b/Tests/Public/Core/DatabaseValue/DatabaseValueTests.swift similarity index 100% rename from GRDB Tests/Public/Core/DatabaseValue/DatabaseValueTests.swift rename to Tests/Public/Core/DatabaseValue/DatabaseValueTests.swift diff --git a/GRDB Tests/Public/Core/DatabaseValueConvertible/DatabaseTimestampTests.swift b/Tests/Public/Core/DatabaseValueConvertible/DatabaseTimestampTests.swift similarity index 100% rename from GRDB Tests/Public/Core/DatabaseValueConvertible/DatabaseTimestampTests.swift rename to Tests/Public/Core/DatabaseValueConvertible/DatabaseTimestampTests.swift diff --git a/GRDB Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConversionTests.swift b/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConversionTests.swift similarity index 100% rename from GRDB Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConversionTests.swift rename to Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConversionTests.swift diff --git a/GRDB Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleFetchTests.swift b/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleFetchTests.swift similarity index 100% rename from GRDB Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleFetchTests.swift rename to Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleFetchTests.swift diff --git a/GRDB Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleSubclassTests.swift b/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleSubclassTests.swift similarity index 100% rename from GRDB Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleSubclassTests.swift rename to Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConvertibleSubclassTests.swift diff --git a/GRDB Tests/Public/Core/DatabaseValueConvertible/NSDataTests.swift b/Tests/Public/Core/DatabaseValueConvertible/NSDataTests.swift similarity index 100% rename from GRDB Tests/Public/Core/DatabaseValueConvertible/NSDataTests.swift rename to Tests/Public/Core/DatabaseValueConvertible/NSDataTests.swift diff --git a/GRDB Tests/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift b/Tests/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift similarity index 100% rename from GRDB Tests/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift rename to Tests/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift diff --git a/GRDB Tests/Public/Core/Function/FunctionTests.swift b/Tests/Public/Core/Function/FunctionTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Function/FunctionTests.swift rename to Tests/Public/Core/Function/FunctionTests.swift diff --git a/GRDB Tests/Public/Core/Persistable/MutablePersistableTests.swift b/Tests/Public/Core/Persistable/MutablePersistableTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Persistable/MutablePersistableTests.swift rename to Tests/Public/Core/Persistable/MutablePersistableTests.swift diff --git a/GRDB Tests/Public/Core/Persistable/PersistableTests.swift b/Tests/Public/Core/Persistable/PersistableTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Persistable/PersistableTests.swift rename to Tests/Public/Core/Persistable/PersistableTests.swift diff --git a/GRDB Tests/Public/Core/Row/DetachedRowTests.swift b/Tests/Public/Core/Row/DetachedRowTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Row/DetachedRowTests.swift rename to Tests/Public/Core/Row/DetachedRowTests.swift diff --git a/GRDB Tests/Public/Core/Row/DictionaryRowTests.swift b/Tests/Public/Core/Row/DictionaryRowTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Row/DictionaryRowTests.swift rename to Tests/Public/Core/Row/DictionaryRowTests.swift diff --git a/GRDB Tests/Public/Core/Row/MetalRowTests.swift b/Tests/Public/Core/Row/MetalRowTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Row/MetalRowTests.swift rename to Tests/Public/Core/Row/MetalRowTests.swift diff --git a/GRDB Tests/Public/Core/Row/RowConvertibleTests.swift b/Tests/Public/Core/Row/RowConvertibleTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Row/RowConvertibleTests.swift rename to Tests/Public/Core/Row/RowConvertibleTests.swift diff --git a/GRDB Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConversionTests.swift b/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConversionTests.swift similarity index 100% rename from GRDB Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConversionTests.swift rename to Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConversionTests.swift diff --git a/GRDB Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift b/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift similarity index 100% rename from GRDB Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift rename to Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift diff --git a/GRDB Tests/Public/Core/Statement/SelectStatementTests.swift b/Tests/Public/Core/Statement/SelectStatementTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Statement/SelectStatementTests.swift rename to Tests/Public/Core/Statement/SelectStatementTests.swift diff --git a/GRDB Tests/Public/Core/Statement/StatementArgumentsTests.swift b/Tests/Public/Core/Statement/StatementArgumentsTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Statement/StatementArgumentsTests.swift rename to Tests/Public/Core/Statement/StatementArgumentsTests.swift diff --git a/GRDB Tests/Public/Core/Statement/UpdateStatementTests.swift b/Tests/Public/Core/Statement/UpdateStatementTests.swift similarity index 100% rename from GRDB Tests/Public/Core/Statement/UpdateStatementTests.swift rename to Tests/Public/Core/Statement/UpdateStatementTests.swift diff --git a/GRDB Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift b/Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift similarity index 100% rename from GRDB Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift rename to Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift diff --git a/GRDB Tests/Public/CoreGraphics/CGFloatTests.swift b/Tests/Public/CoreGraphics/CGFloatTests.swift similarity index 100% rename from GRDB Tests/Public/CoreGraphics/CGFloatTests.swift rename to Tests/Public/CoreGraphics/CGFloatTests.swift diff --git a/GRDB Tests/Public/CrashTests.swift b/Tests/Public/CrashTests.swift similarity index 100% rename from GRDB Tests/Public/CrashTests.swift rename to Tests/Public/CrashTests.swift diff --git a/GRDB Tests/Public/FetchRequest/FetchRequestTests.swift b/Tests/Public/FetchRequest/FetchRequestTests.swift similarity index 100% rename from GRDB Tests/Public/FetchRequest/FetchRequestTests.swift rename to Tests/Public/FetchRequest/FetchRequestTests.swift diff --git a/GRDB Tests/Public/FetchRequest/Record+FetchRequestTests.swift b/Tests/Public/FetchRequest/Record+FetchRequestTests.swift similarity index 100% rename from GRDB Tests/Public/FetchRequest/Record+FetchRequestTests.swift rename to Tests/Public/FetchRequest/Record+FetchRequestTests.swift diff --git a/GRDB Tests/Public/FetchRequest/RowConvertible+FetchRequestTests.swift b/Tests/Public/FetchRequest/RowConvertible+FetchRequestTests.swift similarity index 100% rename from GRDB Tests/Public/FetchRequest/RowConvertible+FetchRequestTests.swift rename to Tests/Public/FetchRequest/RowConvertible+FetchRequestTests.swift diff --git a/GRDB Tests/Public/FetchRequest/SQLSupportTests.swift b/Tests/Public/FetchRequest/SQLSupportTests.swift similarity index 100% rename from GRDB Tests/Public/FetchRequest/SQLSupportTests.swift rename to Tests/Public/FetchRequest/SQLSupportTests.swift diff --git a/GRDB Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift b/Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift similarity index 100% rename from GRDB Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift rename to Tests/Public/FetchRequest/TableMapping+FetchRequestTests.swift diff --git a/GRDB Tests/Public/Foundation/DatabaseCoderTests.swift b/Tests/Public/Foundation/DatabaseCoderTests.swift similarity index 100% rename from GRDB Tests/Public/Foundation/DatabaseCoderTests.swift rename to Tests/Public/Foundation/DatabaseCoderTests.swift diff --git a/GRDB Tests/Public/Foundation/NSDateComponentsTests.swift b/Tests/Public/Foundation/NSDateComponentsTests.swift similarity index 100% rename from GRDB Tests/Public/Foundation/NSDateComponentsTests.swift rename to Tests/Public/Foundation/NSDateComponentsTests.swift diff --git a/GRDB Tests/Public/Foundation/NSDateTests.swift b/Tests/Public/Foundation/NSDateTests.swift similarity index 100% rename from GRDB Tests/Public/Foundation/NSDateTests.swift rename to Tests/Public/Foundation/NSDateTests.swift diff --git a/GRDB Tests/Public/Foundation/Row+FoundationTests.swift b/Tests/Public/Foundation/Row+FoundationTests.swift similarity index 100% rename from GRDB Tests/Public/Foundation/Row+FoundationTests.swift rename to Tests/Public/Foundation/Row+FoundationTests.swift diff --git a/GRDB Tests/Public/Foundation/StatementArguments+FoundationTests.swift b/Tests/Public/Foundation/StatementArguments+FoundationTests.swift similarity index 100% rename from GRDB Tests/Public/Foundation/StatementArguments+FoundationTests.swift rename to Tests/Public/Foundation/StatementArguments+FoundationTests.swift diff --git a/GRDB Tests/Public/Migrations/DatabaseMigratorTests.swift b/Tests/Public/Migrations/DatabaseMigratorTests.swift similarity index 100% rename from GRDB Tests/Public/Migrations/DatabaseMigratorTests.swift rename to Tests/Public/Migrations/DatabaseMigratorTests.swift diff --git a/GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift b/Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift similarity index 100% rename from GRDB Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift rename to Tests/Public/Record/MinimalPrimaryKeyRowIDTests.swift diff --git a/GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift b/Tests/Public/Record/MinimalPrimaryKeySingleTests.swift similarity index 100% rename from GRDB Tests/Public/Record/MinimalPrimaryKeySingleTests.swift rename to Tests/Public/Record/MinimalPrimaryKeySingleTests.swift diff --git a/GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift b/Tests/Public/Record/PrimaryKeyMultipleTests.swift similarity index 100% rename from GRDB Tests/Public/Record/PrimaryKeyMultipleTests.swift rename to Tests/Public/Record/PrimaryKeyMultipleTests.swift diff --git a/GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift b/Tests/Public/Record/PrimaryKeyNoneTests.swift similarity index 100% rename from GRDB Tests/Public/Record/PrimaryKeyNoneTests.swift rename to Tests/Public/Record/PrimaryKeyNoneTests.swift diff --git a/GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift b/Tests/Public/Record/PrimaryKeyRowIDTests.swift similarity index 100% rename from GRDB Tests/Public/Record/PrimaryKeyRowIDTests.swift rename to Tests/Public/Record/PrimaryKeyRowIDTests.swift diff --git a/GRDB Tests/Public/Record/PrimaryKeySingleTests.swift b/Tests/Public/Record/PrimaryKeySingleTests.swift similarity index 100% rename from GRDB Tests/Public/Record/PrimaryKeySingleTests.swift rename to Tests/Public/Record/PrimaryKeySingleTests.swift diff --git a/GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift similarity index 100% rename from GRDB Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift rename to Tests/Public/Record/PrimaryKeySingleWithReplaceConflictResolutionTests.swift diff --git a/GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift b/Tests/Public/Record/RecordAwakeFromFetchTests.swift similarity index 100% rename from GRDB Tests/Public/Record/RecordAwakeFromFetchTests.swift rename to Tests/Public/Record/RecordAwakeFromFetchTests.swift diff --git a/GRDB Tests/Public/Record/RecordCopyTests.swift b/Tests/Public/Record/RecordCopyTests.swift similarity index 100% rename from GRDB Tests/Public/Record/RecordCopyTests.swift rename to Tests/Public/Record/RecordCopyTests.swift diff --git a/GRDB Tests/Public/Record/RecordDescriptionTests.swift b/Tests/Public/Record/RecordDescriptionTests.swift similarity index 100% rename from GRDB Tests/Public/Record/RecordDescriptionTests.swift rename to Tests/Public/Record/RecordDescriptionTests.swift diff --git a/GRDB Tests/Public/Record/RecordEditedTests.swift b/Tests/Public/Record/RecordEditedTests.swift similarity index 100% rename from GRDB Tests/Public/Record/RecordEditedTests.swift rename to Tests/Public/Record/RecordEditedTests.swift diff --git a/GRDB Tests/Public/Record/RecordFetchTests.swift b/Tests/Public/Record/RecordFetchTests.swift similarity index 100% rename from GRDB Tests/Public/Record/RecordFetchTests.swift rename to Tests/Public/Record/RecordFetchTests.swift diff --git a/GRDB Tests/Public/Record/RecordInitializersTests.swift b/Tests/Public/Record/RecordInitializersTests.swift similarity index 100% rename from GRDB Tests/Public/Record/RecordInitializersTests.swift rename to Tests/Public/Record/RecordInitializersTests.swift diff --git a/GRDB Tests/Public/Record/RecordSubClassTests.swift b/Tests/Public/Record/RecordSubClassTests.swift similarity index 100% rename from GRDB Tests/Public/Record/RecordSubClassTests.swift rename to Tests/Public/Record/RecordSubClassTests.swift diff --git a/GRDB Tests/Public/Record/RecordWithColumnNameManglingTests.swift b/Tests/Public/Record/RecordWithColumnNameManglingTests.swift similarity index 100% rename from GRDB Tests/Public/Record/RecordWithColumnNameManglingTests.swift rename to Tests/Public/Record/RecordWithColumnNameManglingTests.swift diff --git a/GRDB Tests/README.md b/Tests/README.md similarity index 91% rename from GRDB Tests/README.md rename to Tests/README.md index 9b642f2b0..7a9058a7d 100644 --- a/GRDB Tests/README.md +++ b/Tests/README.md @@ -1,5 +1,5 @@ -GRDB Tests -========== +Tests +===== - [Carthage](Carthage) From e2eb73e546483a24b1685666b167419a51f7eb59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jan 2016 08:56:34 +0100 Subject: [PATCH 06/26] CHANGELOG.md --- CHANGELOG.md | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b5dd45bfa..21fe91ec8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,22 @@ Release Notes ============= +## Next Release + +**New** + +- The query interface lets you write pure Swift instead of SQL ([documentation](#https://github.com/groue/GRDB.swift/#the-query-interface)): + + ```swift + let wines = Wine.filter(origin == "Burgundy").order(price).fetchAll(db) + ``` + +**Breaking Changes** + +- `DatabasePersistable` and `MutableDatabasePersistable` protocols have been renamed `Persistable` and `MutablePersistable` ([documentation](#https://github.com/groue/GRDB.swift/#persistable-protocol)) +- `DatabaseTableMapping` protocol has been renamed `TableMapping` ([documentation](#https://github.com/groue/GRDB.swift/#tablemapping-protocol)) + + ## 0.41.0 Released January 17, 2016 @@ -137,7 +153,7 @@ Released December 28, 2015 **Breaking Changes** - Methods that return prepared statements can now throw errors ([documentation](https://github.com/groue/GRDB.swift#prepared-statements)). -- `Row(dictionary:)` has been renamed `Row(_:)` ([documentation](https://github.com/groue/GRDB.swift#convenience-rows)). +- `Row(dictionary:)` has been renamed `Row(_:)`. - `RowConvertible.awakeFromFetch()` now takes a database argument ([documentation](https://github.com/groue/GRDB.swift#rowconvertible-protocol)). @@ -155,7 +171,7 @@ Methods names that did not match [Swift 3 API Design Guidelines](https://swift.o **Breaking Changes** -Record ([documentation](https://github.com/groue/GRDB.swift#record)): +Record ([documentation](https://github.com/groue/GRDB.swift#record-class)): - `Record.storedDatabaseDictionary` has been renamed `persistentDictionary`. - `Record.reload()` has been removed. You have to provide your own implementation, should you need reloading. @@ -171,7 +187,7 @@ Row: DatabasePersistable: -- `DatabasePersistable.storedDatabaseDictionary` has been renamed `persistentDictionary` ([documentation](https://github.com/groue/GRDB.swift#databasepersistable-protocol)). +- `DatabasePersistable.storedDatabaseDictionary` has been renamed `persistentDictionary` ([documentation](https://github.com/groue/GRDB.swift#persistable-protocol)). DatabaseValue: From 4c03aad795dc190c36772c06edba9d3fa08ff853 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jan 2016 08:57:23 +0100 Subject: [PATCH 07/26] CHANGELOG.md --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21fe91ec8..2dbf0180e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Release Notes **New** -- The query interface lets you write pure Swift instead of SQL ([documentation](#https://github.com/groue/GRDB.swift/#the-query-interface)): +- The query interface lets you write pure Swift instead of SQL ([documentation](https://github.com/groue/GRDB.swift/#the-query-interface)): ```swift let wines = Wine.filter(origin == "Burgundy").order(price).fetchAll(db) @@ -13,8 +13,8 @@ Release Notes **Breaking Changes** -- `DatabasePersistable` and `MutableDatabasePersistable` protocols have been renamed `Persistable` and `MutablePersistable` ([documentation](#https://github.com/groue/GRDB.swift/#persistable-protocol)) -- `DatabaseTableMapping` protocol has been renamed `TableMapping` ([documentation](#https://github.com/groue/GRDB.swift/#tablemapping-protocol)) +- `DatabasePersistable` and `MutableDatabasePersistable` protocols have been renamed `Persistable` and `MutablePersistable` ([documentation](https://github.com/groue/GRDB.swift/#persistable-protocol)) +- `DatabaseTableMapping` protocol has been renamed `TableMapping` ([documentation](https://github.com/groue/GRDB.swift/#tablemapping-protocol)) ## 0.41.0 From cae8e000837abbb71576fb8f36c132c6dbb1d874 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jan 2016 13:11:21 +0100 Subject: [PATCH 08/26] Project organization --- {Support => GRDB}/GRDB-Bridging.h | 0 {Support => GRDB}/GRDB.h | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {Support => GRDB}/GRDB-Bridging.h (100%) rename {Support => GRDB}/GRDB.h (100%) diff --git a/Support/GRDB-Bridging.h b/GRDB/GRDB-Bridging.h similarity index 100% rename from Support/GRDB-Bridging.h rename to GRDB/GRDB-Bridging.h diff --git a/Support/GRDB.h b/GRDB/GRDB.h similarity index 100% rename from Support/GRDB.h rename to GRDB/GRDB.h From 9f3577b8b9b813210f04caaade56fa647031acbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jan 2016 13:14:41 +0100 Subject: [PATCH 09/26] v0.42.0 --- CHANGELOG.md | 4 +++- GRDB.swift.podspec | 4 ++-- README.md | 10 +++++----- Support/Info.plist | 2 +- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2dbf0180e..fe411401f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,9 @@ Release Notes ============= -## Next Release +## 0.42.0 + +Released January 28, 2016 **New** diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index a66e28d4b..d3352ce30 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '0.41.0' + s.version = '0.42.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'Versatile SQLite toolkit for Swift.' s.homepage = 'https://github.com/groue/GRDB.swift' @@ -11,7 +11,7 @@ Pod::Spec.new do |s| s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.9' s.requires_arc = true - s.module_map = 'GRDB/module.modulemap' + s.module_map = 'Support/module.modulemap' s.framework = 'Foundation' s.library = 'sqlite3' end diff --git a/README.md b/README.md index bb430a704..09b112a19 100644 --- a/README.md +++ b/README.md @@ -5,14 +5,14 @@ GRDB.swift is an SQLite toolkit for Swift 2. It provides an SQL API and application tools. -**January 17, 2016: GRDB.swift 0.41.0 is out** ([changelog](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +**January 28, 2016: GRDB.swift 0.42.0 is out** ([changelog](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. **Requirements**: iOS 7.0+ / OSX 10.9+, Xcode 7+ ### Documentation -- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.41.0/index.html) (on cocoadocs.org) +- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.42.0/index.html) (on cocoadocs.org) - [Installation](#installation) - [SQLite API](#sqlite-api): SQL & SQLite - [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies. @@ -39,7 +39,7 @@ To use GRDB.swift with Cocoapods, specify in your Podfile: source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '~> 0.41.0' +pod 'GRDB.swift', '~> 0.42.0' ``` @@ -50,7 +50,7 @@ pod 'GRDB.swift', '~> 0.41.0' To use GRDB.swift with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" ~> 0.41.0 +github "groue/GRDB.swift" ~> 0.42.0 ``` @@ -170,7 +170,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.41.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.42.0/Structs/Configuration.html) and [Concurrency](#concurrency) for more details. > :bowtie: **Tip**: see [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift) for a sample code that sets up a GRDB database. diff --git a/Support/Info.plist b/Support/Info.plist index e67eaf5bf..09fec46ed 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.41.0 + 0.42.0 CFBundleSignature ???? CFBundleVersion From dc1a16054b89ad5d3af285444f7eb5f79af4932f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jan 2016 13:18:28 +0100 Subject: [PATCH 10/26] README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 09b112a19..b5536f86c 100644 --- a/README.md +++ b/README.md @@ -1603,6 +1603,7 @@ class PointOfInterest : Record { self.coordinate = CLLocationCoordinate2DMake( row.value(named: "latitude"), row.value(named: "longitude")) + super.init(row) } /// The values persisted in the database From be4104c5cfaf93bd583bb17a0315d6058a04a246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jan 2016 13:34:49 +0100 Subject: [PATCH 11/26] Fixed path to Objective-C headers --- GRDB.xcodeproj/project.pbxproj | 112 ++++++++------------------------- 1 file changed, 26 insertions(+), 86 deletions(-) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 6d0a194ed..d7ad0cdd8 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -230,7 +230,7 @@ isa = PBXContainerItemProxy; containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; proxyType = 1; - remoteGlobalIDString = DC7253AB1B52ADEB009B38B1; + remoteGlobalIDString = EE247B3B1C3F3ED000AE3E12; remoteInfo = "SQLite Mac"; }; 560C97D31C0E22D300BF8471 /* PBXContainerItemProxy */ = { @@ -254,13 +254,6 @@ remoteGlobalIDString = DC2B29E21B26F718001C60EA; remoteInfo = "SQLite iOS"; }; - 56CA220C1BB414FE009A04C5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = DC2B29EC1B26F718001C60EA; - remoteInfo = "SQLite iOS Tests"; - }; 56CA220E1BB414FE009A04C5 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; @@ -268,46 +261,11 @@ remoteGlobalIDString = DC7253AC1B52ADEB009B38B1; remoteInfo = "SQLite Mac"; }; - 56CA22101BB414FE009A04C5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = DC7253B51B52ADEC009B38B1; - remoteInfo = "SQLite Mac Tests"; - }; - 56CA22121BB414FE009A04C5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = DCE7BB7A1B7434F90040D364; - remoteInfo = "SQLiteCipher iOS"; - }; - 56CA22141BB414FE009A04C5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = DCE7BB831B7434F90040D364; - remoteInfo = "SQLiteCipher iOS Tests"; - }; - 56CA22161BB414FE009A04C5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = DCE7BBB01B7438610040D364; - remoteInfo = "SQLiteCipher Mac"; - }; - 56CA22181BB414FE009A04C5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = DCE7BBB91B7438620040D364; - remoteInfo = "SQLiteCipher Mac Tests"; - }; 56CA22271BB4165C009A04C5 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; proxyType = 1; - remoteGlobalIDString = DC2B29E11B26F718001C60EA; + remoteGlobalIDString = EE247AD21C3F04ED00AE3E12; remoteInfo = "SQLite iOS"; }; 56E5D7D51B4D3FEE00430942 /* PBXContainerItemProxy */ = { @@ -324,6 +282,20 @@ remoteGlobalIDString = DC3773F219C8CBB3004FCF85; remoteInfo = GRDBOSX; }; + 56E667C91C5A422500D48792 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = EE247ADD1C3F04ED00AE3E12; + remoteInfo = "SQLiteTests iOS"; + }; + 56E667CB1C5A422500D48792 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = EE247B451C3F3ED000AE3E12; + remoteInfo = "SQLiteTests Mac"; + }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ @@ -455,10 +427,10 @@ 56FC78641BBAEB8C00CA1285 /* MappingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MappingTests.swift; sourceTree = ""; }; 56FC78651BBAEB8C00CA1285 /* ManagedDataControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ManagedDataControllerTests.swift; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* MetalRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MetalRowTests.swift; sourceTree = ""; }; - DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; + DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "../GRDB/GRDB-Bridging.h"; sourceTree = ""; }; DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - DC3773F819C8CBB3004FCF85 /* GRDB.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GRDB.h; sourceTree = ""; }; + DC3773F819C8CBB3004FCF85 /* GRDB.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = GRDB.h; path = ../GRDB/GRDB.h; sourceTree = ""; }; DC37740419C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; DC37744219C8DC91004FCF85 /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; }; DC37744719C8F50B004FCF85 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; @@ -874,13 +846,9 @@ isa = PBXGroup; children = ( 56CA220B1BB414FE009A04C5 /* SQLite.framework */, - 56CA220D1BB414FE009A04C5 /* SQLite iOS Tests.xctest */, + 56E667CA1C5A422500D48792 /* SQLiteTests iOS.xctest */, 56CA220F1BB414FE009A04C5 /* SQLite.framework */, - 56CA22111BB414FE009A04C5 /* SQLite Mac Tests.xctest */, - 56CA22131BB414FE009A04C5 /* SQLiteCipher.framework */, - 56CA22151BB414FE009A04C5 /* SQLiteCipher iOS Tests.xctest */, - 56CA22171BB414FE009A04C5 /* SQLiteCipher.framework */, - 56CA22191BB414FE009A04C5 /* SQLiteCipher Mac Tests.xctest */, + 56E667CC1C5A422500D48792 /* SQLiteTests Mac.xctest */, ); name = Products; sourceTree = ""; @@ -1207,13 +1175,6 @@ remoteRef = 56CA220A1BB414FE009A04C5 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56CA220D1BB414FE009A04C5 /* SQLite iOS Tests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = "SQLite iOS Tests.xctest"; - remoteRef = 56CA220C1BB414FE009A04C5 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; 56CA220F1BB414FE009A04C5 /* SQLite.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; @@ -1221,39 +1182,18 @@ remoteRef = 56CA220E1BB414FE009A04C5 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56CA22111BB414FE009A04C5 /* SQLite Mac Tests.xctest */ = { + 56E667CA1C5A422500D48792 /* SQLiteTests iOS.xctest */ = { isa = PBXReferenceProxy; fileType = wrapper.cfbundle; - path = "SQLite Mac Tests.xctest"; - remoteRef = 56CA22101BB414FE009A04C5 /* PBXContainerItemProxy */; + path = "SQLiteTests iOS.xctest"; + remoteRef = 56E667C91C5A422500D48792 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56CA22131BB414FE009A04C5 /* SQLiteCipher.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = SQLiteCipher.framework; - remoteRef = 56CA22121BB414FE009A04C5 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56CA22151BB414FE009A04C5 /* SQLiteCipher iOS Tests.xctest */ = { + 56E667CC1C5A422500D48792 /* SQLiteTests Mac.xctest */ = { isa = PBXReferenceProxy; fileType = wrapper.cfbundle; - path = "SQLiteCipher iOS Tests.xctest"; - remoteRef = 56CA22141BB414FE009A04C5 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56CA22171BB414FE009A04C5 /* SQLiteCipher.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = SQLiteCipher.framework; - remoteRef = 56CA22161BB414FE009A04C5 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56CA22191BB414FE009A04C5 /* SQLiteCipher Mac Tests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = "SQLiteCipher Mac Tests.xctest"; - remoteRef = 56CA22181BB414FE009A04C5 /* PBXContainerItemProxy */; + path = "SQLiteTests Mac.xctest"; + remoteRef = 56E667CB1C5A422500D48792 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXReferenceProxy section */ From 042c0509d6852f917c672acb2e610edf350158ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 28 Jan 2016 19:55:54 +0100 Subject: [PATCH 12/26] README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b5536f86c..cad591484 100644 --- a/README.md +++ b/README.md @@ -1975,7 +1975,7 @@ dbQueue.inDatabase { db in For example: ```swift -let persons = Person.order(name).fetchAll(db) // [Persons] +let persons = Person.all().fetchAll(db) // [Persons] ``` Both `fetch` and `fetchAll` let you iterate the full list of fetched objects. The differences are: @@ -2061,7 +2061,7 @@ You can also fetch other aggregated values (average, sum, min, max, etc.) For ex ```swift dbQueue.inDatabase { db in - // SELECT MIN("age") FROM "persons" WHERE email IS NOT NULL + // SELECT MIN("age") FROM "persons" let request = Person.select(min(Col.age)) let minAge = Int.fetchOne(db, request) // Int? } From 58929684d2c735765fd5e9e5cdd31cc92c7efdf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 06:39:53 +0100 Subject: [PATCH 13/26] README.md --- README.md | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 82 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index cad591484..965700cc8 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,85 @@ It provides an SQL API and application tools. **Requirements**: iOS 7.0+ / OSX 10.9+, Xcode 7+ +### Usage + +```swift +import GRDB + +// SQL usage + +let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") +try dbQueue.inDatabase { db in + try db.execute( + "CREATE TABLE pointOfInterests (" + + "id INTEGER PRIMARY KEY, " + + "title TEXT, " + + "favorite BOOLEAN NOT NULL, " + + "latitude DOUBLE NOT NULL, " + + "longitude DOUBLE NOT NULL" + + ")") + + let parisId = try db.execute( + "INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " + + "VALUES (:title, :favorite, :latitude, :longitude)", + arguments: [ + "title": "Paris", + "favorite": true, + "latitude": 48.85341, + "longitude": 2.3488, + ]).insertedRowID + + for row in Row.fetch(db, "SELECT * FROM pointOfInterests") { + let title: String = row.value(named: "title") + let favorite: Bool = row.value(named: "favorite") + print(title, favorite) + } +} + + +// Database protocols and Records + +struct PointOfInterest { + var id: Int64? + var title: String? + var favorite: Bool + var coordinate: CLLocationCoordinate2D +} + +extension PointOfInterest { + // snip: conformance to database protocols +} + +try dbQueue.inDatabase { db in + // INSERT INTO "pointOfInterests" ... + var berlin = PointOfInterest( + id: nil, + title: "Berlin", + favorite: false, + coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) + try berlin.insert(db) + print(berlin.id) + + // UPDATE "pointOfInterests" ... + berlin.favorite = true + try berlin.update(db) + + // SELECT * FROM "pointOfInterests" + for poi in PointOfInterest.all().fetch(db) { + print(poi.title, poi.coordinate) + } +} + +let title = SQLColumn("title") +let favorite = SQLColumn("favorite") + +let favorites = dbQueue.inDatabase { db in + // SELECT * FROM "pointOfInterests" WHERE "favorite" ORDER BY "title" + PointOfInterest.filter(favorite).order(title).fetchAll(db) +} +``` + + ### Documentation - [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.42.0/index.html) (on cocoadocs.org) @@ -1598,9 +1677,9 @@ class PointOfInterest : Record { /// Initialize from a database row required init(_ row: Row) { - self.id = row.value(named: "id") - self.title = row.value(named: "title") - self.coordinate = CLLocationCoordinate2DMake( + id = row.value(named: "id") + title = row.value(named: "title") + coordinate = CLLocationCoordinate2DMake( row.value(named: "latitude"), row.value(named: "longitude")) super.init(row) From f5dc639211202e648c175e36b39d74e51276a936 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 06:43:31 +0100 Subject: [PATCH 14/26] README.md --- README.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/README.md b/README.md index 965700cc8..4456e1d27 100644 --- a/README.md +++ b/README.md @@ -61,11 +61,7 @@ extension PointOfInterest { try dbQueue.inDatabase { db in // INSERT INTO "pointOfInterests" ... - var berlin = PointOfInterest( - id: nil, - title: "Berlin", - favorite: false, - coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) + var berlin = PointOfInterest(id: nil, title: "Berlin", favorite: false, coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) try berlin.insert(db) print(berlin.id) From f4def1966be4b0cf37d248783ceb7a1bd8a7d6b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 06:47:24 +0100 Subject: [PATCH 15/26] README.md --- README.md | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 4456e1d27..7944f0460 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,9 @@ extension PointOfInterest { // snip: conformance to database protocols } +let title = SQLColumn("title") +let favorite = SQLColumn("favorite") + try dbQueue.inDatabase { db in // INSERT INTO "pointOfInterests" ... var berlin = PointOfInterest(id: nil, title: "Berlin", favorite: false, coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) @@ -69,21 +72,14 @@ try dbQueue.inDatabase { db in berlin.favorite = true try berlin.update(db) - // SELECT * FROM "pointOfInterests" - for poi in PointOfInterest.all().fetch(db) { - print(poi.title, poi.coordinate) - } -} - -let title = SQLColumn("title") -let favorite = SQLColumn("favorite") - -let favorites = dbQueue.inDatabase { db in // SELECT * FROM "pointOfInterests" WHERE "favorite" ORDER BY "title" - PointOfInterest.filter(favorite).order(title).fetchAll(db) + let favorites = PointOfInterest.filter(favorite).order(title).fetchAll(db) + + // Fetch from SQL + let pois = PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests") } ``` - + ### Documentation From 943247187c21131492d1ebec136d2166d8ed2c47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 06:49:11 +0100 Subject: [PATCH 16/26] README.md --- README.md | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 7944f0460..5a580afa4 100644 --- a/README.md +++ b/README.md @@ -30,13 +30,8 @@ try dbQueue.inDatabase { db in let parisId = try db.execute( "INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " + - "VALUES (:title, :favorite, :latitude, :longitude)", - arguments: [ - "title": "Paris", - "favorite": true, - "latitude": 48.85341, - "longitude": 2.3488, - ]).insertedRowID + "VALUES (?, ?, ?, ?)", + arguments: ["Paris", true, 48.85341, 2.3488,]).insertedRowID for row in Row.fetch(db, "SELECT * FROM pointOfInterests") { let title: String = row.value(named: "title") From 7b5415ad0d856cfd95f0d4554237ab274279cf12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 06:51:47 +0100 Subject: [PATCH 17/26] README.md --- README.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 5a580afa4..588d0a177 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,6 @@ extension PointOfInterest { // snip: conformance to database protocols } -let title = SQLColumn("title") -let favorite = SQLColumn("favorite") - try dbQueue.inDatabase { db in // INSERT INTO "pointOfInterests" ... var berlin = PointOfInterest(id: nil, title: "Berlin", favorite: false, coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) @@ -67,12 +64,19 @@ try dbQueue.inDatabase { db in berlin.favorite = true try berlin.update(db) - // SELECT * FROM "pointOfInterests" WHERE "favorite" ORDER BY "title" - let favorites = PointOfInterest.filter(favorite).order(title).fetchAll(db) - // Fetch from SQL let pois = PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests") } + + +// Query Interface + +let title = SQLColumn("title") +let favorite = SQLColumn("favorite") + +let favoritePois = dbQueue.inDatabase { db in + PointOfInterest.filter(favorite).order(title).fetchAll(db) +} ``` From 9ff1915e49213df59b152a7646fbd92abb736fa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 06:52:17 +0100 Subject: [PATCH 18/26] README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 588d0a177..d09afe0d9 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ let title = SQLColumn("title") let favorite = SQLColumn("favorite") let favoritePois = dbQueue.inDatabase { db in + // SELECT * FROM "pointOfInterests" WHERE "favorite" ORDER BY "title" PointOfInterest.filter(favorite).order(title).fetchAll(db) } ``` From 9417d11d370fbff18f39382119456642924a13ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 08:06:55 +0100 Subject: [PATCH 19/26] README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index d09afe0d9..558bca41c 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,10 @@ It provides an SQL API and application tools. ```swift import GRDB +let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") // SQL usage -let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") try dbQueue.inDatabase { db in try db.execute( "CREATE TABLE pointOfInterests (" + @@ -40,8 +40,7 @@ try dbQueue.inDatabase { db in } } - -// Database protocols and Records +// Records struct PointOfInterest { var id: Int64? @@ -50,9 +49,7 @@ struct PointOfInterest { var coordinate: CLLocationCoordinate2D } -extension PointOfInterest { - // snip: conformance to database protocols -} +// snip: turn PointOfInterest into a "record" by adopting database protocols try dbQueue.inDatabase { db in // INSERT INTO "pointOfInterests" ... @@ -74,9 +71,12 @@ try dbQueue.inDatabase { db in let title = SQLColumn("title") let favorite = SQLColumn("favorite") -let favoritePois = dbQueue.inDatabase { db in +dbQueue.inDatabase { db in + // SELECT * FROM "pointOfInterests" WHERE "title" = 'Paris' + let paris = PointOfInterest.filter(title == 'Paris').fetchOne(db) + // SELECT * FROM "pointOfInterests" WHERE "favorite" ORDER BY "title" - PointOfInterest.filter(favorite).order(title).fetchAll(db) + let favoritePois = PointOfInterest.filter(favorite).order(title).fetchAll(db) } ``` From ae353dc771cfaeb3eab6295dd78da22a4a92dc56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 08:09:37 +0100 Subject: [PATCH 20/26] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 558bca41c..d39df677f 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ try dbQueue.inDatabase { db in let parisId = try db.execute( "INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " + "VALUES (?, ?, ?, ?)", - arguments: ["Paris", true, 48.85341, 2.3488,]).insertedRowID + arguments: ["Paris", true, 48.85341, 2.3488]).insertedRowID for row in Row.fetch(db, "SELECT * FROM pointOfInterests") { let title: String = row.value(named: "title") From 754c38ced4b6f05b5529e25e19ecca75fb46dfc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 08:13:34 +0100 Subject: [PATCH 21/26] README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d39df677f..a8ae92194 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,8 @@ struct PointOfInterest { var coordinate: CLLocationCoordinate2D } -// snip: turn PointOfInterest into a "record" by adopting database protocols +// snip: turn PointOfInterest into a "record" by adopting the protocols that +// provide fetching and persistence methods. try dbQueue.inDatabase { db in // INSERT INTO "pointOfInterests" ... From fb8af21c931e0b6d2c95cf1231f7455de1f5f691 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 08:14:54 +0100 Subject: [PATCH 22/26] README.md --- README.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a8ae92194..9990a72da 100644 --- a/README.md +++ b/README.md @@ -12,12 +12,16 @@ It provides an SQL API and application tools. ### Usage +Connect to the database + ```swift import GRDB let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") +``` -// SQL usage +SQL usage +```swift try dbQueue.inDatabase { db in try db.execute( "CREATE TABLE pointOfInterests (" + @@ -39,9 +43,11 @@ try dbQueue.inDatabase { db in print(title, favorite) } } +``` -// Records +Records +```swift struct PointOfInterest { var id: Int64? var title: String? @@ -65,10 +71,11 @@ try dbQueue.inDatabase { db in // Fetch from SQL let pois = PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests") } +``` +Query Interface -// Query Interface - +```swift let title = SQLColumn("title") let favorite = SQLColumn("favorite") From 0e7bee7a7983bc5f6aba7835859ee0de45ecf4f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 08:17:58 +0100 Subject: [PATCH 23/26] README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9990a72da..043c29190 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,14 @@ It provides an SQL API and application tools. ### Usage -Connect to the database +Open a connection to the [database](#database-queues): ```swift import GRDB let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") ``` -SQL usage +Execute [SQL queries](#executing-updates): ```swift try dbQueue.inDatabase { db in @@ -45,7 +45,7 @@ try dbQueue.inDatabase { db in } ``` -Records +Insert and fetch [Records](#records): ```swift struct PointOfInterest { @@ -73,7 +73,7 @@ try dbQueue.inDatabase { db in } ``` -Query Interface +Turn Swift into SQL with the [Query Interface](#the-query-interface): ```swift let title = SQLColumn("title") From b3c23c474a3ad0b67cd5fd87f86047c53f3a5f59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 08:19:31 +0100 Subject: [PATCH 24/26] README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 043c29190..9c0f54dc0 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ let favorite = SQLColumn("favorite") dbQueue.inDatabase { db in // SELECT * FROM "pointOfInterests" WHERE "title" = 'Paris' - let paris = PointOfInterest.filter(title == 'Paris').fetchOne(db) + let paris = PointOfInterest.filter(title == "Paris").fetchOne(db) // SELECT * FROM "pointOfInterests" WHERE "favorite" ORDER BY "title" let favoritePois = PointOfInterest.filter(favorite).order(title).fetchAll(db) From bc3be0f1ff3cdf172a2b2ec8b89d2588ac9e9b8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 09:11:07 +0100 Subject: [PATCH 25/26] README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 9c0f54dc0..75484fa10 100644 --- a/README.md +++ b/README.md @@ -1776,7 +1776,6 @@ let name = SQLColumn("name") > struct Col { > static let id = SQLColumn("id") > static let name = SQLColumn("name") -> static let age = SQLColumn("age") > } > ``` From cc0f76d75b83ad84b4abc4304dc0411b623b7070 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 29 Jan 2016 09:15:12 +0100 Subject: [PATCH 26/26] TODO.md --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 8fae2df8d..bceb82800 100644 --- a/TODO.md +++ b/TODO.md @@ -1,6 +1,7 @@ - [ ] How to have robust single writer/several readers? - [ ] protocol DatabaseEquatable, with default implementation for MutablePersistable - [ ] Query builder + - [ ] Question the utility of request.fetchCount(db, Col.name) and request.fetchCount(db, distinct: Col.name) - [ ] Check for gross pollution (`1.SQLexpression`) - [ ] SELECT readers.*, books.* FROM ... JOIN ... - [ ] date functions