diff --git a/CHANGELOG.md b/CHANGELOG.md index 6521ccf45..b87d3f123 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,16 @@ Release Notes ============= +## 0.52.0 + +Released March 21, 2016 + +**New** + +- Swift 2.2, and Xcode 7.3 +- `Row` adopts Equatable + + ## 0.51.2 Released March 14, 2016 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 797088e12..a69de0128 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.51.2' + s.version = '0.52.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A versatile SQLite toolkit for Swift, with WAL mode support.' s.homepage = 'https://github.com/groue/GRDB.swift' diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f426865f8..2bac4b07c 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -487,7 +487,6 @@ 56B7F4361BE4C11200E39BBF /* DatabaseCoderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoderTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; - 56B8F49B1B4E2F3600C24296 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = ""; }; 56BB86111BA9886D001F9168 /* PerformanceTests.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceTests.sqlite; sourceTree = ""; }; 56BB86121BA9886D001F9168 /* InsertRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordTests.swift; sourceTree = ""; }; 56BB86181BA988F2001F9168 /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = ""; }; @@ -504,6 +503,7 @@ 56BB862D1BA98933001F9168 /* GRDBPerformanceTests-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDBPerformanceTests-Bridging.h"; sourceTree = ""; }; 56BB862E1BA98AA9001F9168 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; }; 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; }; + 56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = ""; }; 56CA21B91BB3FCF7009A04C5 /* NSDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDataTests.swift; sourceTree = ""; }; 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = SQLite.xcodeproj; path = SQLite.swift/SQLite.xcodeproj; sourceTree = ""; }; 56CA22211BB41565009A04C5 /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceTests.swift; sourceTree = ""; }; @@ -738,6 +738,22 @@ path = Collation; sourceTree = ""; }; + 567D10621C9A911C00ACC500 /* GRDBiOS */ = { + isa = PBXGroup; + children = ( + 5683C2681B4D445E00296494 /* libsqlite3.dylib */, + ); + path = GRDBiOS; + sourceTree = ""; + }; + 567D10641C9A911C00ACC500 /* GRDBOSX */ = { + isa = PBXGroup; + children = ( + DC37744219C8DC91004FCF85 /* libsqlite3.dylib */, + ); + path = GRDBOSX; + sourceTree = ""; + }; 569530FA1C9067CC00CF1A2B /* Crash */ = { isa = PBXGroup; children = ( @@ -1003,22 +1019,6 @@ name = Products; sourceTree = ""; }; - 56E5D7BF1B4D3DC900430942 /* GRDBiOS */ = { - isa = PBXGroup; - children = ( - 5683C2681B4D445E00296494 /* libsqlite3.dylib */, - ); - path = GRDBiOS; - sourceTree = ""; - }; - 56E5D7C11B4D3DC900430942 /* GRDBOSX */ = { - isa = PBXGroup; - children = ( - DC37744219C8DC91004FCF85 /* libsqlite3.dylib */, - ); - path = GRDBOSX; - sourceTree = ""; - }; 56EA86921C91DFDA002BB4DF /* DatabaseReader */ = { isa = PBXGroup; children = ( @@ -1126,9 +1126,9 @@ isa = PBXGroup; children = ( 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */, - 56B8F49B1B4E2F3600C24296 /* module.modulemap */, - 56E5D7BF1B4D3DC900430942 /* GRDBiOS */, - 56E5D7C11B4D3DC900430942 /* GRDBOSX */, + 56C48E731C9A9923005DF1D9 /* module.modulemap */, + 567D10621C9A911C00ACC500 /* GRDBiOS */, + 567D10641C9A911C00ACC500 /* GRDBOSX */, DC3773F819C8CBB3004FCF85 /* GRDB.h */, DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */, DC3773F719C8CBB3004FCF85 /* Info.plist */, diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index ce1983f51..ef1c75a67 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,5 +1,15 @@ import Foundation +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + /// Configuration for a DatabaseQueue or DatabasePool. public struct Configuration { diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 50b9de344..158cc1f4c 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1,5 +1,15 @@ import Foundation +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + /// A raw SQLite connection, suitable for the SQLite C API. public typealias SQLiteConnection = COpaquePointer @@ -47,17 +57,17 @@ public final class Database { var dispatchQueueID: UnsafeMutablePointer = nil init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCacheType) throws { - self.configuration = configuration - self.schemaCache = schemaCache - // See https://www.sqlite.org/c3ref/open.html - var sqliteConnection = SQLiteConnection() + var sqliteConnection: SQLiteConnection = nil let code = sqlite3_open_v2(path, &sqliteConnection, configuration.sqliteOpenFlags, nil) - self.sqliteConnection = sqliteConnection guard code == SQLITE_OK else { throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) } + self.configuration = configuration + self.schemaCache = schemaCache + self.sqliteConnection = sqliteConnection + configuration.SQLiteConnectionDidOpen?() // Setup trace first, so that all queries, including initialization queries, are traced. diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 819ced53d..437e17a77 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -1,3 +1,13 @@ +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + /// DatabaseError wraps an SQLite error. public struct DatabaseError : ErrorType { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5e4cc39f9..b7442cbc9 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -1,3 +1,13 @@ +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + /// A DatabasePool grants concurrent accesses to an SQLite database. public final class DatabasePool { @@ -14,32 +24,52 @@ public final class DatabasePool { /// - configuration: A configuration. /// - maximumReaderCount: The maximum number of readers. Default is 5. /// - throws: A DatabaseError whenever an SQLite error occurs. - public convenience init(path: String, configuration: Configuration = Configuration(), maximumReaderCount: Int = 5) throws { + public init(path: String, configuration: Configuration = Configuration(), maximumReaderCount: Int = 5) throws { precondition(maximumReaderCount > 1, "maximumReaderCount must be at least 1") // Database Store - let store = try DatabaseStore(path: path, attributes: configuration.fileAttributes) + store = try DatabaseStore(path: path, attributes: configuration.fileAttributes) // Shared database schema cache let databaseSchemaCache = SharedDatabaseSchemaCache() // Writer - let writer = try SerializedDatabase( + writer = try SerializedDatabase( path: path, configuration: configuration, schemaCache: databaseSchemaCache) // Activate WAL Mode unless readonly if !configuration.readonly { - let mode = writer.inDatabase { db in - String.fetchOne(db, "PRAGMA journal_mode=WAL") - } - guard mode == "wal" else { + let journalMode = String.fetchOne(writer, "PRAGMA journal_mode=WAL") + guard journalMode == "wal" else { throw DatabaseError(message: "could not activate WAL Mode at path: \(path)") } } - self.init(path: path, configuration: configuration, maximumReaderCount: maximumReaderCount, databaseSchemaCache: databaseSchemaCache, writer: writer, store: store) + // Readers + var readerConfig = configuration + readerConfig.readonly = true + readerConfig.defaultTransactionKind = .Deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections. + + readerPool = Pool(maximumCount: maximumReaderCount) + readerPool.makeElement = { [unowned self] in + let serializedDatabase = try! SerializedDatabase( + path: path, + configuration: readerConfig, + schemaCache: databaseSchemaCache) + + serializedDatabase.inDatabase { db in + for function in self.functions { + db.addFunction(function) + } + for collation in self.collations { + db.addCollation(collation) + } + } + + return serializedDatabase + } } @@ -94,34 +124,6 @@ public final class DatabasePool { private var functions = Set() private var collations = Set() - - private init(path: String, configuration: Configuration, maximumReaderCount: Int, databaseSchemaCache: DatabaseSchemaCacheType, writer: SerializedDatabase, store: DatabaseStore) { - self.store = store - self.writer = writer - self.readerPool = Pool(maximumCount: maximumReaderCount) - - var readerConfig = configuration - readerConfig.readonly = true - readerConfig.defaultTransactionKind = .Deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections. - - readerPool.makeElement = { [unowned self] in - let serializedDatabase = try! SerializedDatabase( - path: path, - configuration: readerConfig, - schemaCache: databaseSchemaCache) - - serializedDatabase.inDatabase { db in - for function in self.functions { - db.addFunction(function) - } - for collation in self.collations { - db.addCollation(collation) - } - } - - return serializedDatabase - } - } } /// The available [checkpoint modes](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html). @@ -228,31 +230,15 @@ extension DatabasePool : DatabaseReader { public func addFunction(function: DatabaseFunction) { functions.remove(function) functions.insert(function) - - writer.inDatabase { db in - db.addFunction(function) - } - - readerPool.forEach { reader in - reader.inDatabase { db in - db.addFunction(function) - } - } + writer.addFunction(function) + readerPool.forEach { $0.addFunction(function) } } /// Remove an SQL function. public func removeFunction(function: DatabaseFunction) { functions.remove(function) - - writer.inDatabase { db in - db.removeFunction(function) - } - - readerPool.forEach { reader in - reader.inDatabase { db in - db.removeFunction(function) - } - } + writer.removeFunction(function) + readerPool.forEach { $0.removeFunction(function) } } @@ -270,31 +256,15 @@ extension DatabasePool : DatabaseReader { public func addCollation(collation: DatabaseCollation) { collations.remove(collation) collations.insert(collation) - - writer.inDatabase { db in - db.addCollation(collation) - } - - readerPool.forEach { reader in - reader.inDatabase { db in - db.addCollation(collation) - } - } + writer.addCollation(collation) + readerPool.forEach { $0.addCollation(collation) } } /// Remove a collation. public func removeCollation(collation: DatabaseCollation) { collations.remove(collation) - - writer.inDatabase { db in - db.removeCollation(collation) - } - - readerPool.forEach { reader in - reader.inDatabase { db in - db.removeCollation(collation) - } - } + writer.removeCollation(collation) + readerPool.forEach { $0.removeCollation(collation) } } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index b06693e78..7209367a5 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -23,17 +23,12 @@ public final class DatabaseQueue { /// - path: The path to the database file. /// - configuration: A configuration. /// - throws: A DatabaseError whenever an SQLite error occurs. - public convenience init(path: String, configuration: Configuration = Configuration()) throws { - // Database Store - let store = try DatabaseStore(path: path, attributes: configuration.fileAttributes) - - // Database - let serializedDatabase = try SerializedDatabase( + public init(path: String, configuration: Configuration = Configuration()) throws { + store = try DatabaseStore(path: path, attributes: configuration.fileAttributes) + serializedDatabase = try SerializedDatabase( path: path, configuration: configuration, schemaCache: DatabaseSchemaCache()) - - self.init(serializedDatabase: serializedDatabase, store: store) } /// Opens an in-memory SQLite database. @@ -43,13 +38,12 @@ public final class DatabaseQueue { /// Database memory is released when the database queue gets deallocated. /// /// - parameter configuration: A configuration. - public convenience init(configuration: Configuration = Configuration()) { - let serializedDatabase = try! SerializedDatabase( + public init(configuration: Configuration = Configuration()) { + store = nil + serializedDatabase = try! SerializedDatabase( path: ":memory:", configuration: configuration, schemaCache: DatabaseSchemaCache()) - - self.init(serializedDatabase: serializedDatabase, store: nil) } @@ -181,16 +175,12 @@ extension DatabaseQueue : DatabaseReader { /// Int.fetchOne(db, "SELECT succ(1)") // 2 /// } public func addFunction(function: DatabaseFunction) { - inDatabase { db in - db.addFunction(function) - } + serializedDatabase.addFunction(function) } /// Remove an SQL function. public func removeFunction(function: DatabaseFunction) { - inDatabase { db in - db.removeFunction(function) - } + serializedDatabase.removeFunction(function) } @@ -206,16 +196,12 @@ extension DatabaseQueue : DatabaseReader { /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") /// } public func addCollation(collation: DatabaseCollation) { - inDatabase { db in - db.addCollation(collation) - } + serializedDatabase.addCollation(collation) } /// Remove a collation. public func removeCollation(collation: DatabaseCollation) { - inDatabase { db in - db.removeCollation(collation) - } + serializedDatabase.removeCollation(collation) } } diff --git a/GRDB/Core/DatabaseStore.swift b/GRDB/Core/DatabaseStore.swift index 9bc29f708..e97185fc8 100644 --- a/GRDB/Core/DatabaseStore.swift +++ b/GRDB/Core/DatabaseStore.swift @@ -7,15 +7,22 @@ class DatabaseStore { private let source: dispatch_source_t? private let queue: dispatch_queue_t? - convenience init(path: String, attributes: [String: AnyObject]?) throws { + init(path: String, attributes: [String: AnyObject]?) throws { guard let attributes = attributes else { - self.init() + self.queue = nil + self.source = nil return } let databaseFileName = (path as NSString).lastPathComponent let directoryPath = (path as NSString).stringByDeletingLastPathComponent + // Apply file attributes on existing files + DatabaseStore.setFileAttributes( + directoryPath: directoryPath, + databaseFileName: databaseFileName, + attributes: attributes) + // We use a dispatch_source to monitor the contents of the database file // parent directory, and apply file attributes. // @@ -28,8 +35,23 @@ class DatabaseStore { throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, userInfo: nil) } - // Call the non-throwing initializer - self.init(directoryPath: directoryPath, databaseFileName: databaseFileName, directoryDescriptor: directoryDescriptor, attributes: attributes) + let queue = dispatch_queue_create("com.groue.GRDB.DatabaseStore", nil) + let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(directoryDescriptor), DISPATCH_VNODE_WRITE, queue) + self.queue = queue + self.source = source + + // Configure dispatch source + dispatch_source_set_event_handler(source) { + // Directory has been modified: apply file attributes on unprocessed files + DatabaseStore.setFileAttributes( + directoryPath: directoryPath, + databaseFileName: databaseFileName, + attributes: attributes) + } + dispatch_source_set_cancel_handler(source) { + close(directoryDescriptor) + } + dispatch_resume(source) } private init() { diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 4ea39627c..6c051cb28 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -1,5 +1,15 @@ import Foundation +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + // MARK: - DatabaseValue /// DatabaseValue is the intermediate type between SQLite and your values. diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index be71b81e2..5c4c70c06 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1,5 +1,15 @@ import Foundation +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + /// A database row. public final class Row { @@ -95,7 +105,7 @@ extension Row { /// Columns appear in the same order as they occur as the `.0` member /// of column-value pairs in `self`. public var columnNames: LazyMapCollection { - return LazyMapCollection(self) { $0.0 } + return lazy.map { $0.0 } } /// Returns true if and only if the row has that column. @@ -424,7 +434,7 @@ extension Row { /// Values appear in the same order as they occur as the `.1` member /// of column-value pairs in `self`. public var databaseValues: LazyMapCollection { - return LazyMapCollection(self) { $0.1 } + return lazy.map { $0.1 } } } @@ -798,7 +808,7 @@ private struct StatementRowImpl : RowImpl { self.sqliteStatement = sqliteStatement // Optimize row.value(named: "...") let lowercaseColumnNames = (0.. SQLite support three different threading modes: @@ -34,13 +34,8 @@ final class SerializedDatabase { var config = configuration config.threadingMode = .MultiThread - let database = try Database(path: path, configuration: config, schemaCache: schemaCache) - self.init(database: database) - } - - private init(database: Database) { - self.database = database - self.queue = dispatch_queue_create("GRDB.SerializedDatabase", nil) + database = try Database(path: path, configuration: config, schemaCache: schemaCache) + queue = dispatch_queue_create("GRDB.SerializedDatabase", nil) // Activate database.preconditionValidQueue() let dispatchQueueID = unsafeBitCast(database, UnsafeMutablePointer.self) @@ -86,3 +81,35 @@ final class SerializedDatabase { } } } + +extension SerializedDatabase : DatabaseReader { + func read(block: (db: Database) throws -> T) rethrows -> T { + return try inDatabase { try $0.read(block) } + } + + func nonIsolatedRead(block: (db: Database) throws -> T) rethrows -> T { + return try inDatabase { try $0.nonIsolatedRead(block) } + } + + func addFunction(function: DatabaseFunction) { + inDatabase { $0.addFunction(function) } + } + + func removeFunction(function: DatabaseFunction) { + inDatabase { $0.removeFunction(function) } + } + + func addCollation(collation: DatabaseCollation) { + inDatabase { $0.addCollation(collation) } + } + + func removeCollation(collation: DatabaseCollation) { + inDatabase { $0.removeCollation(collation) } + } +} + +extension SerializedDatabase : DatabaseWriter { + func write(block: (db: Database) throws -> T) rethrows -> T { + return try inDatabase { try $0.write(block) } + } +} diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index d36eafe69..61cb7e730 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -1,5 +1,15 @@ import Foundation +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + /// A raw SQLite statement, suitable for the SQLite C API. public typealias SQLiteStatement = COpaquePointer @@ -288,7 +298,7 @@ public final class SelectStatement : Statement { /// Cache for indexOfColumn(). Keys are lowercase. private lazy var columnIndexes: [String: Int] = { - return Dictionary(self.columnNames.enumerate().map { ($1.lowercaseString, $0) }.reverse()) + return Dictionary(keyValueSequence: self.columnNames.enumerate().map { ($1.lowercaseString, $0) }.reverse()) }() // This method MUST be case-insensitive, and returns the index of the @@ -385,7 +395,8 @@ public class DatabaseGenerator: GeneratorType { guard let element = element else { return nil } - return element(sqliteStatement, unsafeUnwrap(statementRef)) + // TODO: use unsafeUnWrap(statementRef) + return element(sqliteStatement, statementRef!) } } @@ -573,7 +584,7 @@ public struct StatementArguments { /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. public init(_ sequence: Sequence) { - kind = .NamedValues(Dictionary(sequence)) + kind = .NamedValues(Dictionary(keyValueSequence: sequence)) } /// Initializes arguments from a sequence of (key, value) pairs, such as @@ -585,7 +596,7 @@ public struct StatementArguments { /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. public init(_ sequence: Sequence) { - kind = .NamedValues(Dictionary(sequence.map { (key, value) in return (key, value as DatabaseValueConvertible?) })) + kind = .NamedValues(Dictionary(keyValueSequence: sequence.map { (key, value) in return (key, value as DatabaseValueConvertible?) })) } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 9fcd7c20d..cc4a93037 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -1,3 +1,13 @@ +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + /// When a type adopts both DatabaseValueConvertible and /// StatementColumnConvertible, it is granted with faster access to the SQLite /// database values. diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 694e53f38..6eda2797e 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -1,3 +1,13 @@ +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + /// Bool adopts DatabaseValueConvertible and StatementColumnConvertible. extension Bool: DatabaseValueConvertible, StatementColumnConvertible { diff --git a/GRDB/Core/Utils.swift b/GRDB/Core/Utils.swift index edd019ff1..ac63a8240 100644 --- a/GRDB/Core/Utils.swift +++ b/GRDB/Core/Utils.swift @@ -1,5 +1,15 @@ import Foundation +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + // MARK: - Public @@ -59,9 +69,9 @@ extension Array { extension Dictionary { /// 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 { + init(keyValueSequence: Sequence) { + self.init(minimumCapacity: keyValueSequence.underestimateCount()) + for (key, value) in keyValueSequence { self[key] = value } } diff --git a/GRDB/Migrations/DatabaseMigrator.swift b/GRDB/Migrations/DatabaseMigrator.swift index 75d810a37..c28cd9ff0 100644 --- a/GRDB/Migrations/DatabaseMigrator.swift +++ b/GRDB/Migrations/DatabaseMigrator.swift @@ -71,7 +71,7 @@ public struct DatabaseMigrator { /// disabled foreign key checks. /// - block: The migration block that performs SQL statements. /// - precondition: No migration with the same same as already been registered. - public mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (db: Database) throws -> Void) { + public mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (Database) throws -> Void) { registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: disabledForeignKeyChecks, migrate: migrate)) } diff --git a/GRDB/Migrations/Migration.swift b/GRDB/Migrations/Migration.swift index 5132fc6ef..9e7da319f 100644 --- a/GRDB/Migrations/Migration.swift +++ b/GRDB/Migrations/Migration.swift @@ -1,3 +1,13 @@ +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + /// An internal struct that defines a migration. struct Migration { let identifier: String @@ -49,7 +59,7 @@ struct Migration { // // Let's turn any violation into an SQLITE_CONSTRAINT // error, and rollback the transaction. - throw DatabaseError(code: SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed", sql: "PRAGMA foreign_key_check", arguments: nil) + throw DatabaseError(code: SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed", sql: nil, arguments: nil) } // > 11. Commit the transaction started in step 2. diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index c36b83ea5..2cbe7af35 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -154,7 +154,12 @@ public class Record : RowConvertible, TableMapping, Persistable { /// /// See `hasPersistentChangedValues` for more information. public var persistentChangedValues: [String: DatabaseValue?] { - return Dictionary(generatePersistentChangedValues()) + var persistentChangedValues: [String: DatabaseValue?] = [:] + + for (key, value) in generatePersistentChangedValues() { + persistentChangedValues[key] = value + } + return persistentChangedValues } // A change generator that is used by both hasPersistentChangedValues and @@ -162,7 +167,7 @@ public class Record : RowConvertible, TableMapping, Persistable { private func generatePersistentChangedValues() -> AnyGenerator<(column: String, old: DatabaseValue?)> { let oldRow = referenceRow var newValueGenerator = persistentDictionary.generate() - return anyGenerator { + return AnyGenerator { // Loop until we find a change, or exhaust columns: while let (column, newValue) = newValueGenerator.next() { let new = newValue?.databaseValue ?? .Null diff --git a/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift b/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift index a3c1729d2..0079800f9 100644 --- a/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift +++ b/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift @@ -48,7 +48,7 @@ public func sortedMerge AnyGenerator> in var (lGen, rGen) = (lSeq.generate(), rSeq.generate()) var (lOpt, rOpt) = (lGen.next(), rGen.next()) - return anyGenerator { + return AnyGenerator { switch (lOpt, rOpt) { case (let lElem?, let rElem?): let (lKey, rKey) = (leftKey(lElem), rightKey(rElem)) diff --git a/README.md b/README.md index ebc3208eb..52c39b8c9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ GRDB.swift ========== -GRDB.swift is an SQLite toolkit for Swift 2. +GRDB.swift is an SQLite toolkit for Swift 2.2. It ships with an SQL API, protocols that turn your custom types in ORM-like objects, safe concurrent accesses to the database (that's pretty unique), and a Swift query interface which lets SQL-allergic developers avoid their most dreaded language. @@ -11,7 +11,7 @@ You should give it a try. --- -**March 14, 2016: GRDB.swift 0.51.2 is out** ([changelog](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +**March 14, 2016: GRDB.swift 0.52.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+ @@ -110,7 +110,7 @@ Documentation **Reference** -- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/index.html) (on cocoadocs.org) +- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.52.0/index.html) (on cocoadocs.org) **Getting started** @@ -157,7 +157,7 @@ To use GRDB with CocoaPods, specify in your Podfile: source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '~> 0.51.2' +pod 'GRDB.swift', '~> 0.52.0' ``` @@ -168,7 +168,7 @@ pod 'GRDB.swift', '~> 0.51.2' To use GRDB with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" ~> 0.51.2 +github "groue/GRDB.swift" ~> 0.52.0 ``` @@ -250,7 +250,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.52.0/Structs/Configuration.html) for more details. > :bowtie: **Tip**: see [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift) for a sample code that sets up a database queue. @@ -301,7 +301,7 @@ let dbPool = try DatabasePool( maximumReaderCount: 10) // The default is 5 ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.52.0/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -2560,7 +2560,7 @@ See [Transactions](#transactions) for more information. SQLite concurrency is a wiiide topic. -First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.51.2/Protocols/DatabaseWriter.html) protocols. +First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.52.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.52.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.52.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.52.0/Protocols/DatabaseWriter.html) protocols. If the built-in queues and pools do not fit your needs, or if you can not guarantee that a single queue or pool is accessing your database file, you may have a look at: diff --git a/Support/Info.plist b/Support/Info.plist index 6ee1b75a5..2f4db157a 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.51.2 + 0.52.0 CFBundleSignature ???? CFBundleVersion diff --git a/Support/module.modulemap b/Support/module.modulemap index 070b7d034..57256af46 100644 --- a/Support/module.modulemap +++ b/Support/module.modulemap @@ -1,8 +1,21 @@ framework module GRDB { umbrella header "GRDB.h" - - header "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/sqlite3.h" - + export * module * { export * } } + +module SQLiteMacOSX { + header "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/sqlite3.h" + export * +} + +module SQLiteiPhoneOS { + header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/sqlite3.h" + export * +} + +module SQLiteiPhoneSimulator { + header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/sqlite3.h" + export * +} diff --git a/TODO.md b/TODO.md index c3041c6fc..ef233e710 100644 --- a/TODO.md +++ b/TODO.md @@ -1,4 +1,6 @@ -- [ ] Write an app like http://www.appcoda.com/swiftydb/ ? +- [ ] DOC: Write an app like http://www.appcoda.com/swiftydb/ ? +- [ ] DOC: present the safe inDatabase, read, and write methods before the unsafe direct access. +- [ ] DOC: Since commit e6010e334abdf98eb9f62c1d6abbb2a9e8cd7d19, one can not use the raw SQLite API without importing the SQLite module for the platform. We need to document that. - [ ] Read https://sqlite.org/sharedcache.html - [ ] Query builder - [ ] SELECT readers.*, books.* FROM ... JOIN ... diff --git a/Tests/Private/NSDataMemoryTests.swift b/Tests/Private/NSDataMemoryTests.swift index e9659bd40..bba986db6 100644 --- a/Tests/Private/NSDataMemoryTests.swift +++ b/Tests/Private/NSDataMemoryTests.swift @@ -1,4 +1,15 @@ import XCTest + +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + @testable import GRDB class NSDataMemoryTests: GRDBTestCase { diff --git a/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift b/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift index a4823125b..fde09ffa2 100644 --- a/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift +++ b/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift @@ -1,6 +1,16 @@ import XCTest import GRDB +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + // A type that adopts DatabaseValueConvertible but does not adopt StatementColumnConvertible private struct WrappedInt: DatabaseValueConvertible { let int: Int diff --git a/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift b/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift index 2b1feaf2a..057169ff6 100644 --- a/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift +++ b/Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConvertibleFetchTests.swift @@ -1,6 +1,16 @@ import XCTest import GRDB +#if os(OSX) + import SQLiteMacOSX +#elseif os(iOS) +#if (arch(i386) || arch(x86_64)) + import SQLiteiPhoneSimulator + #else + import SQLiteiPhoneOS +#endif +#endif + // A type that adopts DatabaseValueConvertible and StatementColumnConvertible private struct FastWrappedInt: DatabaseValueConvertible, StatementColumnConvertible { let int: Int diff --git a/Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift b/Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift index c2405f515..9db74f1e5 100644 --- a/Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift +++ b/Tests/Public/Core/TransactionObserver/TransactionObserverTests.swift @@ -30,25 +30,25 @@ class TransactionObserver : TransactionObserverType { } func databaseDidChangeWithEvent(event: DatabaseEvent) { - didChangeCount++ + didChangeCount += 1 events.append(event) } func databaseWillCommit() throws { - willCommitCount++ + willCommitCount += 1 if let commitError = commitError { throw commitError } } func databaseDidCommit(db: Database) { - didCommitCount++ + didCommitCount += 1 lastCommittedEvents = events events = [] } func databaseDidRollback(db: Database) { - didRollbackCount++ + didRollbackCount += 1 lastCommittedEvents = [] events = [] } diff --git a/Tests/Public/Migrations/DatabaseMigratorTests.swift b/Tests/Public/Migrations/DatabaseMigratorTests.swift index 5fa776016..0cb5b8ac6 100644 --- a/Tests/Public/Migrations/DatabaseMigratorTests.swift +++ b/Tests/Public/Migrations/DatabaseMigratorTests.swift @@ -110,20 +110,31 @@ class DatabaseMigratorTests : GRDBTestCase { do { try migrator.migrate(dbQueue) XCTFail("Expected error") - } catch { + } catch let error as DatabaseError { // Migration 1 and 2 should be committed. // Migration 3 should not be committed. + XCTAssertEqual(error.code, 19) // SQLITE_CONSTRAINT + XCTAssertEqual(error.message!, "FOREIGN KEY constraint failed") + XCTAssertTrue(error.sql == nil) + XCTAssertEqual(error.description, "SQLite error 19: FOREIGN KEY constraint failed") + // Arthur inserted (migration 1), Barbara (migration 3) not inserted. - let rows = dbQueue.inDatabase { db in - Row.fetchAll(db, "SELECT * FROM persons") - } + var rows = Row.fetchAll(dbQueue, "SELECT * FROM persons") XCTAssertEqual(rows.count, 1) - let row = rows.first! + var row = rows.first! XCTAssertEqual(row.value(named: "name") as String, "Arthur") // persons table has no "tmp" column (migration 2) XCTAssertEqual(Array(row.columnNames), ["id", "name"]) + + // Bobby inserted (migration 1), not deleted by migration 2. + rows = Row.fetchAll(dbQueue, "SELECT * FROM pets") + XCTAssertEqual(rows.count, 1) + row = rows.first! + XCTAssertEqual(row.value(named: "name") as String, "Bobby") + } catch { + XCTFail("Error: \(error)") } } }