mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Merge branch 'development'
This commit is contained in:
commit
e40569844f
29 files changed
+234
-96
No files matched your search
@@ -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)
|
||||
|
||||
+1
-1
@@ -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.'
|
||||
|
||||
@@ -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: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
|
||||
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: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
|
||||
public var journalMode = JournalModeConfiguration.default
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// Defines the how `SQLITE_BUSY` errors are handled.
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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<Int8>? = nil
|
||||
var statementEnd: UnsafePointer<CChar>? = nil
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
|
||||
@@ -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 <https://github.com/groue/GRDB.swift/issues/102>.
|
||||
//
|
||||
// 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 <https://github.com/groue/GRDB.swift/issues/1383>.
|
||||
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<Int8>?)
|
||||
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?)
|
||||
{
|
||||
guard let trace else { return }
|
||||
|
||||
@@ -1896,7 +1931,7 @@ extension Database {
|
||||
public struct Statement: CustomStringConvertible {
|
||||
var sqliteStatement: SQLiteStatement
|
||||
var unexpandedSQL: UnsafePointer<CChar>?
|
||||
var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?
|
||||
var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?
|
||||
var publicStatementArguments: Bool // See Configuration.publicStatementArguments
|
||||
|
||||
/// The executed SQL, where bound parameters are not expanded.
|
||||
|
||||
@@ -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 <https://github.com/groue/GRDB.swift/issues/102>.
|
||||
//
|
||||
// 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 <https://github.com/groue/GRDB.swift/issues/1383>.
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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..<CInt(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
return (0..<CInt(columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
// The database region is reported by `sqlite3_set_authorizer`, and maybe
|
||||
@@ -90,8 +91,8 @@ public final class Statement {
|
||||
sqlite3_stmt_readonly(sqliteStatement) != 0
|
||||
}
|
||||
|
||||
/// A boolean value indicating if the statement deletes some rows.
|
||||
var isDeleteStatement: Bool {
|
||||
/// A boolean value indicating if the statement can delete some rows.
|
||||
var canDeleteRows: Bool {
|
||||
authorizerEventKinds.contains(where: \.isDelete)
|
||||
}
|
||||
|
||||
@@ -101,7 +102,7 @@ public final class Statement {
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
Dictionary(
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
|
||||
@@ -118,8 +119,8 @@ public final class Statement {
|
||||
/// - throws: DatabaseError in case of compilation error.
|
||||
required init?(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
statementStart: UnsafePointer<CChar>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<CChar>?>,
|
||||
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)"
|
||||
|
||||
@@ -57,10 +57,10 @@ final class StatementAuthorizer {
|
||||
|
||||
private func authorize(
|
||||
_ actionCode: CInt,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
_ cString1: UnsafePointer<CChar>?,
|
||||
_ cString2: UnsafePointer<CChar>?,
|
||||
_ cString3: UnsafePointer<CChar>?,
|
||||
_ cString4: UnsafePointer<CChar>?)
|
||||
-> CInt
|
||||
{
|
||||
// Uncomment when debugging
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import Foundation
|
||||
|
||||
@usableFromInline
|
||||
struct SQLiteDateParser {
|
||||
// swiftlint:disable:next unneeded_synthesized_initializer
|
||||
@usableFromInline
|
||||
init() { }
|
||||
|
||||
|
||||
@@ -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<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
|
||||
init(
|
||||
kind: Kind,
|
||||
rowID: Int64,
|
||||
databaseNameCString: UnsafePointer<CChar>?,
|
||||
tableNameCString: UnsafePointer<CChar>?)
|
||||
{
|
||||
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<Int8>?
|
||||
let tableNameCString: UnsafePointer<Int8>?
|
||||
let databaseNameCString: UnsafePointer<CChar>?
|
||||
let tableNameCString: UnsafePointer<CChar>?
|
||||
|
||||
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<Int8>?,
|
||||
tableNameCString: UnsafePointer<Int8>?)
|
||||
databaseNameCString: UnsafePointer<CChar>?,
|
||||
tableNameCString: UnsafePointer<CChar>?)
|
||||
{
|
||||
self.init(
|
||||
kind: kind,
|
||||
@@ -1324,8 +1329,8 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
let connection: SQLiteConnection
|
||||
let kind: DatabasePreUpdateEvent.Kind
|
||||
|
||||
let databaseNameCString: UnsafePointer<Int8>?
|
||||
let tableNameCString: UnsafePointer<Int8>?
|
||||
let databaseNameCString: UnsafePointer<CChar>?
|
||||
let tableNameCString: UnsafePointer<CChar>?
|
||||
|
||||
var databaseName: String { String(cString: databaseNameCString!) }
|
||||
var tableName: String { String(cString: tableNameCString!) }
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -83,7 +83,9 @@ do {
|
||||
- ``acceptsDoubleQuotedStringLiterals``
|
||||
- ``busyMode``
|
||||
- ``foreignKeysEnabled``
|
||||
- ``journalMode``
|
||||
- ``readonly``
|
||||
- ``JournalModeConfiguration``
|
||||
|
||||
### Configuring GRDB Connections
|
||||
|
||||
|
||||
+3
-3
@@ -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<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt,
|
||||
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<CChar>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<CChar>?>?) -> CInt,
|
||||
// swiftlint:disable:next line_length
|
||||
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
|
||||
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<CChar>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
|
||||
-> UnsafePointer<fts5_api>
|
||||
{
|
||||
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)
|
||||
|
||||
@@ -131,10 +131,10 @@ extension Database {
|
||||
tokenizerPointer: OpaquePointer?,
|
||||
context: UnsafeMutableRawPointer?,
|
||||
flags: CInt,
|
||||
pText: UnsafePointer<Int8>?,
|
||||
pText: UnsafePointer<CChar>?,
|
||||
nText: CInt,
|
||||
// swiftlint:disable:next line_length
|
||||
tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, CInt, UnsafePointer<Int8>?, CInt, CInt, CInt) -> CInt)?)
|
||||
tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, CInt, UnsafePointer<CChar>?, CInt, CInt, CInt) -> CInt)?)
|
||||
-> CInt
|
||||
{
|
||||
guard let tokenizerPointer else {
|
||||
|
||||
@@ -7,7 +7,7 @@ import Foundation
|
||||
public typealias FTS5TokenCallback = @convention(c) (
|
||||
_ context: UnsafeMutableRawPointer?,
|
||||
_ flags: CInt,
|
||||
_ pToken: UnsafePointer<Int8>?,
|
||||
_ pToken: UnsafePointer<CChar>?,
|
||||
_ nToken: CInt,
|
||||
_ iStart: CInt,
|
||||
_ iEnd: CInt)
|
||||
@@ -77,7 +77,7 @@ public protocol FTS5Tokenizer: AnyObject {
|
||||
func tokenize(
|
||||
context: UnsafeMutableRawPointer?,
|
||||
tokenization: FTS5Tokenization,
|
||||
pText: UnsafePointer<Int8>?,
|
||||
pText: UnsafePointer<CChar>?,
|
||||
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<Result>(
|
||||
_ input: [String],
|
||||
_ output: inout ContiguousArray<UnsafePointer<Int8>>,
|
||||
_ accessor: (ContiguousArray<UnsafePointer<Int8>>) -> Result)
|
||||
_ output: inout ContiguousArray<UnsafePointer<CChar>>,
|
||||
_ accessor: (ContiguousArray<UnsafePointer<CChar>>) -> Result)
|
||||
-> Result
|
||||
{
|
||||
if output.count == input.count {
|
||||
@@ -219,7 +219,7 @@ extension Database {
|
||||
}
|
||||
}
|
||||
}
|
||||
var cStrings = ContiguousArray<UnsafePointer<Int8>>()
|
||||
var cStrings = ContiguousArray<UnsafePointer<CChar>>()
|
||||
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<Int8>?,
|
||||
pText: UnsafePointer<CChar>?,
|
||||
nText: CInt,
|
||||
tokenCallback: @escaping FTS5TokenCallback)
|
||||
-> CInt
|
||||
|
||||
@@ -87,7 +87,7 @@ extension FTS5WrapperTokenizer {
|
||||
public func tokenize(
|
||||
context: UnsafeMutableRawPointer?,
|
||||
tokenization: FTS5Tokenization,
|
||||
pText: UnsafePointer<Int8>?,
|
||||
pText: UnsafePointer<CChar>?,
|
||||
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -38,7 +38,7 @@ struct DatabasePromise<T> {
|
||||
/// Returns a promise whose value is transformed by the given closure.
|
||||
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
|
||||
DatabasePromise<U> { db in
|
||||
try transform(self.resolve(db))
|
||||
try transform(resolve(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
|
||||
</p>
|
||||
|
||||
**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+
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.16.0</string>
|
||||
<string>6.17.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -52,7 +52,7 @@ private class UserDatabaseValueConvertible2 : DatabaseValueConvertible {
|
||||
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
private class UserFTS5Tokenizer : FTS5Tokenizer {
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() }
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<CChar>?, 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<Int8>?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() }
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<CChar>?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() }
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -23,7 +23,7 @@ private final class StopWordsTokenizer : FTS5CustomTokenizer {
|
||||
// TODO: test that deinit is called
|
||||
}
|
||||
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<CChar>?, 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<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<CChar>?, 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<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<CChar>?, 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
|
||||
|
||||
Reference in new issue
Block a user