Merge pull request #720 from groue/dev/GRDB5-removeDeprecated

Turn deprecated APIs into unavailable ones
This commit is contained in:
Gwendal Roué authored and GitHub committed 2020-03-08 19:15:41 +01:00
commit a31984724e
60 files changed
+531 -2780

No files matched your search

+1
View File
@@ -91,6 +91,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## GRDB5 Branch
- [#719](https://github.com/groue/GRDB.swift/pull/719): Bump required Swift version to 5.2
- [#720](https://github.com/groue/GRDB.swift/pull/720): Turn deprecated APIs into unavailable ones
## 4.11.0
+10 -10
View File
@@ -455,9 +455,9 @@
567DAF221EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567DAF391EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567ECE4F2222E431009245CA /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; };
567ECE502222E431009245CA /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; };
567ECE512222E431009245CA /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; };
567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; };
567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; };
567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; };
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
@@ -908,7 +908,7 @@
AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; };
AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; };
AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; };
AAA4DCD3230F1E0600C74B15 /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-4.0.swift */; };
AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; };
AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; };
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
@@ -1362,7 +1362,7 @@
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567ECE4E2222E431009245CA /* GRDB-4.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-4.0.swift"; sourceTree = "<group>"; };
567ECE4E2222E431009245CA /* GRDB-5.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-5.0.swift"; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
@@ -2225,7 +2225,7 @@
56D7E449221595FE0052464B /* Fixit */ = {
isa = PBXGroup;
children = (
567ECE4E2222E431009245CA /* GRDB-4.0.swift */,
567ECE4E2222E431009245CA /* GRDB-5.0.swift */,
);
path = Fixit;
sourceTree = "<group>";
@@ -2787,7 +2787,7 @@
5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
563EF45D2163309F007DAACD /* Inflections.swift in Sources */,
569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
567ECE512222E431009245CA /* GRDB-4.0.swift in Sources */,
567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */,
565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */,
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */,
@@ -2977,7 +2977,7 @@
569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */,
5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
567ECE502222E431009245CA /* GRDB-4.0.swift in Sources */,
567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */,
566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */,
@@ -3522,7 +3522,7 @@
AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */,
AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */,
AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */,
AAA4DCD3230F1E0600C74B15 /* GRDB-4.0.swift in Sources */,
AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */,
AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */,
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */,
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */,
@@ -3862,7 +3862,7 @@
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
567ECE4F2222E431009245CA /* GRDB-4.0.swift in Sources */,
567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */,
56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */,
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
+3 -26
View File
@@ -111,22 +111,6 @@ public struct Configuration {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var observesSuspensionNotifications = false
// MARK: - Encryption
#if SQLITE_HAS_CODEC
// TODO: remove when the deprecated passphrase turns unavailable.
var _passphrase: String?
/// The passphrase for the encrypted database.
///
/// Default: nil
@available(*, deprecated, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.")
public var passphrase: String? {
get { return _passphrase }
set { _passphrase = newValue }
}
#endif
// MARK: - Managing SQLite Connections
/// A function that is run when an SQLite connection is opened, before the
@@ -197,8 +181,8 @@ public struct Configuration {
///
/// The quality of service is ignored if you supply a target queue.
///
/// Default: .default (.unspecified on macOS < 10.10)
public var qos: DispatchQoS
/// Default: .default
public var qos: DispatchQoS = .default
/// The target queue for all database accesses.
///
@@ -216,14 +200,7 @@ public struct Configuration {
// MARK: - Factory Configuration
/// Creates a factory configuration
public init() {
if #available(OSX 10.10, *) {
qos = .default
} else {
qos = .unspecified
}
}
public init() { }
// MARK: - Not Public
-62
View File
@@ -220,9 +220,6 @@ public final class Database {
#if SQLITE_HAS_CODEC
try validateSQLCipher()
if let passphrase = configuration._passphrase {
try _usePassphrase(passphrase)
}
#endif
// Last step before we can start accessing the database.
@@ -426,48 +423,6 @@ public final class Database {
}
private static func closeConnection(_ sqliteConnection: SQLiteConnection) {
// sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
} else {
closeConnection_v1(sqliteConnection)
}
#endif
}
private static func closeConnection_v1(_ sqliteConnection: SQLiteConnection) {
// https://www.sqlite.org/c3ref/close.html
// > If the database connection is associated with unfinalized prepared
// > statements or unfinished sqlite3_backup objects then
// > sqlite3_close() will leave the database connection open and
// > return SQLITE_BUSY.
let code = sqlite3_close(sqliteConnection)
if code != SQLITE_OK, let log = logError {
// A rare situation where GRDB doesn't fatalError on
// unprocessed errors.
let message = String(cString: sqlite3_errmsg(sqliteConnection))
log(ResultCode(rawValue: code), "could not close database: \(message)")
if code == SQLITE_BUSY {
// Let the user know about unfinalized statements that did
// prevent the connection from closing properly.
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
while stmt != nil {
log(ResultCode(rawValue: code), "unfinalized statement: \(String(cString: sqlite3_sql(stmt)))")
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
}
}
}
}
private static func closeConnection_v2(
_ sqliteConnection: SQLiteConnection,
_ sqlite3_close_v2: @convention(c) (OpaquePointer?) -> Int32)
{
// https://www.sqlite.org/c3ref/close.html
// > If sqlite3_close_v2() is called with unfinalized prepared
// > statements and/or unfinished sqlite3_backups, then the database
@@ -548,9 +503,6 @@ public final class Database {
func beginReadOnly() throws {
if configuration.readonly { return }
if _readOnlyDepth == 0 {
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
}
_readOnlyDepth += 1
@@ -560,9 +512,6 @@ public final class Database {
if configuration.readonly { return }
_readOnlyDepth -= 1
if _readOnlyDepth == 0 {
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute()
}
}
@@ -1178,17 +1127,6 @@ extension Database {
/// try db.usePassphrase("secret")
/// }
public func usePassphrase(_ passphrase: String) throws {
// Support for the deprecated method change(passphrase:).
// After it has been called, the passphrase used for opening the
// database must be ignored.
if configuration._passphrase != nil {
return
}
try _usePassphrase(passphrase)
}
/// See usePassphrase(_:)
private func _usePassphrase(_ passphrase: String) throws {
let data = passphrase.data(using: .utf8)!
let code = data.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
-11
View File
@@ -159,18 +159,7 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
// CustomStringConvertible
extension ResultCode {
var errorString: String? {
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return String(cString: sqlite3_errstr(rawValue))
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
return String(cString: sqlite3_errstr(rawValue))
} else {
return nil
}
#endif
}
/// :nodoc:
+7 -35
View File
@@ -15,9 +15,6 @@ import UIKit
public final class DatabasePool: DatabaseWriter {
private let writer: SerializedDatabase
private var readerPool: Pool<SerializedDatabase>!
// TODO: remove when the deprecated change(passphrase:) method turns unavailable.
private var readerConfiguration: Configuration
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private var tokenizerRegistrations: [(Database) -> Void] = []
@@ -59,7 +56,7 @@ public final class DatabasePool: DatabaseWriter {
purpose: "writer")
// Readers
readerConfiguration = configuration
var readerConfiguration = configuration
readerConfiguration.readonly = true
// Readers use deferred transactions by default.
@@ -96,7 +93,7 @@ public final class DatabasePool: DatabaseWriter {
readerCount += 1 // protected by pool (TODO: documented this protection behavior)
let reader = try SerializedDatabase(
path: path,
configuration: self.readerConfiguration,
configuration: readerConfiguration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
@@ -138,12 +135,12 @@ public final class DatabasePool: DatabaseWriter {
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
#if os(iOS)
setupAutomaticMemoryManagement()
setupMemoryManagement()
#endif
}
deinit {
// Undo job done in setupAutomaticMemoryManagement()
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
@@ -205,14 +202,7 @@ extension DatabasePool {
}
}
#if os(iOS)
// swiftlint:disable:next line_length
@available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.")
public func setupMemoryManagement(in application: UIApplication) {
// No op.
}
/// Listens to UIApplicationDidEnterBackgroundNotification and
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
/// as much memory as possible.
@@ -220,7 +210,7 @@ extension DatabasePool {
/// - param application: The UIApplication that will start a background
/// task to let the database pool release its memory when the application
/// enters background.
private func setupAutomaticMemoryManagement() {
private func setupMemoryManagement() {
let center = NotificationCenter.default
center.addObserver(
self,
@@ -262,23 +252,6 @@ extension DatabasePool {
#endif
}
#if SQLITE_HAS_CODEC
extension DatabasePool {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws {
try readerPool.barrier {
try writer.sync { try $0.changePassphrase(passphrase) }
readerPool.removeAll()
readerConfiguration._passphrase = passphrase
}
}
}
#endif
extension DatabasePool: DatabaseReader {
// MARK: - Interrupting Database Operations
@@ -392,9 +365,8 @@ extension DatabasePool: DatabaseReader {
/// }
/// }
///
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
/// SQLCipher), attempts to write in the database from this method throw a
/// DatabaseError of resultCode `SQLITE_READONLY`.
/// Attempts to write in the database from this method throw a DatabaseError
/// of resultCode `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
+7 -28
View File
@@ -44,7 +44,7 @@ public final class DatabaseQueue: DatabaseWriter {
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
#if os(iOS)
setupAutomaticMemoryManagement()
setupMemoryManagement()
#endif
}
@@ -65,7 +65,7 @@ public final class DatabaseQueue: DatabaseWriter {
}
deinit {
// Undo job done in setupAutomaticMemoryManagement()
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
@@ -85,12 +85,6 @@ extension DatabaseQueue {
}
#if os(iOS)
// swiftlint:disable:next line_length
@available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.")
public func setupMemoryManagement(in application: UIApplication) {
// No op.
}
/// Listens to UIApplicationDidEnterBackgroundNotification and
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
/// as much memory as possible.
@@ -98,7 +92,7 @@ extension DatabaseQueue {
/// - param application: The UIApplication that will start a background
/// task to let the database queue release its memory when the application
/// enters background.
private func setupAutomaticMemoryManagement() {
private func setupMemoryManagement() {
let center = NotificationCenter.default
center.addObserver(
self,
@@ -140,19 +134,6 @@ extension DatabaseQueue {
#endif
}
#if SQLITE_HAS_CODEC
extension DatabaseQueue {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws {
try writer.sync { try $0.changePassphrase(passphrase) }
}
}
#endif
extension DatabaseQueue {
// MARK: - Interrupting Database Operations
@@ -208,9 +189,8 @@ extension DatabaseQueue {
///
/// This method is *not* reentrant.
///
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
/// SQLCipher), attempts to write in the database from this method throw a
/// DatabaseError of resultCode `SQLITE_READONLY`.
/// Attempts to write in the database from this method throw a DatabaseError
/// of resultCode `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
@@ -231,9 +211,8 @@ extension DatabaseQueue {
/// }
/// }
///
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
/// SQLCipher), attempts to write in the database from this method throw a
/// DatabaseError of resultCode `SQLITE_READONLY`.
/// Attempts to write in the database from this method throw a DatabaseError
/// of resultCode `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
+2 -4
View File
@@ -107,8 +107,7 @@ public protocol DatabaseReader: AnyObject {
/// let count = try Player.fetchCount(db)
/// }
///
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
/// and SQLCipher, attempts to write in the database throw a DatabaseError
/// Guarantee 2: attempts to write in the database throw a DatabaseError
/// whose resultCode is `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
@@ -134,8 +133,7 @@ public protocol DatabaseReader: AnyObject {
/// }
/// }
///
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
/// and SQLCipher, attempts to write in the database throw a DatabaseError
/// Guarantee 2: attempts to write in the database throw a DatabaseError
/// whose resultCode is `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
-50
View File
@@ -49,20 +49,6 @@ public protocol FetchRequest: DatabaseRegionConvertible {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
/// This method is deprecated. Use
/// `makePreparedRequest(_:forSingleResult:)` instead.
///
/// Returns a tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// - parameter singleResult: A hint that a single result row will be
/// consumed. Implementations can optionally use this to optimize the
/// prepared statement.
/// - returns: A prepared statement and an eventual row adapter.
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
/// Returns a PreparedRequest that is ready to be executed.
///
/// - parameter db: A database connection.
@@ -114,21 +100,6 @@ extension FetchRequest {
let request = try makePreparedRequest(db, forSingleResult: false)
return request.statement.databaseRegion
}
// Support for legacy requests which only define prepare(_:forSingleResult:)
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
let (statement, adapter) = try prepare(db, forSingleResult: singleResult)
return PreparedRequest(statement: statement, adapter: adapter)
}
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
/// :nodoc:
public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
let request = try makePreparedRequest(db, forSingleResult: singleResult)
return (request.statement, request.adapter)
}
}
// MARK: - AdaptedFetchRequest
@@ -189,27 +160,6 @@ public struct AnyFetchRequest<T>: FetchRequest {
_databaseRegion = request.databaseRegion
}
/// Creates a request whose `prepare()` method wraps and forwards
/// operations the argument closure.
@available(*, deprecated, message: "Define your own FetchRequest type instead.")
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) {
_preparedRequest = { db, singleResult in
let (statement, adapter) = try prepare(db, singleResult)
return PreparedRequest(statement: statement, adapter: adapter)
}
_fetchCount = { db in
let (statement, _) = try prepare(db, false)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)!
}
_databaseRegion = { db in
let (statement, _) = try prepare(db, false)
return statement.databaseRegion
}
}
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
return try _preparedRequest(db, singleResult)
+19 -61
View File
@@ -18,8 +18,6 @@ public struct SQLLiteral {
case selectable(SQLSelectable)
case orderingTerm(SQLOrderingTerm)
case subQuery(SQLLiteral)
// TODO: remove when the deprecated SQLLiteral.mapSQL(_:) is removed.
case map(SQLLiteral, (String) -> String)
// TODO: remove and use default case argument when compiler >= 5.1
static func sql(_ sql: String) -> Element {
@@ -43,8 +41,6 @@ public struct SQLLiteral {
return orderingTerm.orderingTermSQL(&context)
case let .subQuery(sqlLiteral):
return "(" + sqlLiteral.sql(&context) + ")"
case let .map(sqlLiteral, transform):
return transform(sqlLiteral.sql(&context))
}
}
@@ -61,8 +57,6 @@ public struct SQLLiteral {
case .subQuery:
// subqueries are not requalified
return self
case let .map(sqlLiteral, transform):
return .map(sqlLiteral.qualified(with: alias), transform)
}
}
}
@@ -108,12 +102,6 @@ public struct SQLLiteral {
self.init(elements: [.expression(expression)])
}
// TODO: deprecate when SQL interpolation is always available
/// Returns a literal whose SQL is transformed by the given closure.
public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral {
return SQLLiteral(elements: [.map(self, transform)])
}
func sql(_ context: inout SQLGenerationContext) -> String {
return elements.map { $0.sql(&context) }.joined()
}
@@ -165,21 +153,21 @@ extension SQLLiteral {
}
extension SQLLiteral {
/// Creates an SQL literal expression.
/// Creates a literal SQL expression.
///
/// SQLLiteral(sql: "1 + 2").sqlExpression
/// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression
/// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression
public var sqlExpression: SQLExpression {
return SQLExpressionLiteral(sqlLiteral: self)
return _SQLExpressionLiteral(sqlLiteral: self)
}
var sqlSelectable: SQLSelectable {
return SQLSelectionLiteral(sqlLiteral: self)
return _SQLSelectionLiteral(sqlLiteral: self)
}
var sqlOrderingTerm: SQLOrderingTerm {
return SQLOrderingLiteral(sqlLiteral: self)
return _SQLOrderingLiteral(sqlLiteral: self)
}
}
@@ -245,7 +233,7 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
}
}
// MARK: - SQLExpressionLiteral
// MARK: - _SQLExpressionLiteral
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -257,50 +245,17 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
///
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
public struct SQLExpressionLiteral: SQLExpression {
private struct _SQLExpressionLiteral: SQLExpression {
private let sqlLiteral: SQLLiteral
public var sql: String { return sqlLiteral.sql }
public var arguments: StatementArguments { return sqlLiteral.arguments }
// Prefer SQLLiteral.sqlExpression
fileprivate init(sqlLiteral: SQLLiteral) {
init(sqlLiteral: SQLLiteral) {
self.sqlLiteral = sqlLiteral
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral(sql: "1 + 2")
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
@available(*, deprecated, message: "Use SQLiteral.sqlExpression instead")
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
self.init(sqlLiteral: SQLLiteral(sql: sql, arguments: arguments))
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral(literal: SQLLiteral(sql: "1 + 2")
/// SQLExpressionLiteral(literal: SQLLiteral(sql: "? + ?", arguments: [1, 2]))
/// SQLExpressionLiteral(literal: SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// SQLExpressionLiteral(literal: "\(1) + \(2)")
@available(*, deprecated, message: "Use SQLiteral.sqlExpression instead")
public init(literal sqlLiteral: SQLLiteral) {
self.init(sqlLiteral: sqlLiteral)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
@@ -309,14 +264,14 @@ public struct SQLExpressionLiteral: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return sqlLiteral.qualified(with: alias).sqlExpression
}
}
// MARK: - SQLSelectionLiteral
// MARK: - _SQLSelectionLiteral
private struct SQLSelectionLiteral: SQLSelectable {
private struct _SQLSelectionLiteral: SQLSelectable {
private let sqlLiteral: SQLLiteral
// Prefer SQLLiteral.sqlSelectable
@@ -331,21 +286,24 @@ private struct SQLSelectionLiteral: SQLSelectable {
func countedSQL(_ context: inout SQLGenerationContext) -> String {
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several SQLExpressionLiteral instead.
To resolve this error, select one or several literal expressions instead. \
See SQLLiteral.sqlExpression.
""")
}
func count(distinct: Bool) -> SQLCount? {
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several SQLExpressionLiteral instead.
To resolve this error, select one or several literal expressions instead. \
See SQLLiteral.sqlExpression.
""")
}
func columnCount(_ db: Database) throws -> Int {
fatalError("""
Selection literals don't known how many columns they contain. \
To resolve this error, select one or several SQLExpressionLiteral instead.
To resolve this error, select one or several literal expressions instead. \
See SQLLiteral.sqlExpression.
""")
}
@@ -354,9 +312,9 @@ private struct SQLSelectionLiteral: SQLSelectable {
}
}
// MARK: - SQLOrderingLiteral
// MARK: - _SQLOrderingLiteral
private struct SQLOrderingLiteral: SQLOrderingTerm {
private struct _SQLOrderingLiteral: SQLOrderingTerm {
private let sqlLiteral: SQLLiteral
// Prefer SQLLiteral.sqlOrderingTerm
-49
View File
@@ -153,27 +153,6 @@ public class Statement {
_ = try arguments.extractBindings(forStatement: self, allowingRemainingValues: false)
}
/// Throws a DatabaseError of code SQLITE_ERROR if arguments don't fill all
/// statement arguments.
///
/// For example:
///
/// let statement = try db.makeUpdateArgument(sql: """
/// INSERT INTO player (id, name) VALUES (?, ?)
/// """)
///
/// // OK
/// statement.validate([1, "Arthur"])
///
/// // Throws
/// statement.validate([1])
///
/// See also setArguments(_:)
@available(*, deprecated, renamed: "validateArguments(_:)")
public func validate(arguments: StatementArguments) throws {
try validateArguments(arguments)
}
/// Set arguments without any validation. Trades safety for performance.
///
/// Only call this method if you are sure input arguments match all expected
@@ -214,34 +193,6 @@ public class Statement {
}
}
/// Set arguments without any validation. Trades safety for performance.
///
/// Only call this method if you are sure input arguments match all expected
/// arguments of the statement.
///
/// For example:
///
/// let statement = try db.makeUpdateArgument(sql: """
/// INSERT INTO player (id, name) VALUES (?, ?)
/// """)
///
/// // OK
/// statement.unsafeSetArguments([1, "Arthur"])
///
/// // OK
/// let arguments: StatementArguments = ... // some untrusted arguments
/// try statement.validateArguments(arguments)
/// statement.unsafeSetArguments(arguments)
///
/// // NOT OK
/// statement.unsafeSetArguments([1])
///
/// See also setArguments(_:)
@available(*, deprecated, renamed: "setUncheckedArguments(_:)")
public func unsafeSetArguments(_ arguments: StatementArguments) {
setUncheckedArguments(arguments)
}
/// Set the statement arguments, or throws a DatabaseError of code
/// SQLITE_ERROR if arguments don't fill all statement arguments.
///
-44
View File
@@ -31,7 +31,6 @@ public struct FTS3Pattern {
self.rawPattern = rawPattern
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
@@ -70,49 +69,6 @@ public struct FTS3Pattern {
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
#else
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAnyTokenIn: "") // nil
/// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(OSX 10.10, *)
public init?(matchingAnyTokenIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
/// Creates a pattern that matches all tokens found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS3Pattern(matchingAllTokensIn: "") // nil
/// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(OSX 10.10, *)
public init?(matchingAllTokensIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
/// Creates a pattern that matches a contiguous string; returns nil if no
/// pattern could be built.
///
/// FTS3Pattern(matchingPhrase: "") // nil
/// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(OSX 10.10, *)
public init?(matchingPhrase string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
#endif
}
extension FTS3Pattern: DatabaseValueConvertible {
-40
View File
@@ -32,7 +32,6 @@ public struct FTS3TokenizerDescriptor {
/// See https://www.sqlite.org/fts3.html#tokenizer
public static let porter = FTS3TokenizerDescriptor("porter")
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The "unicode61" tokenizer.
///
/// db.create(virtualTable: "book", using: FTS4()) { t in
@@ -56,35 +55,6 @@ public struct FTS3TokenizerDescriptor {
{
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#else
/// The "unicode61" tokenizer.
///
/// db.create(virtualTable: "book", using: FTS4()) { t in
/// t.tokenizer = .unicode61()
/// }
///
/// - parameters:
/// - diacritics: By default SQLite will strip diacritics from
/// latin characters.
/// - separators: Unless empty (the default), SQLite will consider these
/// characters as token separators.
/// - tokenCharacters: Unless empty (the default), SQLite will consider
/// these characters as token characters.
///
/// See https://www.sqlite.org/fts3.html#tokenizer
@available(OSX 10.10, *)
public static func unicode61(
diacritics: FTS3.Diacritics = .removeLegacy,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#endif
private static func _unicode61(
diacritics: FTS3.Diacritics,
@@ -118,24 +88,14 @@ public struct FTS3TokenizerDescriptor {
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
func tokenize(_ string: String) -> [String] {
return _tokenize(string)
}
#else
@available(OSX 10.10, *)
func tokenize(_ string: String) -> [String] {
return _tokenize(string)
}
#endif
/// Returns an array of tokens found in the string argument.
///
/// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"]
private func _tokenize(_ string: String) -> [String] {
// fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return DatabaseQueue().inDatabase { db in
var tokenizerChunks: [String] = []
tokenizerChunks.append(name)
-26
View File
@@ -261,7 +261,6 @@ public final class FTS4ColumnDefinition {
self.isLanguageId = false
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "document", using: FTS4()) { t in
@@ -272,36 +271,11 @@ public final class FTS4ColumnDefinition {
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
///
/// - returns: Self so that you can further refine the column definition.
/// :nodoc:
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
#else
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "document", using: FTS4()) { t in
/// t.column("a")
/// t.column("b").notIndexed()
/// }
///
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
///
/// - returns: Self so that you can further refine the column definition.
@available(OSX 10.10, *)
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
#endif
/// Uses the column as the Int32 language id hidden column.
///
-271
View File
@@ -1,271 +0,0 @@
import Dispatch
// Fixits for changes introduced by GRDB 4.0.0
extension Cursor {
@available(*, unavailable, renamed: "compactMap")
public func flatMap<ElementOfResult>(
_ transform: @escaping (Element) throws -> ElementOfResult?)
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
{ preconditionFailure() }
}
extension DatabaseWriter {
@available(*, unavailable, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() }
}
extension ValueObservation {
@available(*, unavailable, message: "Provide the reducer in a (Database) -> Reducer closure")
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer)
-> ValueObservation
{ preconditionFailure() }
@available(*, unavailable, message: "Use removeDuplicates() instead")
public static func tracking<Value>(
_ regions: DatabaseRegionConvertible...,
fetchDistinct fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Value>>>
where Value: Equatable
{ preconditionFailure() }
}
@available(*, unavailable, renamed: "FastDatabaseValueCursor")
public typealias ColumnCursor<Value> = FastDatabaseValueCursor<Value>
where Value: DatabaseValueConvertible & StatementColumnConvertible
@available(*, unavailable, renamed: "FastNullableDatabaseValueCursor")
public typealias NullableColumnCursor<Value> = FastNullableDatabaseValueCursor<Value>
where Value: DatabaseValueConvertible & StatementColumnConvertible
extension Database {
@available(*, unavailable, renamed: "execute(sql:arguments:)")
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws { preconditionFailure() }
@available(*, unavailable, renamed: "makeSelectStatement(sql:)")
public func makeSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() }
@available(*, unavailable, renamed: "cachedSelectStatement(sql:)")
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() }
@available(*, unavailable, renamed: "makeUpdateStatement(sql:)")
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() }
@available(*, unavailable, renamed: "cachedUpdateStatement(sql:)")
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() }
}
extension DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{ preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{ preconditionFailure() }
}
extension Row {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RowCursor
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Row]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Row?
{ preconditionFailure() }
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{ preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{ preconditionFailure() }
}
extension FetchableRecord {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RecordCursor<Self>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{ preconditionFailure() }
}
extension SQLRequest {
@available(*, unavailable, renamed: "init(sql:arguments:adapter:cached:)")
public init(
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil,
cached: Bool = false)
{ preconditionFailure() }
}
extension SQLExpressionLiteral {
@available(*, unavailable, renamed: "init(sql:arguments:)")
public init(_ sql: String, arguments: StatementArguments? = nil) { preconditionFailure() }
}
extension SQLExpression {
@available(*, unavailable, message: "Use sqlLiteral property instead")
public var literal: SQLExpressionLiteral { preconditionFailure() }
}
extension FTS3TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(
removeDiacritics: Bool,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{ preconditionFailure() }
}
#if SQLITE_ENABLE_FTS5
extension FTS5TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(
removeDiacritics: Bool = true,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS5TokenizerDescriptor
{ preconditionFailure() }
}
#endif
extension DatabaseValue {
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil)
-> T
where T: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil)
-> T?
where T: DatabaseValueConvertible
{ preconditionFailure() }
}
extension ValueScheduling {
@available(*, unavailable, renamed: "async(onQueue:startImmediately:)")
public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool)
-> ValueScheduling
{ preconditionFailure() }
}
extension ValueObservation {
// swiftlint:disable:next line_length
@available(*, unavailable, message: "Observation extent is controlled by the lifetime of observers returned by the start() method.")
public var extent: Database.TransactionObservationExtent {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
extension Configuration {
@available(*, unavailable, message: "Run the PRAGMA cipher_page_size in Configuration.prepareDatabase instead.")
public var cipherPageSize: Int {
get { preconditionFailure() }
set { preconditionFailure() }
}
@available(*, unavailable, message: "Run the PRAGMA kdf_iter in Configuration.prepareDatabase instead.")
public var kdfIterations: Int {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
+200
View File
@@ -0,0 +1,200 @@
// Fixits for changes introduced by GRDB 5.0.0
#if os(iOS)
import UIKit
#endif
extension AnyFetchRequest {
@available(*, unavailable, message: "Define your own FetchRequest type instead.")
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
{ preconditionFailure() }
}
extension AssociationAggregate {
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ name: String) -> AssociationAggregate<RowDecoder>
{ preconditionFailure() }
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder>
{ preconditionFailure() }
}
extension DatabaseMigrator {
@available(*, unavailable, renamed: "registerMigration(_:migrate:)")
public mutating func registerMigrationWithDeferredForeignKeyCheck(
_ identifier: String,
migrate: @escaping (Database) throws -> Void)
{ preconditionFailure() }
@available(*, unavailable, message: "Wrap this method: reader.read(migrator.appliedMigrations) }")
public func appliedMigrations(in reader: DatabaseReader) throws -> Set<String>
{ preconditionFailure() }
@available(*, unavailable, message: "Wrap this method: reader.read(migrator.hasCompletedMigrations) }")
public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool
{ preconditionFailure() }
@available(*, unavailable, message: "Prefer reader.read(migrator.completedMigrations).contains(targetIdentifier)")
public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool
{ preconditionFailure() }
@available(*, unavailable, message: "Prefer reader.read(migrator.completedMigrations).last")
public func lastCompletedMigration(in reader: DatabaseReader) throws -> String?
{ preconditionFailure() }
}
extension DatabasePool {
#if os(iOS)
@available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.")
public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() }
#endif
}
extension DatabaseQueue {
#if os(iOS)
@available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.")
public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() }
#endif
}
extension FetchRequest {
@available(*, unavailable, message: "Use makePreparedRequest(_:forSingleResult:) instead.")
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
{ preconditionFailure() }
}
extension SQLExpression {
@available(*, unavailable, message: "Use SQLLiteral initializer instead")
public var sqlLiteral: SQLLiteral
{ preconditionFailure() }
}
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
public struct SQLExpressionLiteral: SQLExpression {
public var sql: String { preconditionFailure() }
public var arguments: StatementArguments { preconditionFailure() }
public init(sql: String, arguments: StatementArguments = StatementArguments())
{ preconditionFailure() }
public init(literal sqlLiteral: SQLLiteral)
{ preconditionFailure() }
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String
{ preconditionFailure() }
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression
{ preconditionFailure() }
}
extension SQLLiteral {
@available(*, unavailable, message: "Use SQL interpolation instead.")
public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral
{ preconditionFailure() }
}
@available(*, unavailable, renamed: "SQLAssociativeBinaryOperator")
typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator
extension SQLSpecificExpressible {
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ name: String) -> SQLSelectable
{ preconditionFailure() }
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ key: CodingKey) -> SQLSelectable
{ preconditionFailure() }
}
extension Statement {
@available(*, unavailable, renamed: "setUncheckedArguments(_:)")
public func unsafeSetArguments(_ arguments: StatementArguments)
{ preconditionFailure() }
@available(*, unavailable, renamed: "validateArguments(_:)")
public func validate(arguments: StatementArguments) throws
{ preconditionFailure() }
}
extension ValueObservation where Reducer == Void {
@available(*, unavailable, message: "Use request.observationForCount() instead")
public static func trackingCount<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Int>>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use request.observationForAll() instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.AllValues<Request.RowDecoder>>
where Request.RowDecoder: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable, message: "Use request.observationForFirst() instead")
public static func trackingOne<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.AllValues<Request.RowDecoder>>
where Request.RowDecoder: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable, message: "Use request.observationForAll() instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.AllOptionalValues<Request.RowDecoder._Wrapped>>
where Request.RowDecoder: _OptionalProtocol,
Request.RowDecoder._Wrapped: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable, message: "Use request.observationForAll() instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.AllRecords<Request.RowDecoder>>
where Request.RowDecoder: FetchableRecord
{ preconditionFailure() }
@available(*, unavailable, message: "Use request.observationForFirst() instead")
public static func trackingOne<Request: FetchRequest>(_ request: Request) ->
ValueObservation<ValueReducers.OneRecord<Request.RowDecoder>>
where Request.RowDecoder: FetchableRecord
{ preconditionFailure() }
@available(*, unavailable, message: "Use request.observationForAll() instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.AllRows>
where Request.RowDecoder == Row
{ preconditionFailure() }
@available(*, unavailable, message: "Use request.observationForFirst() instead")
public static func trackingOne<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.OneRow>
where Request.RowDecoder == Row
{ preconditionFailure() }
}
extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable {
@available(*, unavailable, renamed: "removeDuplicates")
public func distinctUntilChanged() -> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
{ preconditionFailure() }
}
extension ValueReducer where Value: Equatable {
@available(*, unavailable, renamed: "removeDuplicates")
public func distinctUntilChanged() -> ValueReducers.RemoveDuplicates<Self>
{ preconditionFailure() }
}
#if SQLITE_HAS_CODEC
extension Configuration {
@available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.")
public var passphrase: String? {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
extension DatabasePool {
@available(*, unavailable, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws { preconditionFailure() }
}
extension DatabaseQueue {
@available(*, unavailable, message: "Use Database.changePassphrase(_:) instead")
public func change(passphrase: String) throws { preconditionFailure() }
}
#endif
+1 -63
View File
@@ -93,28 +93,6 @@ public struct DatabaseMigrator {
registerMigration(Migration(identifier: identifier, migrate: migrate))
}
/// Registers a migration.
///
/// migrator.registerMigrationWithDeferredForeignKeyCheck("createAuthors") { db in
/// try db.create(table: "author") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("creationDate", .datetime)
/// t.column("name", .text).notNull()
/// }
/// }
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
@available(*, deprecated, renamed: "registerMigration(_:migrate:)")
public mutating func registerMigrationWithDeferredForeignKeyCheck(
_ identifier: String,
migrate: @escaping (Database) throws -> Void)
{
registerMigration(identifier, migrate: migrate)
}
// MARK: - Applying Migrations
/// Iterate migrations in the same order as they were registered. If a
@@ -176,15 +154,6 @@ public struct DatabaseMigrator {
// MARK: - Querying Migrations
/// Returns the set of applied migration identifiers.
///
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
/// - throws: An eventual database error.
@available(*, deprecated, message: "Wrap this method: reader.read(migrator.appliedMigrations) }")
public func appliedMigrations(in reader: DatabaseReader) throws -> Set<String> {
return try Set(reader.read(appliedMigrations))
}
/// Returns the applied migration identifiers, in the same order as
/// registered migrations.
///
@@ -216,15 +185,6 @@ public struct DatabaseMigrator {
.map { $0.0 })
}
/// Returns true if all migrations are applied.
///
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
/// - throws: An eventual database error.
@available(*, deprecated, message: "Wrap this method: reader.read(migrator.hasCompletedMigrations) }")
public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool {
return try reader.read(hasCompletedMigrations)
}
/// Returns true if all migrations are applied.
///
/// - parameter db: A database connection.
@@ -232,29 +192,7 @@ public struct DatabaseMigrator {
public func hasCompletedMigrations(_ db: Database) throws -> Bool {
return try completedMigrations(db).last == migrations.last?.identifier
}
/// Returns true if all migrations up to the provided target are applied,
/// and maybe further.
///
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
/// - parameter targetIdentifier: The identifier of a registered migration.
/// - throws: An eventual database error.
@available(*, deprecated, message: "Prefer reader.read(migrator.completedMigrations).contains(targetIdentifier)")
public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool {
return try reader.read(completedMigrations).contains(targetIdentifier)
}
/// Returns the identifier of the last migration for which all predecessors
/// have been applied.
///
/// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool).
/// - returns: An eventual migration identifier.
/// - throws: An eventual database error.
@available(*, deprecated, message: "Prefer reader.read(migrator.completedMigrations).last")
public func lastCompletedMigration(in reader: DatabaseReader) throws -> String? {
return try reader.read(completedMigrations).last
}
// MARK: - Non public
private mutating func registerMigration(_ migration: Migration) {
@@ -71,20 +71,6 @@ public struct AssociationAggregate<RowDecoder> {
}
extension AssociationAggregate: KeyPathRefining {
/// Returns an aggregate that is selected in a column with the given name.
///
/// For example:
///
/// let aggregate = Author.books.count.aliased("numberOfBooks")
/// let request = Author.annotated(with: aggregate)
/// if let row = try Row.fetchOne(db, request) {
/// let numberOfBooks: Int = row["numberOfBooks"]
/// }
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ name: String) -> AssociationAggregate<RowDecoder> {
return forKey(name)
}
/// Returns an aggregate that is selected in a column with the given name.
///
/// For example:
@@ -98,26 +84,6 @@ extension AssociationAggregate: KeyPathRefining {
return with(\.key, key)
}
/// Returns an aggregate that is selected in a column named like the given
/// coding key.
///
/// For example:
///
/// struct AuthorInfo: Decodable, FetchableRecord {
/// var author: Author
/// var numberOfBooks: Int
///
/// static func fetchAll(_ db: Database) throws -> [AuthorInfo] {
/// let aggregate = Author.books.count.aliased(CodingKeys.numberOfBooks)
/// let request = Author.annotated(with: aggregate)
/// return try AuthorInfo.fetchAll(db, request)
/// }
/// }
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder> {
return forKey(key)
}
/// Returns an aggregate that is selected in a column named like the given
/// coding key.
///
@@ -1,16 +1,6 @@
// MARK: - SQLExpression
extension SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Converts an expression to an SQLLiteral
///
/// :nodoc:
@available(*, deprecated, message: "Use SQLLiteral initializer instead")
public var sqlLiteral: SQLLiteral {
return SQLLiteral(self)
}
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
///
/// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'""
@@ -243,9 +233,6 @@ public struct SQLAssociativeBinaryOperator: Hashable {
}
}
@available(*, deprecated, renamed: "SQLAssociativeBinaryOperator")
typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator
/// SQLExpressionBinary is an expression made of two expressions joined with a
/// binary operator.
///
@@ -39,22 +39,6 @@ extension SQLSpecificExpressible {
/// :nodoc:
extension SQLSpecificExpressible {
/// Give the expression the given SQL name.
///
/// For example:
///
/// // SELECT (width * height) AS area FROM shape
/// let area = (Column("width") * Column("height")).aliased("area")
/// let request = Shape.select(area)
/// if let row = try Row.fetchOne(db, request) {
/// let area: Int = row["area"]
/// }
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ name: String) -> SQLSelectable {
return forKey(name)
}
/// Give the expression the given SQL name.
///
/// For example:
@@ -69,29 +53,6 @@ extension SQLSpecificExpressible {
return SQLAliasedExpression(sqlExpression, name: key)
}
/// Give the expression the same SQL name as the coding key.
///
/// For example:
///
/// struct Shape: Decodable, FetchableRecord, TableRecord {
/// let width: Int
/// let height: Int
/// let area: Int
///
/// static let databaseSelection: [SQLSelectable] = [
/// Column(CodingKeys.width),
/// Column(CodingKeys.height),
/// (Column(CodingKeys.width) * Column(CodingKeys.height)).aliased(CodingKeys.area),
/// ]
/// }
///
/// // SELECT width, height, (width * height) AS area FROM shape
/// let shapes: [Shape] = try Shape.fetchAll(db)
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ key: CodingKey) -> SQLSelectable {
return forKey(key)
}
/// Give the expression the same SQL name as the coding key.
///
/// For example:
@@ -2,7 +2,6 @@ extension Database {
// MARK: - Database Schema
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates a database table.
///
/// try db.create(table: "place") { t in
@@ -42,88 +41,6 @@ extension Database {
let sql = try definition.sql(self)
try execute(sql: sql)
}
#else
/// Creates a database table.
///
/// try db.create(table: "place") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("title", .text)
/// t.column("favorite", .boolean).notNull().default(false)
/// t.column("longitude", .double).notNull()
/// t.column("latitude", .double).notNull()
/// }
///
/// See https://www.sqlite.org/lang_createtable.html and
/// https://www.sqlite.org/withoutrowid.html
///
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@available(OSX 10.10, *)
public func create(
table name: String,
temporary: Bool = false,
ifNotExists: Bool = false,
withoutRowID: Bool,
body: (TableDefinition) -> Void)
throws
{
// WITHOUT ROWID was added in SQLite 3.8.2 http://www.sqlite.org/changes.html#version_3_8_2
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = TableDefinition(
name: name,
temporary: temporary,
ifNotExists: ifNotExists,
withoutRowID: withoutRowID)
body(definition)
let sql = try definition.sql(self)
try execute(sql: sql)
}
/// Creates a database table.
///
/// try db.create(table: "place") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("title", .text)
/// t.column("favorite", .boolean).notNull().default(false)
/// t.column("longitude", .double).notNull()
/// t.column("latitude", .double).notNull()
/// }
///
/// See https://www.sqlite.org/lang_createtable.html
///
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create(
table name: String,
temporary: Bool = false,
ifNotExists: Bool = false,
body: (TableDefinition) -> Void)
throws
{
let definition = TableDefinition(
name: name,
temporary: temporary,
ifNotExists: ifNotExists,
withoutRowID: false)
body(definition)
let sql = try definition.sql(self)
try execute(sql: sql)
}
#endif
/// Renames a database table.
///
@@ -162,7 +79,6 @@ extension Database {
try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)")
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates an index.
///
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
@@ -192,9 +108,6 @@ extension Database {
condition: SQLExpressible? = nil)
throws
{
// Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(
name: name,
table: table,
@@ -205,85 +118,6 @@ extension Database {
let sql = definition.sql()
try execute(sql: sql)
}
#else
/// Creates an index.
///
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
///
/// SQLite can also index expressions (https://www.sqlite.org/expridx.html)
/// and use specific collations. To create such an index, use a raw SQL
/// query.
///
/// try db.execute(sql: "CREATE INDEX ...")
///
/// See https://www.sqlite.org/lang_createindex.html
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - unique: If true, creates a unique index.
/// - ifNotExists: If false, no error is thrown if index already exists.
public func create(
index name: String,
on table: String,
columns: [String],
unique: Bool = false,
ifNotExists: Bool = false)
throws
{
// Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(
name: name,
table: table,
columns: columns,
unique: unique,
ifNotExists: ifNotExists,
condition: nil)
let sql = definition.sql()
try execute(sql: sql)
}
/// Creates a partial index.
///
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"], condition: Column("email") != nil)
///
/// See https://www.sqlite.org/lang_createindex.html, and
/// https://www.sqlite.org/partialindex.html
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - unique: If true, creates a unique index.
/// - ifNotExists: If false, no error is thrown if index already exists.
/// - condition: The condition that indexed rows must verify.
@available(OSX 10.10, *)
public func create(
index name: String,
on table: String,
columns: [String],
unique: Bool = false,
ifNotExists: Bool = false,
condition: SQLExpressible)
throws
{
// Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(
name: name,
table: table,
columns: columns,
unique: unique,
ifNotExists: ifNotExists,
condition: condition.sqlExpression)
let sql = definition.sql()
try execute(sql: sql)
}
#endif
/// Deletes a database index.
///
@@ -64,38 +64,3 @@ extension TableRecord {
return all().observationForCount()
}
}
extension ValueObservation where Reducer == Void {
// MARK: - Count Observation
/// Creates a ValueObservation which observes *request*, and notifies its
/// count whenever it is modified by a database transaction.
///
/// For example:
///
/// let request = Player.all()
/// let observation = ValueObservation.trackingCount(request)
///
/// let observer = try observation.start(in: dbQueue) { count: Int in
/// print("Number of players has changed")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter request: the observed request.
/// - returns: a ValueObservation.
@available(*, deprecated, message: "Use request.observationForCount() instead")
public static func trackingCount<Request: FetchRequest>(_ request: Request)
-> ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Int>>>
{
return request.observationForCount()
}
}
@@ -124,107 +124,6 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
}
}
extension ValueObservation where Reducer == Void {
// MARK: - DatabaseValueConvertible Observation
/// Creates a ValueObservation which observes *request*, and notifies
/// fresh values whenever the request is modified by a
/// database transaction.
///
/// For example:
///
/// let request = Player.select(Column("name"), as: String.self)
/// let observation = ValueObservation.trackingAll(request)
///
/// let observer = try observation.start(in: dbQueue) { names: [String] in
/// print("Player names have changed")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter request: the observed request.
/// - returns: a ValueObservation.
@available(*, deprecated, message: "Use request.observationForAll() instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<DatabaseValuesReducer<Request.RowDecoder>>
where Request.RowDecoder: DatabaseValueConvertible
{
return request.observationForAll()
}
/// Creates a ValueObservation which observes *request*, and notifies a
/// fresh value whenever the request is modified by a database transaction.
///
/// For example:
///
/// let request = Player.select(max(Column("score")), as: Int.self)
/// let observation = ValueObservation.trackingOne(request)
///
/// let observer = try observation.start(in: dbQueue) { maxScore: Int? in
/// print("Maximum score has changed")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter request: the observed request.
/// - returns: a ValueObservation.
@available(*, deprecated, message: "Use request.observationForFirst() instead")
public static func trackingOne<Request: FetchRequest>(_ request: Request)
-> ValueObservation<DatabaseValueReducer<Request.RowDecoder>>
where Request.RowDecoder: DatabaseValueConvertible
{
return request.observationForFirst()
}
/// Creates a ValueObservation which observes *request*, and notifies
/// fresh values whenever the request is modified by a
/// database transaction.
///
/// For example:
///
/// let request = Player.select(Column("name"), as: Optional<String>.self)
/// let observation = ValueObservation.trackingAll(request)
///
/// let observer = try observation.start(in: dbQueue) { names: [String?] in
/// print("Player names have changed")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter request: the observed request.
/// - returns: a ValueObservation.
@available(*, deprecated, message: "Use request.observationForAll() instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<OptionalDatabaseValuesReducer<Request.RowDecoder._Wrapped>>
where Request.RowDecoder: _OptionalProtocol,
Request.RowDecoder._Wrapped: DatabaseValueConvertible
{
return request.observationForAll()
}
}
extension ValueReducers {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -332,18 +231,3 @@ extension ValueReducers {
}
}
}
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.AllValues")
public typealias DatabaseValuesReducer<RowDecoder> = ValueReducers.AllValues<RowDecoder>
where RowDecoder: DatabaseValueConvertible
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.OneValue")
public typealias DatabaseValueReducer<RowDecoder> = ValueReducers.OneValue<RowDecoder>
where RowDecoder: DatabaseValueConvertible
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.AllOptionalValues")
public typealias OptionalDatabaseValuesReducer<RowDecoder> = ValueReducers.AllOptionalValues<RowDecoder>
where RowDecoder: DatabaseValueConvertible
@@ -118,74 +118,6 @@ extension TableRecord where Self: FetchableRecord {
}
}
extension ValueObservation where Reducer == Void {
// MARK: - FetchableRecord Observation
/// Creates a ValueObservation which observes *request*, and notifies
/// fresh records whenever the request is modified by a
/// database transaction.
///
/// For example:
///
/// let request = Player.all()
/// let observation = ValueObservation.trackingAll(request)
///
/// let observer = try observation.start(in: dbQueue) { players: [Player] in
/// print("Players have changed")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter request: the observed request.
/// - returns: a ValueObservation.
@available(*, deprecated, message: "Use request.observationForAll() instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<FetchableRecordsReducer<Request.RowDecoder>>
where Request.RowDecoder: FetchableRecord
{
return request.observationForAll()
}
/// Creates a ValueObservation which observes *request*, and notifies a
/// fresh record whenever the request is modified by a database transaction.
///
/// For example:
///
/// let request = Player.filter(key: 1)
/// let observation = ValueObservation.trackingOne(request)
///
/// let observer = try observation.start(in: dbQueue) { player: Player? in
/// print("Player has changed")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter request: the observed request.
/// - returns: a ValueObservation.
@available(*, deprecated, message: "Use request.observationForFirst() instead")
public static func trackingOne<Request: FetchRequest>(_ request: Request) ->
ValueObservation<FetchableRecordReducer<Request.RowDecoder>>
where Request.RowDecoder: FetchableRecord
{
return request.observationForFirst()
}
}
extension ValueReducers {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -247,15 +179,3 @@ extension ValueReducers {
}
}
}
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.AllRecords")
public typealias FetchableRecordsReducer<RowDecoder>
= ValueReducers.AllRecords<RowDecoder>
where RowDecoder: FetchableRecord
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.OneRecord")
public typealias FetchableRecordReducer<RowDecoder>
= ValueReducers.OneRecord<RowDecoder>
where RowDecoder: FetchableRecord
@@ -59,73 +59,6 @@ extension FetchRequest where RowDecoder == Row {
}
}
extension ValueObservation where Reducer == Void {
// MARK: - Row Observation
/// Creates a ValueObservation which observes *request*, and notifies
/// fresh rows whenever the request is modified by a database transaction.
///
/// For example:
///
/// let request = SQLRequest<Row>(sql: "SELECT * FROM player")
/// let observation = ValueObservation.trackingAll(request)
///
/// let observer = try observation.start(in: dbQueue) { rows: [Row] in
/// print("Players have changed")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter request: the observed request.
/// - returns: a ValueObservation.
@available(*, deprecated, message: "Use request.observationForAll() instead")
public static func trackingAll<Request: FetchRequest>(_ request: Request)
-> ValueObservation<RowsReducer>
where Request.RowDecoder == Row
{
return request.observationForAll()
}
/// Creates a ValueObservation which observes *request*, and notifies a
/// fresh row whenever the request is modified by a database transaction.
///
/// For example:
///
/// let request = SQLRequest<Row>(sql: "SELECT * FROM player WHERE id = ?", arguments: [1])
/// let observation = ValueObservation.trackingOne(request)
///
/// let observer = try observation.start(in: dbQueue) { row: Row? in
/// print("Players have changed")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter request: the observed request.
/// - returns: a ValueObservation.
@available(*, deprecated, message: "Use request.observationForFirst() instead")
public static func trackingOne<Request: FetchRequest>(_ request: Request)
-> ValueObservation<RowReducer>
where Request.RowDecoder == Row
{
return request.observationForFirst()
}
}
extension ValueReducers {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -183,11 +116,3 @@ extension ValueReducers {
}
}
}
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.AllRows")
public typealias RowsReducer = ValueReducers.AllRows
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.OneRow")
public typealias RowReducer = ValueReducers.OneRow
@@ -44,7 +44,3 @@ extension ValueReducers {
}
}
}
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.CompactMap")
public typealias CompactMapValueReducer<Base, Value> = ValueReducers.CompactMap<Base, Value> where Base: ValueReducer
@@ -20,7 +20,3 @@ extension ValueReducers {
}
}
}
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.Fetch")
public typealias RawValueReducer<Value> = ValueReducers.Fetch<Value>
@@ -47,7 +47,3 @@ extension ValueReducers {
}
}
}
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.Map")
public typealias MapValueReducer<Base, Value> = ValueReducers.Map<Base, Value> where Base: ValueReducer
@@ -1,12 +1,4 @@
extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable {
/// Returns a ValueObservation which filters out consecutive equal values.
@available(*, deprecated, renamed: "removeDuplicates")
public func distinctUntilChanged()
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
{
return removeDuplicates()
}
/// Returns a ValueObservation which filters out consecutive equal values.
public func removeDuplicates()
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
@@ -16,14 +8,6 @@ extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable
}
extension ValueReducer where Value: Equatable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns a ValueReducer which filters out consecutive equal values.
@available(*, deprecated, renamed: "removeDuplicates")
public func distinctUntilChanged() -> ValueReducers.RemoveDuplicates<Self> {
return removeDuplicates()
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns a ValueReducer which filters out consecutive equal values.
@@ -63,8 +47,3 @@ extension ValueReducers {
}
}
}
/// :nodoc:
@available(*, deprecated, renamed: "ValueReducers.RemoveDuplicates")
public typealias DistinctUntilChangedValueReducer<Base> = ValueReducers.RemoveDuplicates<Base>
where Base: ValueReducer, Base.Value: Equatable
+6 -6
View File
@@ -28,8 +28,8 @@
5613ED7021A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */; };
5613EDA321A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */; };
5613EDA421A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */; };
561408A0221596A100DAD589 /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-4.0.swift */; };
561408A1221596A100DAD589 /* GRDB-4.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-4.0.swift */; };
561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-5.0.swift */; };
561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-5.0.swift */; };
5615B258222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; };
5615B259222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; };
5615B26D222AFEB300061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B26C222AFEB300061C1C /* AssociationHasOneThroughRowScopeTests.swift */; };
@@ -745,7 +745,7 @@
5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = "<group>"; };
5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = "<group>"; };
5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = "<group>"; };
5614089E221596A100DAD589 /* GRDB-4.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-4.0.swift"; sourceTree = "<group>"; };
5614089E221596A100DAD589 /* GRDB-5.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-5.0.swift"; sourceTree = "<group>"; };
5615B256222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLDerivationTests.swift; sourceTree = "<group>"; };
5615B26C222AFEB300061C1C /* AssociationHasOneThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughRowScopeTests.swift; sourceTree = "<group>"; };
5615B277222B109500061C1C /* AssociationHasOneThroughFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughFetchableRecordTests.swift; sourceTree = "<group>"; };
@@ -1206,7 +1206,7 @@
5614089D221596A100DAD589 /* Fixit */ = {
isa = PBXGroup;
children = (
5614089E221596A100DAD589 /* GRDB-4.0.swift */,
5614089E221596A100DAD589 /* GRDB-5.0.swift */,
);
path = Fixit;
sourceTree = "<group>";
@@ -2250,7 +2250,7 @@
F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */,
5656A8802295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
561408A1221596A100DAD589 /* GRDB-4.0.swift in Sources */,
561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */,
F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */,
56FBFED72210731100945324 /* SQLRequest.swift in Sources */,
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */,
@@ -2589,7 +2589,7 @@
F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */,
5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
561408A0221596A100DAD589 /* GRDB-4.0.swift in Sources */,
561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */,
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */,
56FBFED62210731100945324 /* SQLRequest.swift in Sources */,
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */,
+1 -1
View File
@@ -1742,7 +1742,7 @@ When the same query will be used several times in the lifetime of your applicati
**Don't cache statements yourself.**
> :point_up: **Note**: This is because you don't have the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which you don't manage yourself, especially when you use [database pools](#database-pools). A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement. On systems earlier than OSX 10.10 that don't have the [sqlite3_close_v2 function](https://www.sqlite.org/c3ref/close.html), SQLite connections won't close properly if statements have been kept alive.
> :point_up: **Note**: This is because you don't have the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which you don't manage yourself, especially when you use [database pools](#database-pools). A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement.
Instead, use the `cachedUpdateStatement` and `cachedSelectStatement` methods. GRDB does all the hard caching and [memory management](#memory-management) stuff for you:
@@ -45,7 +45,7 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Player.joining(required: Player.defaultTeam)
let (_, adapter) = try request.prepare(db, forSingleResult: false)
let adapter = try request.makePreparedRequest(db, forSingleResult: false).adapter
XCTAssertNil(adapter)
}
}
@@ -61,7 +61,7 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = A.joining(required: A.defaultC)
let (_, adapter) = try request.prepare(db, forSingleResult: false)
let adapter = try request.makePreparedRequest(db, forSingleResult: false).adapter
XCTAssertNil(adapter)
}
}
@@ -110,8 +110,6 @@ private class UserPersistableRecord2 : PersistableRecord {
private struct UserRowRequest : FetchRequest {
struct CustomType { }
typealias RowDecoder = CustomType
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() }
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { preconditionFailure() }
}
@@ -176,7 +176,7 @@ class DatabaseConfigurationTests: GRDBTestCase {
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let queue = DispatchQueue.global(priority: .default)
let queue = DispatchQueue.global(qos: .default)
let group = DispatchGroup()
queue.async(group: group) {
+13 -32
View File
@@ -8,14 +8,11 @@ import XCTest
class DatabaseErrorTests: GRDBTestCase {
func testDatabaseErrorMessage() {
// Error messages are not always available
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
// We don't test for actual messages, since they may depend on SQLite version
XCTAssertEqual(DatabaseError().resultCode, .SQLITE_ERROR)
XCTAssertNotNil(DatabaseError().message)
XCTAssertNotNil(DatabaseError(resultCode: .SQLITE_BUSY).message)
XCTAssertNotEqual(DatabaseError().message, DatabaseError(resultCode: .SQLITE_BUSY).message)
}
// We don't test for actual messages, since they may depend on SQLite version
XCTAssertEqual(DatabaseError().resultCode, .SQLITE_ERROR)
XCTAssertNotNil(DatabaseError().message)
XCTAssertNotNil(DatabaseError(resultCode: .SQLITE_BUSY).message)
XCTAssertNotEqual(DatabaseError().message, DatabaseError(resultCode: .SQLITE_BUSY).message)
}
func testDatabaseErrorInTransaction() throws {
@@ -30,9 +27,7 @@ class DatabaseErrorTests: GRDBTestCase {
return .commit
}
} catch let error as DatabaseError {
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
@@ -67,9 +62,7 @@ class DatabaseErrorTests: GRDBTestCase {
}
}
} catch let error as DatabaseError {
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
@@ -90,9 +83,7 @@ class DatabaseErrorTests: GRDBTestCase {
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
XCTFail()
} catch let error as DatabaseError {
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
@@ -107,9 +98,7 @@ class DatabaseErrorTests: GRDBTestCase {
try statement.execute(arguments: [1, "Bobby"])
XCTFail()
} catch let error as DatabaseError {
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
@@ -125,9 +114,7 @@ class DatabaseErrorTests: GRDBTestCase {
try statement.execute()
XCTFail()
} catch let error as DatabaseError {
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
@@ -147,9 +134,7 @@ class DatabaseErrorTests: GRDBTestCase {
""")
XCTFail()
} catch let error as DatabaseError {
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
@@ -166,9 +151,7 @@ class DatabaseErrorTests: GRDBTestCase {
do {
try db.execute(sql: "INSERT INTO children (parentId) VALUES (1)")
} catch let error as DatabaseError {
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode.rawValue, 19) // primary SQLITE_CONSTRAINT
}
}
@@ -184,9 +167,7 @@ class DatabaseErrorTests: GRDBTestCase {
} catch let error as NSError {
XCTAssertEqual(DatabaseError.errorDomain, "GRDB.DatabaseError")
XCTAssertEqual(error.domain, DatabaseError.errorDomain)
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
XCTAssert([19, 787].contains(error.code))
XCTAssertEqual(error.code, 787)
}
}
}
+1 -206
View File
@@ -159,9 +159,7 @@ class DatabaseMigratorTests : GRDBTestCase {
// The first migration should be committed.
// The second migration should be rollbacked.
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
@@ -173,11 +171,6 @@ class DatabaseMigratorTests : GRDBTestCase {
}
func testForeignKeyViolation() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, tmp TEXT)")
@@ -230,112 +223,6 @@ class DatabaseMigratorTests : GRDBTestCase {
}
}
func testMigrationWithDeferredForeignKeyChecksDeprecated() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, tmp TEXT)")
try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
try db.execute(sql: "INSERT INTO persons (name) VALUES ('Arthur')")
let personId = db.lastInsertedRowID
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, 'Bobby')", arguments:[personId])
}
migrator.registerMigrationWithDeferredForeignKeyCheck("removePersonTmpColumn") { db in
// Test the technique described at https://www.sqlite.org/lang_altertable.html#otheralter
try db.execute(sql: "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute(sql: "INSERT INTO new_persons SELECT id, name FROM persons")
try db.execute(sql: "DROP TABLE persons")
try db.execute(sql: "ALTER TABLE new_persons RENAME TO persons")
}
migrator.registerMigrationWithDeferredForeignKeyCheck("foreignKeyError") { db in
// Make sure foreign keys are checked at the end.
try db.execute(sql: "INSERT INTO persons (name) VALUES ('Barbara')")
do {
// triggers foreign key error, but not now.
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"])
} catch {
XCTFail("Error not expected at this point")
}
}
let dbQueue = try makeDatabaseQueue()
do {
try migrator.migrate(dbQueue)
XCTFail("Expected error")
} catch let error as DatabaseError {
// Migration 1 and 2 should be committed.
// Migration 3 should not be committed.
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.message!, "FOREIGN KEY constraint failed")
XCTAssertTrue(error.sql == nil)
XCTAssertEqual(error.description, "SQLite error 19: FOREIGN KEY constraint failed")
try dbQueue.inDatabase { db in
// Arthur inserted (migration 1), Barbara (migration 3) not inserted.
var rows = try Row.fetchAll(db, sql: "SELECT * FROM persons")
XCTAssertEqual(rows.count, 1)
var row = rows.first!
XCTAssertEqual(row["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 = try Row.fetchAll(db, sql: "SELECT * FROM pets")
XCTAssertEqual(rows.count, 1)
row = rows.first!
XCTAssertEqual(row["name"] as String, "Bobby")
}
}
}
func testAppliedMigrationsDeprecated() throws {
var migrator = DatabaseMigrator()
// No migration
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), [])
}
// One migration
migrator.registerMigration("1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer)
}
}
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), [])
try migrator.migrate(dbQueue, upTo: "1")
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"])
}
// Two migrations
migrator.registerMigration("2") { db in
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
}
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), [])
try migrator.migrate(dbQueue, upTo: "1")
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"])
try migrator.migrate(dbQueue, upTo: "2")
try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1", "2"])
}
}
func testAppliedMigrations() throws {
var migrator = DatabaseMigrator()
@@ -378,98 +265,6 @@ class DatabaseMigratorTests : GRDBTestCase {
}
}
func testHasCompletedMigrationsDeprecated() throws {
var migrator = DatabaseMigrator()
// No migration
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue))
}
// One migration
migrator.registerMigration("1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer)
}
}
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue))
try migrator.migrate(dbQueue, upTo: "1")
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue))
}
// Two migrations
migrator.registerMigration("2") { db in
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
}
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2"))
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue))
try migrator.migrate(dbQueue, upTo: "1")
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2"))
try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue))
try migrator.migrate(dbQueue, upTo: "2")
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1"))
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "2"))
try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue))
}
}
func testLastCompletedMigrationDeprecated() throws {
var migrator = DatabaseMigrator()
// No migration
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue))
}
// One migration
migrator.registerMigration("1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer)
}
}
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue))
try migrator.migrate(dbQueue, upTo: "1")
try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1")
}
// Two migrations
migrator.registerMigration("2") { db in
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
}
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue))
try migrator.migrate(dbQueue, upTo: "1")
try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1")
try migrator.migrate(dbQueue, upTo: "2")
try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "2")
}
}
func testCompletedMigrations() throws {
var migrator = DatabaseMigrator()
@@ -36,7 +36,6 @@ class DatabasePoolBackupTests: GRDBTestCase {
}
// TODO: fix flaky test
// @available(OSX 10.10, *)
// func testConcurrentWriteDuringBackup() throws {
// let source = try makeDatabasePool(filename: "source.sqlite")
// let destination = try makeDatabasePool(filename: "destination.sqlite")
@@ -1185,91 +1185,87 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// MARK: - Barrier
func testBarrierLocksReads() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
var fetchedValue: Int?
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let s3 = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
try! dbPool.barrierWriteWithoutTransaction { db in
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
s1.signal()
s2.wait()
}
}
DispatchQueue.global().async {
// Wait for barrier to start
s1.wait()
fetchedValue = try! dbPool.read { db in
try Int.fetchOne(db, sql: "SELECT id FROM items")!
}
expectation.fulfill()
s3.signal()
}
// Assert that read is blocked
waitForExpectations(timeout: 1)
// Release barrier
s2.signal()
// Wait for read to complete
s3.wait()
XCTAssertEqual(fetchedValue, 1)
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
var fetchedValue: Int?
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let s3 = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
try! dbPool.barrierWriteWithoutTransaction { db in
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
s1.signal()
s2.wait()
}
}
DispatchQueue.global().async {
// Wait for barrier to start
s1.wait()
fetchedValue = try! dbPool.read { db in
try Int.fetchOne(db, sql: "SELECT id FROM items")!
}
expectation.fulfill()
s3.signal()
}
// Assert that read is blocked
waitForExpectations(timeout: 1)
// Release barrier
s2.signal()
// Wait for read to complete
s3.wait()
XCTAssertEqual(fetchedValue, 1)
}
func testBarrierIsLockedByOneUnfinishedRead() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let s3 = DispatchSemaphore(value: 0)
let s4 = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
try! dbPool.read { _ in
s1.signal()
s2.signal()
s3.wait()
}
}
DispatchQueue.global().async {
// Wait for read to start
s1.wait()
dbPool.barrierWriteWithoutTransaction { _ in }
expectation.fulfill()
s4.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release read
s3.signal()
// Wait for barrier to complete
s4.wait()
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let s3 = DispatchSemaphore(value: 0)
let s4 = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
try! dbPool.read { _ in
s1.signal()
s2.signal()
s3.wait()
}
}
DispatchQueue.global().async {
// Wait for read to start
s1.wait()
dbPool.barrierWriteWithoutTransaction { _ in }
expectation.fulfill()
s4.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release read
s3.signal()
// Wait for barrier to complete
s4.wait()
}
// MARK: - Concurrent opening
-8
View File
@@ -266,14 +266,6 @@ class DatabaseTests : GRDBTestCase {
}
func testFailedCommitIsRollbacked() throws {
// PRAGMA defer_foreign_keys = ON was introduced in SQLite 3.12.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE parent (id INTEGER PRIMARY KEY)")
-158
View File
@@ -606,163 +606,5 @@ class EncryptionTests: GRDBTestCase {
}
}
}
// MARK: - Deprecated
func testDeprecatedPassphrase() throws {
do {
var config = Configuration()
config.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
}
}
do {
var config = Configuration()
config.passphrase = "secret"
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 1)
}
}
do {
var config = Configuration()
config.passphrase = nil
do {
_ = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_NOTADB)
XCTAssertEqual(error.message!, "file is not a database")
}
}
}
func testDeprecatedDatabaseQueueWithPassphraseToDatabaseQueueWithNewPassphrase() throws {
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.change(passphrase: "newSecret")
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO data (value) VALUES (2)")
}
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("newSecret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
}
func testDeprecatedDatabaseQueueWithPassphraseToDatabasePoolWithNewPassphrase() throws {
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.change(passphrase: "newSecret")
try dbPool.write { db in
try db.execute(sql: "INSERT INTO data (value) VALUES (2)")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("newSecret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
}
func testDeprecatedDatabasePoolWithPassphraseToDatabasePoolWithNewPassphrase() throws {
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.write { db in
try db.execute(sql: "CREATE TABLE data (value INTEGER)")
try db.execute(sql: "INSERT INTO data (value) VALUES (1)")
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("secret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.change(passphrase: "newSecret")
try dbPool.write { db in
try db.execute(sql: "INSERT INTO data (value) VALUES (2)")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
do {
var config = Configuration()
config.prepareDatabase = { db in
try db.usePassphrase("newSecret")
}
let dbPool = try makeDatabasePool(filename: "test.sqlite", configuration: config)
try dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM data")!, 2)
}
}
}
}
#endif
-18
View File
@@ -70,12 +70,6 @@ class FTS3PatternTests: GRDBTestCase {
}
func testFTS3PatternWithAnyToken() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let wrongInputs = ["", "*", "^", " ", "(", "()", "\"", "?!"]
for string in wrongInputs {
if let pattern = FTS3Pattern(matchingAnyTokenIn: string) {
@@ -106,12 +100,6 @@ class FTS3PatternTests: GRDBTestCase {
}
func testFTS3PatternWithAllTokens() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let wrongInputs = ["", "*", "^", " ", "(", "()", "\"", "?!"]
for string in wrongInputs {
if let pattern = FTS3Pattern(matchingAllTokensIn: string) {
@@ -142,12 +130,6 @@ class FTS3PatternTests: GRDBTestCase {
}
func testFTS3PatternWithPhrase() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let wrongInputs = ["", "*", "^", " ", "(", "()", "\"", "?!"]
for string in wrongInputs {
if let pattern = FTS3Pattern(matchingPhrase: string) {
@@ -61,12 +61,6 @@ class FTS3TableBuilderTests: GRDBTestCase {
}
func testUnicode61Tokenizer() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
@@ -77,12 +71,6 @@ class FTS3TableBuilderTests: GRDBTestCase {
}
func testUnicode61TokenizerDiacriticsKeep() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
@@ -105,12 +93,6 @@ class FTS3TableBuilderTests: GRDBTestCase {
#endif
func testUnicode61TokenizerSeparators() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
@@ -121,12 +103,6 @@ class FTS3TableBuilderTests: GRDBTestCase {
}
func testUnicode61TokenizerTokenCharacters() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
-24
View File
@@ -58,12 +58,6 @@ class FTS3TokenizerTests: GRDBTestCase {
}
func testUnicode61Tokenizer() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
@@ -85,12 +79,6 @@ class FTS3TokenizerTests: GRDBTestCase {
}
func testUnicode61TokenizerDiacriticsKeep() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
@@ -135,12 +123,6 @@ class FTS3TokenizerTests: GRDBTestCase {
#endif
func testUnicode61TokenizerSeparators() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
@@ -155,12 +137,6 @@ class FTS3TokenizerTests: GRDBTestCase {
}
func testUnicode61TokenizerTokenCharacters() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
+1 -30
View File
@@ -61,12 +61,6 @@ class FTS4TableBuilderTests: GRDBTestCase {
}
func testUnicode61Tokenizer() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS4()) { t in
@@ -77,12 +71,6 @@ class FTS4TableBuilderTests: GRDBTestCase {
}
func testUnicode61TokenizerDiacriticsKeep() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS4()) { t in
@@ -92,6 +80,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
}
}
// TODO: why only custom SQLite build?
#if GRDBCUSTOMSQLITE
func testUnicode61TokenizerDiacriticsRemove() throws {
let dbQueue = try makeDatabaseQueue()
@@ -105,12 +94,6 @@ class FTS4TableBuilderTests: GRDBTestCase {
#endif
func testUnicode61TokenizerSeparators() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS4()) { t in
@@ -121,12 +104,6 @@ class FTS4TableBuilderTests: GRDBTestCase {
}
func testUnicode61TokenizerTokenCharacters() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS4()) { t in
@@ -156,12 +133,6 @@ class FTS4TableBuilderTests: GRDBTestCase {
}
func testNotIndexedColumns() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "books", using: FTS4()) { t in
-27
View File
@@ -7,33 +7,6 @@ import XCTest
class FetchRequestTests: GRDBTestCase {
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
func testDeprecatedPrepareMethod() throws {
struct CustomRequest : FetchRequest {
typealias RowDecoder = Row
// This method is deprecated but we must support it
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
return try (db.makeSelectStatement(sql: "SELECT * FROM table1"), nil)
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "table1") { t in
t.column("id", .integer).primaryKey()
}
try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES")
try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES")
let request = CustomRequest()
let rows = try request.fetchAll(db)
XCTAssertEqual(lastSQLQuery, "SELECT * FROM table1")
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id": 1])
XCTAssertEqual(rows[1], ["id": 2])
}
}
func testRequestFetchRows() throws {
struct CustomRequest : FetchRequest {
typealias RowDecoder = Row
+155 -165
View File
@@ -67,188 +67,178 @@ class PoolTests: XCTestCase {
}
func testBarrierLocksElements() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 1)
var element: Int?
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let s3 = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier {
s1.signal()
s2.wait()
}
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 1)
var element: Int?
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let s3 = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier {
s1.signal()
s2.wait()
}
DispatchQueue.global().async {
// Wait for barrier to start
s1.wait()
let first = try! pool.get()
element = first.element
first.release()
expectation.fulfill()
s3.signal()
}
// Assert that get() is blocked
waitForExpectations(timeout: 1)
// Release barrier
s2.signal()
// Wait for get() to complete
s3.wait()
XCTAssertEqual(element, 1)
}
DispatchQueue.global().async {
// Wait for barrier to start
s1.wait()
let first = try! pool.get()
element = first.element
first.release()
expectation.fulfill()
s3.signal()
}
// Assert that get() is blocked
waitForExpectations(timeout: 1)
// Release barrier
s2.signal()
// Wait for get() to complete
s3.wait()
XCTAssertEqual(element, 1)
}
func testBarrierIsLockedByOneUsedElementOutOfOne() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 1)
// Get element
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier { }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release element
first.release()
// Wait for barrier to complete
s.wait()
// Get and release recycled element
let second = try pool.get()
XCTAssertEqual(second.element, 1)
second.release()
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 1)
// Get element
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier { }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release element
first.release()
// Wait for barrier to complete
s.wait()
// Get and release recycled element
let second = try pool.get()
XCTAssertEqual(second.element, 1)
second.release()
}
func testBarrierIsLockedByOneUsedElementOutOfTwo() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 2)
// Get elements
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let second = try pool.get()
XCTAssertEqual(second.element, 2)
// Release first element
first.release()
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier { }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release second element
second.release()
// Wait for barrier to complete
s.wait()
// Get and release recycled element
let third = try pool.get()
XCTAssertEqual(third.element, 1)
third.release()
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 2)
// Get elements
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let second = try pool.get()
XCTAssertEqual(second.element, 2)
// Release first element
first.release()
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier { }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release second element
second.release()
// Wait for barrier to complete
s.wait()
// Get and release recycled element
let third = try pool.get()
XCTAssertEqual(third.element, 1)
third.release()
}
func testBarrierIsLockedByTwoUsedElementsOutOfTwo() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 2)
// Get elements
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let second = try pool.get()
XCTAssertEqual(second.element, 2)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier { }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release elements
first.release()
second.release()
// Wait for barrier to complete
s.wait()
// Get and release recycled element
let third = try pool.get()
XCTAssertEqual(third.element, 1)
third.release()
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 2)
// Get elements
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let second = try pool.get()
XCTAssertEqual(second.element, 2)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
pool.barrier { }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release elements
first.release()
second.release()
// Wait for barrier to complete
s.wait()
// Get and release recycled element
let third = try pool.get()
XCTAssertEqual(third.element, 1)
third.release()
}
func testBarrierRemoveAll() throws {
if #available(OSX 10.10, *) {
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 1)
// Get element
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
// No deadlock
pool.barrier { pool.removeAll() }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release element
first.release()
// Wait for barrier to complete
s.wait()
// Get and release new element
let second = try pool.get()
XCTAssertEqual(second.element, 2)
second.release()
let expectation = self.expectation(description: "lock")
expectation.isInverted = true
let pool = makeCounterPool(maximumCount: 1)
// Get element
let first = try pool.get()
XCTAssertEqual(first.element, 1)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
// No deadlock
pool.barrier { pool.removeAll() }
expectation.fulfill()
s.signal()
}
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
// Release element
first.release()
// Wait for barrier to complete
s.wait()
// Get and release new element
let second = try pool.get()
XCTAssertEqual(second.element, 2)
second.release()
}
}
@@ -37,21 +37,7 @@ func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression {
// CAST
private func castDeprecated(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression {
let literal = value.sqlExpression.sqlLiteral
let castLiteral = literal.mapSQL { sql in
"CAST(\(sql) AS \(type.rawValue))"
}
return SQLExpressionLiteral(literal: castLiteral)
}
private func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression {
return SQLLiteral(value.sqlExpression)
.mapSQL({ sql in "CAST(\(sql) AS \(type.rawValue))" })
.sqlExpression
}
private func castInterpolated<T: SQLExpressible>(_ value: T, as type: Database.ColumnType) -> SQLExpression {
private func cast<T: SQLExpressible>(_ value: T, as type: Database.ColumnType) -> SQLExpression {
return SQLLiteral("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression
}
@@ -96,37 +82,6 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase {
}
}
func testCastDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
t.column("text", .text)
}
struct Record : TableRecord {
static let databaseTableName = "records"
}
try db.execute(sql: "INSERT INTO records (text) VALUES (?)", arguments: ["foo"])
do {
let request = Record.select(castDeprecated(Column("text"), as: .blob))
let dbValue = try DatabaseValue.fetchOne(db, request)!
switch dbValue.storage {
case .blob:
break
default:
XCTFail("Expected data blob")
}
XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\" LIMIT 1")
}
do {
let request = Record.select(castDeprecated(Column("text"), as: .blob) && true)
_ = try DatabaseValue.fetchOne(db, request)!
XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) AND 1 FROM \"records\" LIMIT 1")
}
}
}
func testCast() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -157,35 +112,4 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase {
}
}
}
func testCastInterpolated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
t.column("text", .text)
}
struct Record : TableRecord {
static let databaseTableName = "records"
}
try db.execute(sql: "INSERT INTO records (text) VALUES (?)", arguments: ["foo"])
do {
let request = Record.select(castInterpolated(Column("text"), as: .blob))
let dbValue = try DatabaseValue.fetchOne(db, request)!
switch dbValue.storage {
case .blob:
break
default:
XCTFail("Expected data blob")
}
XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\" LIMIT 1")
}
do {
let request = Record.select(castInterpolated(Column("text"), as: .blob) && true)
_ = try DatabaseValue.fetchOne(db, request)!
XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) AND 1 FROM \"records\" LIMIT 1")
}
}
}
}
@@ -44,7 +44,7 @@ class QueryInterfaceRequestTests: GRDBTestCase {
func testSimpleRequestDoesNotUseAnyRowAdapter() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let (_, adapter) = try Reader.all().prepare(db, forSingleResult: false)
let adapter = try Reader.all().makePreparedRequest(db, forSingleResult: false).adapter
XCTAssertNil(adapter)
}
}
+2 -2
View File
@@ -129,8 +129,8 @@ class SQLLiteralTests: GRDBTestCase {
}
do {
// Test mapSQL plus qualification
let literal = SQLLiteral(Column("name")).mapSQL { sql in "\(sql) || 'foo'" }
// Test qualification of interpolated literal
let literal: SQLLiteral = "\(Column("name")) || 'foo'"
let request = Player.aliased(TableAlias(name: "p")).select(literal.sqlExpression)
try assertEqualSQL(db, request, """
SELECT "p"."name" || 'foo' FROM "player" "p"
+12 -12
View File
@@ -11,9 +11,9 @@ class SQLRequestTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = SQLRequest<Row>(sql: "SELECT 1")
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
XCTAssertEqual(statement.sql, "SELECT 1")
XCTAssertNil(adapter)
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
XCTAssertEqual(preparedRequest.statement.sql, "SELECT 1")
XCTAssertNil(preparedRequest.adapter)
let row = try request.fetchOne(db)
XCTAssertEqual(row, ["1": 1])
}
@@ -23,9 +23,9 @@ class SQLRequestTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = SQLRequest<Int>(sql: "SELECT ?, ?", arguments: [1, 2], adapter: SuffixRowAdapter(fromIndex: 1))
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
XCTAssertEqual(statement.sql, "SELECT ?, ?")
XCTAssertNotNil(adapter)
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
XCTAssertEqual(preparedRequest.statement.sql, "SELECT ?, ?")
XCTAssertNotNil(preparedRequest.adapter)
let int = try request.fetchOne(db)!
XCTAssertEqual(int, 2)
}
@@ -35,9 +35,9 @@ class SQLRequestTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = SQLRequest<Row>(sql: "SELECT 1")
let (statement1, _) = try request.prepare(db, forSingleResult: false)
let (statement2, _) = try request.prepare(db, forSingleResult: false)
XCTAssertTrue(statement1 !== statement2)
let preparedRequest1 = try request.makePreparedRequest(db, forSingleResult: false)
let preparedRequest2 = try request.makePreparedRequest(db, forSingleResult: false)
XCTAssertTrue(preparedRequest1.statement !== preparedRequest2.statement)
}
}
@@ -45,9 +45,9 @@ class SQLRequestTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = SQLRequest<Row>(sql: "SELECT 1", cached: true)
let (statement1, _) = try request.prepare(db, forSingleResult: false)
let (statement2, _) = try request.prepare(db, forSingleResult: false)
XCTAssertTrue(statement1 === statement2)
let preparedRequest1 = try request.makePreparedRequest(db, forSingleResult: false)
let preparedRequest2 = try request.makePreparedRequest(db, forSingleResult: false)
XCTAssertTrue(preparedRequest1.statement === preparedRequest2.statement)
}
}
+7 -24
View File
@@ -35,25 +35,14 @@ class TableDefinitionTests: GRDBTestCase {
func testTableCreationOptions() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
if #available(iOS 8.2, OSX 10.10, *) {
try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in
t.column("id", .integer).primaryKey()
}
assertEqualSQL(
lastSQLQuery,
("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" +
"\"id\" INTEGER PRIMARY KEY" +
") WITHOUT ROWID") as String)
} else {
try db.create(table: "test", temporary: true, ifNotExists: true) { t in
t.column("id", .integer).primaryKey()
}
assertEqualSQL(
lastSQLQuery,
("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" +
"\"id\" INTEGER PRIMARY KEY" +
")") as String)
try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in
t.column("id", .integer).primaryKey()
}
assertEqualSQL(
lastSQLQuery,
("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" +
"\"id\" INTEGER PRIMARY KEY" +
") WITHOUT ROWID") as String)
}
}
@@ -568,12 +557,6 @@ class TableDefinitionTests: GRDBTestCase {
}
func testCreatePartialIndex() throws {
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "test") { t in
@@ -11,40 +11,6 @@ import XCTest
#endif
class ValueObservationCountTests: GRDBTestCase {
func testCountDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
var counts: [Int] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 5
struct T: TableRecord { }
let observation = ValueObservation.trackingCount(T.all())
let observer = try observation.start(in: dbQueue) { count in
counts.append(count)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1
try db.execute(sql: "UPDATE t SET id = id") // =
try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "DELETE FROM t WHERE id = 1")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 2") // -1
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(counts, [0, 1, 2, 3, 2])
}
}
func testCount() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
@@ -28,42 +28,6 @@ private struct Name: DatabaseValueConvertible {
}
class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase {
func testAllDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
var results: [[Name]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
let observation = ValueObservation.trackingAll(SQLRequest<Name>(sql: "SELECT name FROM t ORDER BY id"))
let observer = try observation.start(in: dbQueue) { names in
results.append(names)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map { $0.rawValue }}, [
[],
["foo"],
["foo", "bar"],
["bar"]])
}
}
func testAll() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
@@ -100,50 +64,6 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase {
}
}
func testOneDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
var results: [Name?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 7
let observation = ValueObservation.trackingOne(SQLRequest<Name>(sql: "SELECT name FROM t ORDER BY id DESC"))
let observer = try observation.start(in: dbQueue) { name in
results.append(name)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'baz')")
try db.execute(sql: "UPDATE t SET name = NULL")
try db.execute(sql: "DELETE FROM t")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)")
try db.execute(sql: "UPDATE t SET name = 'qux'")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map { $0.rawValue }}, [
nil,
"foo",
"bar",
nil,
"baz",
nil,
"qux"])
}
}
func testOne() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
@@ -188,42 +108,6 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase {
}
}
func testAllOptionalDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
var results: [[Name?]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
let observation = ValueObservation.trackingAll(SQLRequest<Name?>(sql: "SELECT name FROM t ORDER BY id"))
let observer = try observation.start(in: dbQueue) { names in
results.append(names)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, NULL)")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map { $0?.rawValue }}, [
[],
["foo"],
["foo", nil],
[nil]])
}
}
func testAllOptional() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
@@ -52,38 +52,6 @@ class ValueObservationFetchTests: GRDBTestCase {
try test(makeDatabasePool())
}
func testDistinctUntilChangedDeprecated() throws {
func test(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
var counts: [Int] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 3
let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
}).distinctUntilChanged()
let observer = try observation.start(in: dbWriter) { count in
counts.append(count)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbWriter.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "UPDATE t SET id = id")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(counts, [0, 1, 2])
}
}
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
func testRemoveDuplicated() throws {
func test(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
@@ -49,41 +49,6 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
}
}
func testOneRowWithPrefetchedRowsDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
var results: [Row?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: Row.self)
let observation = ValueObservation.trackingOne(request)
let observer = try observation.start(in: dbQueue) { row in
results.append(row)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0]!.unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[0]!.prefetchedRows["children"], [
["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1],
["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]])
XCTAssertEqual(results[1]!.unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[1]!.prefetchedRows["children"], [])
}
}
func testOneRowWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
@@ -118,49 +83,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
XCTAssertEqual(results[1]!.prefetchedRows["children"], [])
}
}
func testAllRowsWithPrefetchedRowsDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
var results: [[Row]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: Row.self)
let observation = ValueObservation.trackingAll(request)
let observer = try observation.start(in: dbQueue) { rows in
results.append(rows)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0].count, 2)
XCTAssertEqual(results[0][0].unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[0][0].prefetchedRows["children"], [
["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1],
["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]])
XCTAssertEqual(results[0][1].unscoped, ["id": 2, "name": "bar"])
XCTAssertEqual(results[0][1].prefetchedRows["children"], [
["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]])
XCTAssertEqual(results[1].count, 2)
XCTAssertEqual(results[1][0].unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[1][0].prefetchedRows["children"], [])
XCTAssertEqual(results[1][1].unscoped, ["id": 2, "name": "bar"])
XCTAssertEqual(results[1][1].prefetchedRows["children"], [])
}
}
func testAllRowsWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
@@ -203,43 +126,6 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
}
}
func testOneRecordWithPrefetchedRowsDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
var results: [ParentInfo?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
let observation = ValueObservation.trackingOne(request)
let observer = try observation.start(in: dbQueue) { parentInfo in
results.append(parentInfo)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: [
Child(id: 1, parentId: 1, name: "fooA"),
Child(id: 2, parentId: 1, name: "fooB"),
]),
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: []),
])
}
}
func testOneRecordWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
@@ -277,55 +163,6 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
}
}
func testAllRecordsWithPrefetchedRowsDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
var results: [[ParentInfo]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
let observation = ValueObservation.trackingAll(request)
let observer = try observation.start(in: dbQueue) { parentInfos in
results.append(parentInfos)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
[
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: [
Child(id: 1, parentId: 1, name: "fooA"),
Child(id: 2, parentId: 1, name: "fooB"),
]),
ParentInfo(
parent: Parent(id: 2, name: "bar"),
children: [
Child(id: 3, parentId: 2, name: "barA"),
]),
],
[
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: []),
ParentInfo(
parent: Parent(id: 2, name: "bar"),
children: []),
],
])
}
}
func testAllRecordsWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
@@ -26,42 +26,6 @@ private struct Player: TableRecord, FetchableRecord {
}
class ValueObservationRecordTests: GRDBTestCase {
func testAllDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
var results: [[Player]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
let observation = ValueObservation.trackingAll(SQLRequest<Player>(sql: "SELECT * FROM t ORDER BY id"))
let observer = try observation.start(in: dbQueue) { players in
results.append(players)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map { $0.row }}, [
[],
[["id":1, "name":"foo"]],
[["id":1, "name":"foo"], ["id":2, "name":"bar"]],
[["id":2, "name":"bar"]]])
}
}
func testAll() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
@@ -133,43 +97,7 @@ class ValueObservationRecordTests: GRDBTestCase {
[["id":2, "name":"bar"]]])
}
}
func testOneDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
var results: [Player?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
let observation = ValueObservation.trackingOne(SQLRequest<Player>(sql: "SELECT * FROM t ORDER BY id DESC"))
let observer = try observation.start(in: dbQueue) { player in
results.append(player)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t") // -1
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map { $0.row }}, [
nil,
["id":1, "name":"foo"],
["id":2, "name":"bar"],
nil])
}
}
func testOne() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
@@ -11,42 +11,6 @@ import XCTest
#endif
class ValueObservationRowTests: GRDBTestCase {
func testAllDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
var results: [[Row]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
let observation = ValueObservation.trackingAll(SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id"))
let observer = try observation.start(in: dbQueue) { rows in
results.append(rows)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
[],
[["id":1, "name":"foo"]],
[["id":1, "name":"foo"], ["id":2, "name":"bar"]],
[["id":2, "name":"bar"]]])
}
}
func testAll() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
@@ -83,42 +47,6 @@ class ValueObservationRowTests: GRDBTestCase {
}
}
func testOneDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
var results: [Row?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
let observation = ValueObservation.trackingOne(SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id DESC"))
let observer = try observation.start(in: dbQueue) { row in
results.append(row)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t") // -1
}
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
nil,
["id":1, "name":"foo"],
["id":2, "name":"bar"],
nil])
}
func testOne() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
@@ -50,7 +50,6 @@ class ValueObservationSchedulingTests: GRDBTestCase {
try test(makeDatabasePool())
}
@available(OSX 10.10, *) // DispatchQueue qos
func testMainQueueObservationStartedFromAnotherQueue() throws {
func test(_ dbWriter: DatabaseWriter) throws {
// We need something to change
@@ -49,14 +49,6 @@ private final class FTS3TokenizeTableDefinition {
class VirtualTableModuleTests: GRDBTestCase {
func testCustomVirtualTableModule() throws {
// fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "test", using: FTS3TokenizeModule()) { t in
@@ -68,14 +60,6 @@ class VirtualTableModuleTests: GRDBTestCase {
}
func testThrowingCustomVirtualTableModule() throws {
// fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 8.2, OSX 10.10, *) else {
return
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {