diff --git a/CHANGELOG.md b/CHANGELOG.md index cd6621e25..11040c11f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 6.17.0 + +Released August 26, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.16.0...v6.17.0) + +- **New**: [#1421](https://github.com/groue/GRDB.swift/pull/1421) by [@groue](https://github.com/groue): Make it possible to open a DatabaseQueue in the WAL mode + ## 6.16.0 Released July 9, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.1...v6.16.0) diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 24952f89f..1b20f7355 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.16.0' + s.version = '6.17.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 18d4736fd..780ce452a 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -288,6 +288,46 @@ public struct Configuration { /// of a read access. public var allowsUnsafeTransactions = false + // MARK: - Journal Mode + + /// Defines how the journal mode is configured when the database + /// connection is opened. + /// + /// Related SQLite documentation: + public enum JournalModeConfiguration { + /// The default setup has ``DatabaseQueue`` perform no specific + /// configuration of the journal mode, and ``DatabasePool`` + /// configure the database for the WAL mode (just like the + /// ``wal`` case). + case `default` + + /// The journal mode is set to WAL (plus extra configurations that + /// make life easier with WAL databases). + case wal + } + + /// Defines how the journal mode is configured when the database + /// connection is opened. + /// + /// This configuration is ignored when ``readonly`` is true. + /// + /// The default value has ``DatabaseQueue`` perform no specific + /// configuration of the journal mode, and ``DatabasePool`` configure + /// the database for the WAL mode. + /// + /// Applications that need to open a WAL database with a + /// ``DatabaseQueue`` should set the `journalMode` to `wal`: + /// + /// ```swift + /// // Open a WAL database with DatabaseQueue + /// var config = Configuration() + /// config.journalMode = .wal + /// let dbQueue = try DatabaseQueue(path: "...", configuration: config) + /// ``` + /// + /// Related SQLite documentation: + public var journalMode = JournalModeConfiguration.default + // MARK: - Concurrency /// Defines the how `SQLITE_BUSY` errors are handled. diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index bc3f9c4b7..e114c851c 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1343,10 +1343,6 @@ struct TableInfo: FetchableRecord { /// A value in the `type` column of `sqlite_master`. struct SchemaObjectType: Hashable, RawRepresentable, DatabaseValueConvertible { var rawValue: String - init(rawValue: String) { - self.rawValue = rawValue - } - static let index = SchemaObjectType(rawValue: "index") static let table = SchemaObjectType(rawValue: "table") static let trigger = SchemaObjectType(rawValue: "trigger") diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index c3fabdeaf..48d4ad74e 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -373,7 +373,7 @@ extension SQLStatementCursor: Cursor { let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0. // Compile next statement - var statementEnd: UnsafePointer? = nil + var statementEnd: UnsafePointer? = nil let statement = try Statement( database: database, statementStart: baseAddress + offset, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 266155cbb..86ef1b8fa 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -421,6 +421,41 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib configuration.SQLiteConnectionDidOpen?() } + /// Performs ``Configuration/JournalModeConfiguration/wal``. + func setUpWALMode() throws { + let journalMode = try String.fetchOne(self, sql: "PRAGMA journal_mode = WAL") + guard journalMode == "wal" else { + throw DatabaseError(message: "could not activate WAL Mode at path: \(path)") + } + + // https://www.sqlite.org/pragma.html#pragma_synchronous + // > Many applications choose NORMAL when in WAL mode + try execute(sql: "PRAGMA synchronous = NORMAL") + + // Make sure a non-empty wal file exists. + // + // The presence of the wal file avoids an SQLITE_CANTOPEN (14) + // error when the user opens a pool and reads from it. + // See . + // + // The non-empty wal file avoids an SQLITE_ERROR (1) error + // when the user opens a pool and creates a wal snapshot + // (which happens when starting a ValueObservation). + // See . + let walPath = path + "-wal" + if try FileManager.default.fileExists(atPath: walPath) == false + || (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0 + { + try inSavepoint { + try execute(sql: """ + CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); + DROP TABLE grdb_issue_102; + """) + return .commit + } + } + } + private func setupDoubleQuotedStringLiterals() { if configuration.acceptsDoubleQuotedStringLiterals { _enableDoubleQuotedStringLiterals(sqliteConnection) @@ -877,7 +912,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib _ mask: CInt, _ p: UnsafeMutableRawPointer?, _ x: UnsafeMutableRawPointer?, - _ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) + _ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) { guard let trace else { return } @@ -1896,7 +1931,7 @@ extension Database { public struct Statement: CustomStringConvertible { var sqliteStatement: SQLiteStatement var unexpandedSQL: UnsafePointer? - var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer? + var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer? var publicStatementArguments: Bool // See Configuration.publicStatementArguments /// The executed SQL, where bound parameters are not expanded. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 602cea60b..7dd0525fc 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -75,39 +75,12 @@ public final class DatabasePool { purpose: "reader.\(readerCount)") }) - // Activate WAL Mode unless readonly + // Set up journal mode unless readonly if !configuration.readonly { - try writer.sync { db in - let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = WAL") - guard journalMode == "wal" else { - throw DatabaseError(message: "could not activate WAL Mode at path: \(path)") - } - - // https://www.sqlite.org/pragma.html#pragma_synchronous - // > Many applications choose NORMAL when in WAL mode - try db.execute(sql: "PRAGMA synchronous = NORMAL") - - // Make sure a non-empty wal file exists. - // - // The presence of the wal file avoids an SQLITE_CANTOPEN (14) - // error when the user opens a pool and reads from it. - // See . - // - // The non-empty wal file avoids an SQLITE_ERROR (1) error - // when the user opens a pool and creates a wal snapshot - // (which happens when starting a ValueObservation). - // See . - let walPath = path + "-wal" - if try FileManager.default.fileExists(atPath: walPath) == false - || (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0 - { - try db.inSavepoint { - try db.execute(sql: """ - CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); - DROP TABLE grdb_issue_102; - """) - return .commit - } + switch configuration.journalMode { + case .default, .wal: + try writer.sync { + try $0.setUpWALMode() } } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 9912e05c0..79252cb25 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -50,6 +50,18 @@ public final class DatabaseQueue { configuration: configuration, defaultLabel: "GRDB.DatabaseQueue") + // Set up journal mode unless readonly + if !configuration.readonly { + switch configuration.journalMode { + case .default: + break + case .wal: + try writer.sync { + try $0.setUpWALMode() + } + } + } + setupSuspension() // Be a nice iOS citizen, and don't consume too much memory diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index b60c6a54c..5bec60a16 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -42,14 +42,15 @@ public final class Statement { public var sql: String { SchedulingWatchdog.preconditionValidQueue(database) - // trim white space and semicolumn for homogeneous output + // trim white space and semicolon for homogeneous output return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement } /// The column names, ordered from left to right. public lazy var columnNames: [String] = { + // swiftlint:disable:next redundant_self_in_closure let sqliteStatement = self.sqliteStatement - return (0.., - statementEnd: UnsafeMutablePointer?>, + statementStart: UnsafePointer, + statementEnd: UnsafeMutablePointer?>, prepFlags: CUnsignedInt) throws { SchedulingWatchdog.preconditionValidQueue(database) @@ -222,7 +223,7 @@ public final class Statement { private var _arguments = StatementArguments() lazy var sqliteArgumentCount: Int = { - Int(sqlite3_bind_parameter_count(self.sqliteStatement)) + Int(sqlite3_bind_parameter_count(sqliteStatement)) }() // Returns ["id", nil, "name"] for "INSERT INTO table VALUES (:id, ?, :name)" diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 5fe6f9dbe..e20883049 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -57,10 +57,10 @@ final class StatementAuthorizer { private func authorize( _ actionCode: CInt, - _ cString1: UnsafePointer?, - _ cString2: UnsafePointer?, - _ cString3: UnsafePointer?, - _ cString4: UnsafePointer?) + _ cString1: UnsafePointer?, + _ cString2: UnsafePointer?, + _ cString3: UnsafePointer?, + _ cString4: UnsafePointer?) -> CInt { // Uncomment when debugging diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index fd31c3724..954edb350 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -75,7 +75,7 @@ extension DatabaseDateComponents: StatementColumnConvertible { } let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen let components = cString.withMemoryRebound( - to: Int8.self, + to: CChar.self, capacity: length + 1 /* trailing \0 */) { cString in SQLiteDateParser().components(cString: cString, length: length) } diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 74db8e5fd..4f234749d 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -4,6 +4,7 @@ import Foundation @usableFromInline struct SQLiteDateParser { + // swiftlint:disable:next unneeded_synthesized_initializer @usableFromInline init() { } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 8cddd2984..24bbffae5 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -20,8 +20,8 @@ extension Database { // Drop cached statements that delete, because the addition of an // observer may change the need for truncate optimization prevention. - publicStatementCache.removeAll { $0.isDeleteStatement } - internalStatementCache.removeAll { $0.isDeleteStatement } + publicStatementCache.removeAll { $0.canDeleteRows } + internalStatementCache.removeAll { $0.canDeleteRows } observationBroker.add(transactionObserver: transactionObserver, extent: extent) } @@ -33,8 +33,8 @@ extension Database { // Drop cached statements that delete, because the removal of an // observer may change the need for truncate optimization prevention. - publicStatementCache.removeAll { $0.isDeleteStatement } - internalStatementCache.removeAll { $0.isDeleteStatement } + publicStatementCache.removeAll { $0.canDeleteRows } + internalStatementCache.removeAll { $0.canDeleteRows } observationBroker.remove(transactionObserver: transactionObserver) } @@ -1095,7 +1095,12 @@ public struct DatabaseEvent { self.impl = impl } - init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer?, tableNameCString: UnsafePointer?) { + init( + kind: Kind, + rowID: Int64, + databaseNameCString: UnsafePointer?, + tableNameCString: UnsafePointer?) + { self.init( kind: kind, rowID: rowID, @@ -1131,8 +1136,8 @@ private protocol DatabaseEventImpl { /// Optimization: MetalDatabaseEventImpl does not create Swift strings from raw /// SQLite char* until actually asked for databaseName or tableName. private struct MetalDatabaseEventImpl: DatabaseEventImpl { - let databaseNameCString: UnsafePointer? - let tableNameCString: UnsafePointer? + let databaseNameCString: UnsafePointer? + let tableNameCString: UnsafePointer? var databaseName: String { String(cString: databaseNameCString!) } var tableName: String { String(cString: tableNameCString!) } @@ -1267,8 +1272,8 @@ public struct DatabasePreUpdateEvent { kind: Kind, initialRowID: Int64, finalRowID: Int64, - databaseNameCString: UnsafePointer?, - tableNameCString: UnsafePointer?) + databaseNameCString: UnsafePointer?, + tableNameCString: UnsafePointer?) { self.init( kind: kind, @@ -1324,8 +1329,8 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { let connection: SQLiteConnection let kind: DatabasePreUpdateEvent.Kind - let databaseNameCString: UnsafePointer? - let tableNameCString: UnsafePointer? + let databaseNameCString: UnsafePointer? + let tableNameCString: UnsafePointer? var databaseName: String { String(cString: databaseNameCString!) } var tableName: String { String(cString: tableNameCString!) } diff --git a/GRDB/Documentation.docc/DatabaseSharing.md b/GRDB/Documentation.docc/DatabaseSharing.md index b83f56e60..3cc64120e 100644 --- a/GRDB/Documentation.docc/DatabaseSharing.md +++ b/GRDB/Documentation.docc/DatabaseSharing.md @@ -21,11 +21,13 @@ We'll address all of those challenges below. > > Always consider sharing plain files, or any other inter-process communication technique, before sharing an SQLite database. -## Use a Database Pool +## Use the WAL mode -In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database. +In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database because it allows multiple processes to access the database concurrently. -Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator]. +It is also possible to use a ``DatabaseQueue``, with the `.wal` ``Configuration/journalMode``. + +Since several processes may open the database at the same time, protect the creation of the database connection with an [NSFileCoordinator]. - In a process that can create and write in the database, use this sample code: diff --git a/GRDB/Documentation.docc/Extension/Configuration.md b/GRDB/Documentation.docc/Extension/Configuration.md index e2e4b2743..efb77b8a6 100644 --- a/GRDB/Documentation.docc/Extension/Configuration.md +++ b/GRDB/Documentation.docc/Extension/Configuration.md @@ -83,7 +83,9 @@ do { - ``acceptsDoubleQuotedStringLiterals`` - ``busyMode`` - ``foreignKeysEnabled`` +- ``journalMode`` - ``readonly`` +- ``JournalModeConfiguration`` ### Configuring GRDB Connections diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 333a2f226..43daaf5dd 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -143,9 +143,9 @@ public struct FTS5 { private static func api_v2( _ db: Database, // swiftlint:disable:next line_length - _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, CInt, CUnsignedInt, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> CInt, + _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, CInt, CUnsignedInt, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> CInt, // swiftlint:disable:next line_length - _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt) + _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt) -> UnsafePointer { var statement: SQLiteStatement? = nil @@ -157,7 +157,7 @@ public struct FTS5 { fatalError("FTS5 is not available") } defer { sqlite3_finalize(statement) } - type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in + type.utf8Start.withMemoryRebound(to: CChar.self, capacity: type.utf8CodeUnitCount) { typePointer in _ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil) } sqlite3_step(statement) diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index b0a10a61a..a294c35b3 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -131,10 +131,10 @@ extension Database { tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: CInt, - pText: UnsafePointer?, + pText: UnsafePointer?, nText: CInt, // swiftlint:disable:next line_length - tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, CInt, UnsafePointer?, CInt, CInt, CInt) -> CInt)?) + tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, CInt, UnsafePointer?, CInt, CInt, CInt) -> CInt)?) -> CInt { guard let tokenizerPointer else { diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index be19d6f59..02db06153 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -7,7 +7,7 @@ import Foundation public typealias FTS5TokenCallback = @convention(c) ( _ context: UnsafeMutableRawPointer?, _ flags: CInt, - _ pToken: UnsafePointer?, + _ pToken: UnsafePointer?, _ nToken: CInt, _ iStart: CInt, _ iEnd: CInt) @@ -77,7 +77,7 @@ public protocol FTS5Tokenizer: AnyObject { func tokenize( context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, - pText: UnsafePointer?, + pText: UnsafePointer?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt @@ -143,7 +143,7 @@ extension FTS5Tokenizer { guard let addr = buffer.baseAddress else { return [] } - let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) + let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: CChar.self) let nText = CInt(buffer.count) var context = TokenizeContext() @@ -206,8 +206,8 @@ extension Database { } else { func withArrayOfCStrings( _ input: [String], - _ output: inout ContiguousArray>, - _ accessor: (ContiguousArray>) -> Result) + _ output: inout ContiguousArray>, + _ accessor: (ContiguousArray>) -> Result) -> Result { if output.count == input.count { @@ -219,7 +219,7 @@ extension Database { } } } - var cStrings = ContiguousArray>() + var cStrings = ContiguousArray>() cStrings.reserveCapacity(arguments.count) code = withArrayOfCStrings(arguments, &cStrings) { (cStrings) in cStrings.withUnsafeBufferPointer { azArg in @@ -252,7 +252,7 @@ extension Database { func tokenize( context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, - pText: UnsafePointer?, + pText: UnsafePointer?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index 7be012bf2..8b9de904a 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -87,7 +87,7 @@ extension FTS5WrapperTokenizer { public func tokenize( context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, - pText: UnsafePointer?, + pText: UnsafePointer?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt @@ -138,7 +138,7 @@ extension FTS5WrapperTokenizer { return } let pToken = UnsafeMutableRawPointer(mutating: addr) - .assumingMemoryBound(to: Int8.self) + .assumingMemoryBound(to: CChar.self) let nToken = CInt(buffer.count) // Inject token bytes into SQLite diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index fe3d84b5f..9757c85b0 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -269,8 +269,8 @@ public struct DatabaseMigrator { writer.asyncBarrierWriteWithoutTransaction { dbResult in do { let db = try dbResult.get() - if let lastMigration = self._migrations.last { - try self.migrate(db, upTo: lastMigration.identifier) + if let lastMigration = _migrations.last { + try migrate(db, upTo: lastMigration.identifier) } completion(.success(db)) } catch { @@ -409,7 +409,7 @@ public struct DatabaseMigrator { if eraseDatabaseOnSchemaChange { var needsErase = false try db.inTransaction(.deferred) { - let appliedIdentifiers = try self.appliedIdentifiers(db) + let appliedIdentifiers = try appliedIdentifiers(db) let knownIdentifiers = Set(_migrations.map { $0.identifier }) if !appliedIdentifiers.isSubset(of: knownIdentifiers) { // Database contains an unknown migration diff --git a/GRDB/QueryInterface/SQL/DatabasePromise.swift b/GRDB/QueryInterface/SQL/DatabasePromise.swift index 23d7a8b7a..9d497b584 100644 --- a/GRDB/QueryInterface/SQL/DatabasePromise.swift +++ b/GRDB/QueryInterface/SQL/DatabasePromise.swift @@ -38,7 +38,7 @@ struct DatabasePromise { /// Returns a promise whose value is transformed by the given closure. func map(_ transform: @escaping (T) throws -> U) -> DatabasePromise { DatabasePromise { db in - try transform(self.resolve(db)) + try transform(resolve(db)) } } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 5c39d13e3..17551514b 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -566,8 +566,8 @@ private struct SQLQualifiedRelation { /// The full selection, including selection of joined relations var selectionPromise: DatabasePromise<[SQLSelection]> { DatabasePromise { db in - let selection = try self.sourceSelectionPromise.resolve(db) - return try self.joins.values.reduce(into: selection) { selection, join in + let selection = try sourceSelectionPromise.resolve(db) + return try joins.values.reduce(into: selection) { selection, join in let joinedSelection = try join.relation.selectionPromise.resolve(db) selection.append(contentsOf: joinedSelection) } diff --git a/README.md b/README.md index 85cbd4ad0..ddd865de7 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ CI Status

-**Latest release**: July 9, 2023 • [version 6.16.0](https://github.com/groue/GRDB.swift/tree/v6.16.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: August 26, 2023 • [version 6.17.0](https://github.com/groue/GRDB.swift/tree/v6.17.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ diff --git a/Scripts/swiftlint.yml b/Scripts/swiftlint.yml index c933e32ea..af49e16e2 100644 --- a/Scripts/swiftlint.yml +++ b/Scripts/swiftlint.yml @@ -57,11 +57,13 @@ opt_in_rules: - pattern_matching_keywords - prohibited_super_call - reduce_into + - redundant_self_in_closure - redundant_type_annotation - shorthand_optional_binding - sorted_first_last - sorted_imports - toggle_bool + - unhandled_throwing_task - vertical_parameter_alignment_on_call - yoda_condition diff --git a/Support/Info.plist b/Support/Info.plist index 3538d97b0..c9117a319 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.16.0 + 6.17.0 CFBundleSignature ???? CFBundleVersion diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 25eebc715..183fd89ed 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -52,7 +52,7 @@ private class UserDatabaseValueConvertible2 : DatabaseValueConvertible { #if SQLITE_ENABLE_FTS5 private class UserFTS5Tokenizer : FTS5Tokenizer { - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() } + func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() } } #endif @@ -62,7 +62,7 @@ private class UserFTS5Tokenizer : FTS5Tokenizer { private class UserFTS5CustomTokenizer : FTS5CustomTokenizer { static let name: String = "UserFTS5CustomTokenizer" required init(db: Database, arguments: [String]) throws { preconditionFailure() } - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() } + func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() } } #endif diff --git a/Tests/GRDBTests/DatabasePoolTests.swift b/Tests/GRDBTests/DatabasePoolTests.swift index cc6e24df1..7580b1a34 100644 --- a/Tests/GRDBTests/DatabasePoolTests.swift +++ b/Tests/GRDBTests/DatabasePoolTests.swift @@ -2,6 +2,38 @@ import XCTest import GRDB class DatabasePoolTests: GRDBTestCase { + func testJournalModeConfiguration() throws { + do { + // Factory default + let config = Configuration() + let dbPool = try makeDatabasePool(filename: "factory", configuration: config) + let journalMode = try dbPool.read { db in + try String.fetchOne(db, sql: "PRAGMA journal_mode") + } + XCTAssertEqual(journalMode, "wal") + } + do { + // Explicit default + var config = Configuration() + config.journalMode = .default + let dbPool = try makeDatabasePool(filename: "default", configuration: config) + let journalMode = try dbPool.read { db in + try String.fetchOne(db, sql: "PRAGMA journal_mode") + } + XCTAssertEqual(journalMode, "wal") + } + do { + // Explicit wal + var config = Configuration() + config.journalMode = .wal + let dbPool = try makeDatabasePool(filename: "wal", configuration: config) + let journalMode = try dbPool.read { db in + try String.fetchOne(db, sql: "PRAGMA journal_mode") + } + XCTAssertEqual(journalMode, "wal") + } + } + func testDatabasePoolCreatesWalShm() throws { let dbPool = try makeDatabasePool(filename: "test") try withExtendedLifetime(dbPool) { diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 2c3f26d07..4a1b5f333 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -3,6 +3,37 @@ import Dispatch import GRDB class DatabaseQueueTests: GRDBTestCase { + func testJournalModeConfiguration() throws { + do { + // Factory default + let config = Configuration() + let dbQueue = try makeDatabaseQueue(filename: "factory", configuration: config) + let journalMode = try dbQueue.read { db in + try String.fetchOne(db, sql: "PRAGMA journal_mode") + } + XCTAssertEqual(journalMode, "delete") + } + do { + // Explicit default + var config = Configuration() + config.journalMode = .default + let dbQueue = try makeDatabaseQueue(filename: "default", configuration: config) + let journalMode = try dbQueue.read { db in + try String.fetchOne(db, sql: "PRAGMA journal_mode") + } + XCTAssertEqual(journalMode, "delete") + } + do { + // Explicit wal + var config = Configuration() + config.journalMode = .wal + let dbQueue = try makeDatabaseQueue(filename: "wal", configuration: config) + let journalMode = try dbQueue.read { db in + try String.fetchOne(db, sql: "PRAGMA journal_mode") + } + XCTAssertEqual(journalMode, "wal") + } + } func testInvalidFileFormat() throws { do { diff --git a/Tests/GRDBTests/FTS5CustomTokenizerTests.swift b/Tests/GRDBTests/FTS5CustomTokenizerTests.swift index 0c665b2b8..f5d76765d 100644 --- a/Tests/GRDBTests/FTS5CustomTokenizerTests.swift +++ b/Tests/GRDBTests/FTS5CustomTokenizerTests.swift @@ -23,7 +23,7 @@ private final class StopWordsTokenizer : FTS5CustomTokenizer { // TODO: test that deinit is called } - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { // The way we implement stop words is by letting wrappedTokenizer do its // job but intercepting its tokens before they feed SQLite. @@ -76,7 +76,7 @@ private final class NFKCTokenizer : FTS5CustomTokenizer { // TODO: test that deinit is called } - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { // The way we implement NFKC conversion is by letting wrappedTokenizer // do its job, but intercepting its tokens before they feed SQLite. @@ -107,7 +107,7 @@ private final class NFKCTokenizer : FTS5CustomTokenizer { guard let addr = buffer.baseAddress else { return 0 // SQLITE_OK } - let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) + let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: CChar.self) let nToken = Int32(buffer.count) return customContext.tokenCallback(customContext.context, flags, pToken, nToken, iStart, iEnd) } @@ -135,7 +135,7 @@ private final class SynonymsTokenizer : FTS5CustomTokenizer { // TODO: test that deinit is called } - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { // Don't look for synonyms when tokenizing queries, as advised by // https://www.sqlite.org/fts5.html#synonym_support if tokenization.contains(.query) { @@ -176,7 +176,7 @@ private final class SynonymsTokenizer : FTS5CustomTokenizer { guard let addr = buffer.baseAddress else { return 0 // SQLITE_OK } - let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) + let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: CChar.self) let nToken = Int32(buffer.count) // Set FTS5_TOKEN_COLOCATED for all but first token let synonymFlags = (index == 0) ? flags : flags | 1 // 1: FTS5_TOKEN_COLOCATED