mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52b7b7bd26 | ||
|
|
9a9d2e9993 | ||
|
|
1ce8e38bea | ||
|
|
67b34dc57c | ||
|
|
515bd78d28 | ||
|
|
f2aa6b386f | ||
|
|
71e09a38d4 | ||
|
|
d800a79d5d | ||
|
|
4065ff58e8 | ||
|
|
18eab53f74 | ||
|
|
6eba24d169 | ||
|
|
bd3ac9ef75 | ||
|
|
392137c357 | ||
|
|
b48a56ae03 | ||
|
|
bbd1eab402 | ||
|
|
53c9d12d29 | ||
|
|
9b09c5342e | ||
|
|
aed22fe0bc | ||
|
|
eec220b652 | ||
|
|
79a782038e | ||
|
|
618e72d153 | ||
|
|
824100990f | ||
|
|
c7205b172f | ||
|
|
49d14e6b66 | ||
|
|
54ed7ec611 | ||
|
|
68e17351ff | ||
|
|
494e697e94 | ||
|
|
87b236dfe0 | ||
|
|
ea6d8e0123 | ||
|
|
073209f1dc | ||
|
|
430530f5f1 | ||
|
|
a716915280 | ||
|
|
ef36727d9a | ||
|
|
78b2796f46 | ||
|
|
3535a42c53 | ||
|
|
5a4d9b5cb9 | ||
|
|
a64b09d121 |
No files matched your search
@@ -46,7 +46,7 @@ jobs:
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=iPhone 15 Pro"
|
||||
destination: "OS=18.1,name=iPhone 16 Pro"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
@@ -73,23 +73,6 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM test_install_SPM
|
||||
SPMSQLCipher:
|
||||
name: SPM
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: GRDBCIPHER="https://github.com/skiptools/swift-sqlcipher.git#1.2.1" swift test
|
||||
SQLCipher3:
|
||||
name: SQLCipher3
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
@@ -158,4 +141,4 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_universal_xcframework
|
||||
|
||||
|
||||
@@ -7,6 +7,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `7.4.x` Releases - [7.4.0](#740)
|
||||
- `7.3.x` Releases - [7.3.0](#730)
|
||||
- `7.2.x` Releases - [7.2.0](#720)
|
||||
- `7.1.x` Releases - [7.1.0](#710)
|
||||
- `7.0.x` Releases - [7.0.0](#700)
|
||||
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6) - [7.0.0-beta.7](#700-beta7)
|
||||
|
||||
@@ -132,6 +136,34 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 7.4.0
|
||||
|
||||
Released March 22, 2025
|
||||
|
||||
- **New**: Add the MIN and MAX multi-argument SQL functions to the query interface by [@groue](https://github.com/groue) in [#1745](https://github.com/groue/GRDB.swift/pull/1745)
|
||||
- **Fixed**: Transaction observers are not impacted by Task Cancellation by [@groue](https://github.com/groue) in [#1747](https://github.com/groue/GRDB.swift/pull/1747). This fixes unexpected `ValueObservation` failures in applications that perform asynchronous writes.
|
||||
|
||||
## 7.3.0
|
||||
|
||||
Released February 23, 2025
|
||||
|
||||
- **New**: Support for temporary virtual tables by [@groue](https://github.com/groue) in [#1731](https://github.com/groue/GRDB.swift/pull/1731)
|
||||
- Fixed a compiler error in Xcode 16.3 beta ([#1729](https://github.com/groue/GRDB.swift/pull/1729), [#1730](https://github.com/groue/GRDB.swift/pull/1730))
|
||||
|
||||
## 7.2.0
|
||||
|
||||
Released February 12, 2025
|
||||
|
||||
- **New**: Select ids with selectID() by [@groue](https://github.com/groue) in [#1719](https://github.com/groue/GRDB.swift/pull/1719)
|
||||
|
||||
## 7.1.0
|
||||
|
||||
Released February 5, 2025
|
||||
|
||||
- **New**: Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber` by [@groue](https://github.com/groue) in [#1713](https://github.com/groue/GRDB.swift/pull/1713)
|
||||
- **Fixed**: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled by [@groue](https://github.com/groue) in [#1716](https://github.com/groue/GRDB.swift/pull/1716)
|
||||
- **New**: Allow RxGRDB to compile without warning by [@groue](https://github.com/groue) in [#1717](https://github.com/groue/GRDB.swift/pull/1717)
|
||||
|
||||
## 7.0.0
|
||||
|
||||
Released January 26, 2025
|
||||
|
||||
@@ -91,7 +91,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
|
||||
|
||||
**FTS3 and FTS4 full-text tables store and index textual content.**
|
||||
|
||||
Create tables with the `create(virtualTable:using:)` method:
|
||||
Create tables with the `create(virtualTable:options:using:_:)` method:
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE document USING fts3(content)
|
||||
@@ -326,7 +326,7 @@ let documents = try Document.filter(Column("content").match(pattern)).fetchAll(d
|
||||
|
||||
To use FTS5, you'll need a [custom SQLite build] that activates the `SQLITE_ENABLE_FTS5` compilation option.
|
||||
|
||||
Create FTS5 tables with the `create(virtualTable:using:)` method:
|
||||
Create FTS5 tables with the `create(virtualTable:options:using:_:)` method:
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
|
||||
@@ -24,4 +24,4 @@ To release a new GRDB version:
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
`make test_performance_comparison | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
|
||||
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.0.0'
|
||||
s.version = '7.4.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
@@ -494,11 +494,9 @@ extension Database {
|
||||
|
||||
switch ResultCode(rawValue: resultCode) {
|
||||
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
|
||||
if suspensionMutex.load().isCancelled {
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
throw CancellationError()
|
||||
}
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
try suspensionMutex.load().checkCancellation()
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
@@ -341,10 +341,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// If true, the database access has been cancelled.
|
||||
var isCancelled: Bool
|
||||
|
||||
/// If true, the database throws an error when it is cancelled.
|
||||
var interruptsWhenCancelled: Bool
|
||||
|
||||
func checkCancellation() throws {
|
||||
if isCancelled, interruptsWhenCancelled {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
|
||||
let suspensionMutex = Mutex(Suspension(
|
||||
isSuspended: false,
|
||||
isCancelled: false,
|
||||
interruptsWhenCancelled: true))
|
||||
|
||||
// MARK: - Transaction Date
|
||||
|
||||
@@ -1222,7 +1234,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
|
||||
suspension.isCancelled = true
|
||||
return true
|
||||
return suspension.interruptsWhenCancelled
|
||||
}
|
||||
|
||||
if needsInterrupt {
|
||||
@@ -1237,6 +1249,24 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Within the given closure, Task cancellation does not interrupt
|
||||
/// database accesses.
|
||||
func ignoringCancellation<T>(_ value: () throws -> T) rethrows -> T {
|
||||
let previous = suspensionMutex.withLock {
|
||||
let previous = $0.interruptsWhenCancelled
|
||||
$0.interruptsWhenCancelled = false
|
||||
return previous
|
||||
}
|
||||
|
||||
defer {
|
||||
suspensionMutex.withLock {
|
||||
$0.interruptsWhenCancelled = previous
|
||||
}
|
||||
}
|
||||
|
||||
return try value()
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
private func journalMode() throws -> String {
|
||||
if let journalMode = journalModeCache {
|
||||
@@ -1288,6 +1318,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return
|
||||
}
|
||||
|
||||
// Suspension should not prevent adjusting the read-only mode.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1715>.
|
||||
if statement.isQueryOnlyPragma {
|
||||
return
|
||||
}
|
||||
|
||||
// How should we interrupt the statement?
|
||||
enum Interrupt {
|
||||
case abort // Rollback and throw SQLITE_ABORT
|
||||
@@ -1297,7 +1333,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in
|
||||
// Check for cancellation first, so that the only error that
|
||||
// a user sees when a Task is cancelled is CancellationError.
|
||||
if suspension.isCancelled {
|
||||
if suspension.isCancelled, suspension.interruptsWhenCancelled {
|
||||
return .cancel
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -83,6 +83,7 @@ extension DatabaseRegionObservation {
|
||||
/// - parameter onChange: The closure to execute when a transaction has
|
||||
/// modified the observed region.
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
@preconcurrency // For RxGRDB, see <https://github.com/RxSwiftCommunity/RxGRDB/issues/72#issuecomment-2631125658>
|
||||
public func start(
|
||||
in writer: any DatabaseWriter,
|
||||
onError: @escaping @Sendable (Error) -> Void,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
@@ -92,6 +92,9 @@ public final class Statement {
|
||||
/// The effects on the database (reported by `sqlite3_set_authorizer`).
|
||||
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
private(set) var isQueryOnlyPragma = false
|
||||
|
||||
/// A boolean value indicating if the prepared statement makes no direct
|
||||
/// changes to the content of the database file.
|
||||
///
|
||||
@@ -160,6 +163,7 @@ public final class Statement {
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.authorizerEventKinds = authorizer.databaseEventKinds
|
||||
self.isQueryOnlyPragma = authorizer.isQueryOnlyPragma
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
@@ -11,8 +11,6 @@ import SQLite3
|
||||
import string_h
|
||||
#elseif os(Linux)
|
||||
import Glibc
|
||||
#elseif canImport(Android)
|
||||
import Android
|
||||
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
@@ -43,6 +41,9 @@ final class StatementAuthorizer {
|
||||
/// savepoint statement.
|
||||
var transactionEffect: Statement.TransactionEffect?
|
||||
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
var isQueryOnlyPragma = false
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
init(_ database: Database) {
|
||||
@@ -69,6 +70,7 @@ final class StatementAuthorizer {
|
||||
databaseEventKinds = []
|
||||
invalidatesDatabaseSchemaCache = false
|
||||
transactionEffect = nil
|
||||
isQueryOnlyPragma = false
|
||||
isDropStatement = false
|
||||
}
|
||||
|
||||
@@ -194,6 +196,11 @@ final class StatementAuthorizer {
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_PRAGMA:
|
||||
if let cString1 {
|
||||
isQueryOnlyPragma = sqlite3_stricmp(cString1, "query_only") == 0
|
||||
}
|
||||
return SQLITE_OK
|
||||
default:
|
||||
return SQLITE_OK
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#if !os(Linux)
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#if !os(Linux) && !os(Windows) && !os(Android)
|
||||
#if !os(Linux) && !os(Windows)
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows) && !os(Android)
|
||||
#if !os(Linux) && !os(Windows)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows) && !os(Android)
|
||||
#if !os(Linux) && !os(Windows)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
@@ -549,8 +549,12 @@ class DatabaseObservationBroker {
|
||||
savepointStack.clear()
|
||||
|
||||
if !database.isReadOnly {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
// Observers must be able to access the database, even if the
|
||||
// task that has performed the commit is cancelled.
|
||||
database.ignoringCancellation {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,12 +613,18 @@ class DatabaseObservationBroker {
|
||||
|
||||
// Called from statementDidExecute or statementDidFail
|
||||
private func databaseDidRollback(notifyTransactionObservers: Bool) {
|
||||
#warning("TODO")
|
||||
savepointStack.clear()
|
||||
|
||||
if notifyTransactionObservers {
|
||||
assert(!database.isReadOnly, "Read-only transactions are not notified")
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
|
||||
// Observers must be able to access the database, even if the
|
||||
// task that has performed the commit is cancelled.
|
||||
database.ignoringCancellation {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
}
|
||||
}
|
||||
}
|
||||
databaseDidEndTransaction()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -252,8 +252,8 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
|
||||
|
||||
- ``Database/alter(table:body:)``
|
||||
- ``Database/create(table:options:body:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
- ``Database/create(virtualTable:options:using:)``
|
||||
- ``Database/create(virtualTable:options:using:_:)``
|
||||
- ``Database/drop(table:)``
|
||||
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
|
||||
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
|
||||
@@ -265,6 +265,7 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
|
||||
- ``TableDefinition``
|
||||
- ``TableOptions``
|
||||
- ``VirtualTableModule``
|
||||
- ``VirtualTableOptions``
|
||||
|
||||
### Database Views
|
||||
|
||||
@@ -288,3 +289,5 @@ Those are legacy interfaces that are preserved for backwards compatibility. Thei
|
||||
|
||||
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
|
||||
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
@@ -94,6 +94,26 @@ migrator.registerMigration("Create authors") { db in
|
||||
}
|
||||
```
|
||||
|
||||
#### How to Rename a Foreign Key
|
||||
|
||||
When a migration **renames a foreign key**, make sure the migration runs with `.immediate` foreign key checks, in order to avoid database integrity problems:
|
||||
|
||||
```swift
|
||||
// IMPORTANT: rename foreign keys with immediate foreign key checks.
|
||||
migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
|
||||
try db.rename(table: "team", to: "guild")
|
||||
|
||||
try db.alter(table: "player") { t in
|
||||
// Rename a foreign key
|
||||
t.rename(column: "teamId", to: "guildId")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note: migrations that run with `.immediate` foreign key checks can not be used to recreated database tables, as described below. When needed, define two migrations instead of one.
|
||||
|
||||
#### How to Recreate a Database Table
|
||||
|
||||
When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table.
|
||||
|
||||
For example:
|
||||
@@ -113,19 +133,39 @@ migrator.registerMigration("Add NOT NULL check on author.name") { db in
|
||||
|
||||
The detailed sequence of operations for recreating a database table from a migration is:
|
||||
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table X. This information will be needed in steps 6 and 7 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in steps 6 below. One way to do this is to run the following statement and examine the output in the console:
|
||||
|
||||
2. Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
|
||||
```swift
|
||||
try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'")
|
||||
```
|
||||
|
||||
3. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
|
||||
2. Construct a new table `new_X` that is in the desired revised format of table `X`. Make sure that the name `new_X` does not collide with any existing table name, of course.
|
||||
|
||||
4. Drop the old table X: `DROP TABLE X`.
|
||||
```swift
|
||||
try db.create(table: "new_X") { t in ... }
|
||||
```
|
||||
|
||||
5. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
|
||||
3. Transfer content from `X` into `new_X` using a statement like:
|
||||
|
||||
6. When relevant, use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.
|
||||
```swift
|
||||
try db.execute(sql: "INSERT INTO new_X SELECT ... FROM X")
|
||||
```
|
||||
|
||||
7. If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
4. Drop the old table `X`:
|
||||
|
||||
```swift
|
||||
try db.drop(table: "X")
|
||||
```
|
||||
|
||||
5. Change the name of `new_X` to `X` using:
|
||||
|
||||
```swift
|
||||
try db.rename(table: "new_X", to: "X")
|
||||
```
|
||||
|
||||
6. When relevant, reconstruct indexes, triggers, and views associated with table `X`.
|
||||
|
||||
7. If any views refer to table `X` in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
|
||||
> Important: When recreating a table, be sure to follow the above procedure exactly, in the given order, or you might corrupt triggers, views, and foreign key constraints.
|
||||
>
|
||||
|
||||
@@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request
|
||||
|
||||
```swift
|
||||
extension QueryInterfaceRequest<Author> {
|
||||
// Selects author ids
|
||||
func selectId() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey(as: Int64.self)
|
||||
// Selects authors' name
|
||||
func selectName() -> QueryInterfaceRequest<String> {
|
||||
select(Author.Columns.name)
|
||||
}
|
||||
}
|
||||
|
||||
// The ids of Japanese authors
|
||||
let ids: Set<Int64> = try Author.all()
|
||||
// The names of Japanese authors
|
||||
let names: Set<String> = try Author.all()
|
||||
.filter(countryCode: "JP")
|
||||
.selectId()
|
||||
.selectName()
|
||||
.fetchSet(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import Foundation
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
// MARK: - Dump
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
/// The virtual table module for the FTS3 full-text engine.
|
||||
///
|
||||
/// To create FTS3 tables, use the ``Database`` method
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
|
||||
/// ``Database/create(virtualTable:options:using:_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts3(content)
|
||||
@@ -63,7 +63,7 @@ public struct FTS3 {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
/// See ``Database/create(virtualTable:options:using:_:)``
|
||||
public init() { }
|
||||
|
||||
/// Returns an array of tokens found in the string argument.
|
||||
@@ -143,7 +143,7 @@ extension FTS3: VirtualTableModule {
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
|
||||
|
||||
@@ -106,13 +106,13 @@ public struct FTS3TokenizerDescriptor: Sendable {
|
||||
if !separators.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as separators, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
arguments.append("separators=" + separators.sorted().map { String($0) }.joined())
|
||||
}
|
||||
if !tokenCharacters.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined())
|
||||
}
|
||||
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
|
||||
|
||||
+13
-3
@@ -1,7 +1,7 @@
|
||||
/// The virtual table module for the FTS4 full-text engine.
|
||||
///
|
||||
/// To create FTS4 tables, use the ``Database`` method
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
|
||||
/// ``Database/create(virtualTable:options:using:_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts4(content)
|
||||
@@ -31,7 +31,7 @@ public struct FTS4 {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
/// See ``Database/create(virtualTable:options:using:_:)``
|
||||
public init() { }
|
||||
}
|
||||
|
||||
@@ -102,6 +102,16 @@ extension FTS4: VirtualTableModule {
|
||||
case .synchronized(let contentTable):
|
||||
// https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
|
||||
|
||||
if definition.configuration.temporary {
|
||||
// SQLite can't rebuild the index of temporary tables:
|
||||
//
|
||||
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
|
||||
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts4(content="t", b, c);
|
||||
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
|
||||
// Runtime error: SQL logic error
|
||||
fatalError("Temporary external content FTS4 tables are not supported.")
|
||||
}
|
||||
|
||||
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
|
||||
let ftsTable = tableName.quotedDatabaseIdentifier
|
||||
let content = contentTable.quotedDatabaseIdentifier
|
||||
@@ -149,7 +159,7 @@ extension FTS4: VirtualTableModule {
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
|
||||
|
||||
+18
-8
@@ -1,9 +1,9 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
@@ -13,7 +13,7 @@ import Foundation
|
||||
/// The virtual table module for the FTS5 full-text engine.
|
||||
///
|
||||
/// To create FTS5 tables, use the ``Database`` method
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
|
||||
/// ``Database/create(virtualTable:options:using:_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
@@ -85,7 +85,7 @@ public struct FTS5 {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
/// See ``Database/create(virtualTable:options:using:_:)``
|
||||
public init() { }
|
||||
|
||||
// Support for FTS5Pattern initializers. Don't make public. Users tokenize
|
||||
@@ -143,7 +143,7 @@ extension FTS5: VirtualTableModule {
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
/// See Database.create(virtualTable:options:using:_:)
|
||||
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition {
|
||||
FTS5TableDefinition(configuration: configuration)
|
||||
}
|
||||
@@ -219,7 +219,7 @@ extension FTS5: VirtualTableModule {
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
/// See Database.create(virtualTable:options:using:_:)
|
||||
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
|
||||
switch definition.contentMode {
|
||||
case .raw:
|
||||
@@ -227,6 +227,16 @@ extension FTS5: VirtualTableModule {
|
||||
case .synchronized(let contentTable):
|
||||
// https://sqlite.org/fts5.html#external_content_tables
|
||||
|
||||
if definition.configuration.temporary {
|
||||
// SQLite can't rebuild the index of temporary tables:
|
||||
//
|
||||
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
|
||||
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts5(content="t",content_rowid="a",b,c);
|
||||
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
|
||||
// Runtime error: SQL logic error
|
||||
fatalError("Temporary external content FTS5 tables are not supported.")
|
||||
}
|
||||
|
||||
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
|
||||
let ftsTable = tableName.quotedDatabaseIdentifier
|
||||
let content = contentTable.quotedDatabaseIdentifier
|
||||
@@ -274,7 +284,7 @@ extension FTS5: VirtualTableModule {
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -112,14 +112,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
|
||||
if !separators.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as separators, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
components.append("separators")
|
||||
components.append(separators.sorted().map { String($0) }.joined())
|
||||
}
|
||||
if !tokenCharacters.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
components.append("tokenchars")
|
||||
components.append(tokenCharacters.sorted().map { String($0) }.joined())
|
||||
}
|
||||
@@ -197,14 +197,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
|
||||
if !separators.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as separators, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
components.append("separators")
|
||||
components.append(separators.sorted().map { String($0) }.joined())
|
||||
}
|
||||
if !tokenCharacters.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
components.append("tokenchars")
|
||||
components.append(tokenCharacters.sorted().map { String($0) }.joined())
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
/// - ``select(_:as:)-3o8qw``
|
||||
/// - ``select(literal:as:)``
|
||||
/// - ``select(sql:arguments:as:)``
|
||||
/// - ``selectID()``
|
||||
/// - ``selectPrimaryKey(as:)``
|
||||
///
|
||||
/// ### Batch Delete
|
||||
@@ -237,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
select(sqlLiteral, as: type)
|
||||
}
|
||||
|
||||
/// Selects the primary key.
|
||||
/// Returns a request that selects the primary key.
|
||||
///
|
||||
/// All primary keys are supported:
|
||||
///
|
||||
@@ -281,6 +282,46 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
.asRequest(of: PrimaryKey.self)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the primary key.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT id FROM player WHERE ...
|
||||
/// let request = try Player.filter(...).selectID()
|
||||
/// ```
|
||||
///
|
||||
/// **Important**: if the record type has an `ID` type that is an
|
||||
/// optional, such as `Int64?`, it is recommended to prefer
|
||||
/// ``selectPrimaryKey(as:)`` instead:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Identifiable {
|
||||
/// var id: Int64?
|
||||
/// }
|
||||
///
|
||||
/// // NOT RECOMMENDED: Set<Int64?>
|
||||
/// let ids = try Player.filter(...)
|
||||
/// .selectID()
|
||||
/// .fetchSet(db)
|
||||
///
|
||||
/// // BETTER: Set<Int64>
|
||||
/// let ids = try Player.filter(...)
|
||||
/// .selectPrimaryKey(as: Int64.self)
|
||||
/// .fetchSet(db)
|
||||
/// ```
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
|
||||
where RowDecoder: Identifiable
|
||||
{
|
||||
selectWhenConnected { db in
|
||||
let primaryKey = try db.primaryKey(self.databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
|
||||
return [Column(primaryKey.columns[0])]
|
||||
}.asRequest(of: RowDecoder.ID.self)
|
||||
}
|
||||
|
||||
public func annotatedWhenConnected(
|
||||
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
|
||||
-> Self
|
||||
|
||||
@@ -2209,8 +2209,10 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``localizedLowercased``
|
||||
/// - ``localizedUppercased``
|
||||
/// - ``lowercased``
|
||||
/// - ``min(_:_:_:)``
|
||||
/// - ``min(_:)``
|
||||
/// - ``min(_:filter:)``
|
||||
/// - ``max(_:_:_:)``
|
||||
/// - ``max(_:)``
|
||||
/// - ``max(_:filter:)``
|
||||
/// - ``sum(_:)``
|
||||
|
||||
@@ -11,7 +11,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `AVG` SQL function.
|
||||
/// The `AVG` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -26,7 +26,7 @@ public func average(
|
||||
.aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `AVG` SQL function.
|
||||
/// The `AVG` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -44,7 +44,7 @@ public func average(
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `AVG` SQL function.
|
||||
/// The `AVG` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -147,8 +147,24 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("LENGTH", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `MAX` SQL multi-argument function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MAX(score, 1000)
|
||||
/// max(Column("score"), 1000)
|
||||
/// ```
|
||||
public func max(
|
||||
_ value1: any SQLSpecificExpressible,
|
||||
_ value2: any SQLExpressible,
|
||||
_ values: any SQLExpressible...
|
||||
) -> SQLExpression {
|
||||
.simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `MAX` SQL function.
|
||||
/// The `MAX` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -163,7 +179,7 @@ public func max(
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MAX` SQL function.
|
||||
/// The `MAX` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -179,7 +195,7 @@ public func max(
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MAX` SQL function.
|
||||
/// The `MAX` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -192,8 +208,24 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// The `MIN` SQL multi-argument function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MIN(score, 1000)
|
||||
/// min(Column("score"), 1000)
|
||||
/// ```
|
||||
public func min(
|
||||
_ value1: any SQLSpecificExpressible,
|
||||
_ value2: any SQLExpressible,
|
||||
_ values: any SQLExpressible...
|
||||
) -> SQLExpression {
|
||||
.simpleFunction("MIN", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `MIN` SQL function.
|
||||
/// The `MIN` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -208,7 +240,7 @@ public func min(
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MIN` SQL function.
|
||||
/// The `MIN` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -224,7 +256,7 @@ public func min(
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MIN` SQL function.
|
||||
/// The `MIN` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -238,7 +270,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `SUM` SQL function.
|
||||
/// The `SUM` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -262,7 +294,7 @@ public func sum(
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `SUM` SQL function.
|
||||
/// The `SUM` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -284,7 +316,7 @@ public func sum(
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `SUM` SQL function.
|
||||
/// The `SUM` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -302,7 +334,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `TOTAL` SQL function.
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -326,7 +358,7 @@ public func total(
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `TOTAL` SQL function.
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -348,7 +380,7 @@ public func total(
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `TOTAL` SQL function.
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
|
||||
@@ -94,6 +94,7 @@
|
||||
/// - ``select(literal:as:)``
|
||||
/// - ``select(sql:arguments:)``
|
||||
/// - ``select(sql:arguments:as:)``
|
||||
/// - ``selectID()``
|
||||
/// - ``selectPrimaryKey(as:)``
|
||||
/// - ``with(_:)``
|
||||
///
|
||||
@@ -424,6 +425,40 @@ extension Table {
|
||||
all().selectPrimaryKey(as: type)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the primary key.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let table = Table<Player>("player")
|
||||
///
|
||||
/// // SELECT id FROM player
|
||||
/// let request = try table.selectID()
|
||||
/// ```
|
||||
///
|
||||
/// **Important**: if the record type has an `ID` type that is an
|
||||
/// optional, such as `Int64?`, it is recommended to prefer
|
||||
/// ``selectPrimaryKey(as:)`` instead:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Identifiable {
|
||||
/// var id: Int64?
|
||||
/// }
|
||||
///
|
||||
/// let table = Table<Player>("player")
|
||||
///
|
||||
/// // NOT RECOMMENDED: Set<Int64?>
|
||||
/// let ids = try table.selectID().fetchSet(db)
|
||||
///
|
||||
/// // BETTER: Set<Int64>
|
||||
/// let ids = try table.selectPrimaryKey(as: Int64.self).fetchSet(db)
|
||||
/// ```
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
|
||||
where RowDecoder: Identifiable
|
||||
{
|
||||
all().selectID()
|
||||
}
|
||||
|
||||
/// Returns a request with the provided result columns appended to the
|
||||
/// table columns.
|
||||
///
|
||||
|
||||
@@ -125,6 +125,28 @@ public final class TableAlteration {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Take care, when you rename **foreign keys** in <doc:Migrations>,
|
||||
/// to run the migration with the ``DatabaseMigrator/ForeignKeyChecks/immediate``
|
||||
/// foreign key checks, in order to avoid integrity failures:
|
||||
///
|
||||
/// ```swift
|
||||
/// // RECOMMENDED: rename foreign keys with immediate foreign key checks.
|
||||
/// migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
|
||||
/// try db.rename(table: "team", to: "guild")
|
||||
/// try db.alter(table: "player") { t in
|
||||
/// t.rename(column: "teamId", to: "guildId")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // NOT RECOMMENDED: rename foreign keys with disabled foreign keys.
|
||||
/// migrator.registerMigration("Guilds") { db in
|
||||
/// try db.rename(table: "team", to: "guild")
|
||||
/// try db.alter(table: "player") { t in
|
||||
/// t.rename(column: "teamId", to: "guildId")
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
|
||||
///
|
||||
/// - parameter name: the old name of the column.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/// The protocol for SQLite virtual table modules.
|
||||
///
|
||||
/// The protocol can define a DSL for the
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` `Database` method:
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` `Database` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// let module = ...
|
||||
@@ -20,7 +20,7 @@
|
||||
/// - ``VirtualTableConfiguration``
|
||||
public protocol VirtualTableModule {
|
||||
/// The type of the argument in the
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` closure.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -35,7 +35,7 @@ public protocol VirtualTableModule {
|
||||
var moduleName: String { get }
|
||||
|
||||
/// Returns a table definition that is passed as the argument in the
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` closure.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -54,10 +54,29 @@ public protocol VirtualTableModule {
|
||||
func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
|
||||
}
|
||||
|
||||
// TODO: Question the existence of this API. VirtualTableConfiguration was
|
||||
// never able to be used by user-defined VirtualTableModule types, because
|
||||
// `ifNotExists` has never been public.
|
||||
public struct VirtualTableConfiguration {
|
||||
/// If true, existing objects must not be replaced, or generate any error
|
||||
/// (even if they do not match the objects that would be created otherwise.)
|
||||
var ifNotExists: Bool
|
||||
|
||||
/// If true, new objects must be created in the temp schema.
|
||||
var temporary: Bool
|
||||
}
|
||||
|
||||
/// Virtual table creation options.
|
||||
public struct VirtualTableOptions: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
/// Only creates the table if it does not already exist.
|
||||
public static let ifNotExists = VirtualTableOptions(rawValue: 1 << 0)
|
||||
|
||||
/// Creates a temporary table.
|
||||
public static let temporary = VirtualTableOptions(rawValue: 1 << 1)
|
||||
}
|
||||
|
||||
extension Database {
|
||||
@@ -77,18 +96,24 @@ extension Database {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - options: Table creation options.
|
||||
/// - module: The name of an SQLite virtual table module.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
|
||||
public func create(
|
||||
virtualTable name: String,
|
||||
options: VirtualTableOptions = [],
|
||||
using module: String
|
||||
) throws {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE VIRTUAL TABLE")
|
||||
if ifNotExists {
|
||||
if options.contains(.ifNotExists) {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
if options.contains(.temporary) {
|
||||
chunks.append("temp.\(name.quotedDatabaseIdentifier)")
|
||||
} else {
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
}
|
||||
chunks.append("USING")
|
||||
chunks.append(module)
|
||||
let sql = chunks.joined(separator: " ")
|
||||
@@ -114,21 +139,21 @@ extension Database {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - tableName: The table name.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - options: Table creation options.
|
||||
/// - module: a virtual module.
|
||||
/// - body: An optional closure that defines the virtual table.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func create<Module: VirtualTableModule>(
|
||||
virtualTable tableName: String,
|
||||
ifNotExists: Bool = false,
|
||||
options: VirtualTableOptions = [],
|
||||
using module: Module,
|
||||
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
// Define virtual table
|
||||
let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists)
|
||||
let configuration = VirtualTableConfiguration(
|
||||
ifNotExists: options.contains(.ifNotExists),
|
||||
temporary: options.contains(.temporary))
|
||||
let definition = module.makeTableDefinition(configuration: configuration)
|
||||
if let body {
|
||||
try body(definition)
|
||||
@@ -137,10 +162,14 @@ extension Database {
|
||||
// Create virtual table
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE VIRTUAL TABLE")
|
||||
if ifNotExists {
|
||||
if options.contains(.ifNotExists) {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(tableName.quotedDatabaseIdentifier)
|
||||
if options.contains(.temporary) {
|
||||
chunks.append("temp.\(tableName.quotedDatabaseIdentifier)")
|
||||
} else {
|
||||
chunks.append(tableName.quotedDatabaseIdentifier)
|
||||
}
|
||||
chunks.append("USING")
|
||||
let arguments = try module.moduleArguments(for: definition, in: self)
|
||||
if arguments.isEmpty {
|
||||
@@ -156,4 +185,78 @@ extension Database {
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a virtual database table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE vocabulary USING spellfix1
|
||||
/// try db.create(virtualTable: "vocabulary", using: "spellfix1")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
|
||||
///
|
||||
/// - warning: This is a legacy interface that is preserved for backwards
|
||||
/// compatibility. Use of this interface is not recommended: prefer
|
||||
/// ``create(virtualTable:options:using:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - module: The name of an SQLite virtual table module.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@_disfavoredOverload
|
||||
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
|
||||
try create(
|
||||
virtualTable: name,
|
||||
options: ifNotExists ? .ifNotExists : [],
|
||||
using: module)
|
||||
}
|
||||
|
||||
/// Creates a virtual database table.
|
||||
///
|
||||
/// The type of the argument of the `body` function depends on the type of
|
||||
/// the `module` argument: refer to this module's documentation.
|
||||
///
|
||||
/// You can use this method to create full-text virtual tables:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.column("title")
|
||||
/// t.column("author")
|
||||
/// t.column("body")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
|
||||
///
|
||||
/// - warning: This is a legacy interface that is preserved for backwards
|
||||
/// compatibility. Use of this interface is not recommended: prefer
|
||||
/// ``create(virtualTable:options:using:_:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - tableName: The table name.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - module: a virtual module.
|
||||
/// - body: An optional closure that defines the virtual table.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@_disfavoredOverload
|
||||
public func create<Module: VirtualTableModule>(
|
||||
virtualTable tableName: String,
|
||||
ifNotExists: Bool = false,
|
||||
using module: Module,
|
||||
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
try create(
|
||||
virtualTable: tableName,
|
||||
options: ifNotExists ? .ifNotExists : [],
|
||||
using: module,
|
||||
body)
|
||||
}
|
||||
}
|
||||
@@ -251,6 +251,36 @@ extension TableRecord {
|
||||
all().selectPrimaryKey(as: type)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the primary key.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT id FROM player
|
||||
/// let request = try Player.selectID()
|
||||
/// ```
|
||||
///
|
||||
/// **Important**: if the record type has an `ID` type that is an
|
||||
/// optional, such as `Int64?`, it is recommended to prefer
|
||||
/// ``selectPrimaryKey(as:)`` instead:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Identifiable {
|
||||
/// var id: Int64?
|
||||
/// }
|
||||
///
|
||||
/// // NOT RECOMMENDED: Set<Int64?>
|
||||
/// let ids = try Player.selectID().fetchSet(db)
|
||||
///
|
||||
/// // BETTER: Set<Int64>
|
||||
/// let ids = try Player.selectPrimaryKey(as: Int64.self).fetchSet(db)
|
||||
/// ```
|
||||
public static func selectID() -> QueryInterfaceRequest<Self.ID>
|
||||
where Self: Identifiable
|
||||
{
|
||||
all().selectID()
|
||||
}
|
||||
|
||||
/// Returns a request with the provided result columns appended to the
|
||||
/// record selection.
|
||||
///
|
||||
|
||||
@@ -524,7 +524,12 @@ public enum DatabaseDataEncodingStrategy: Sendable {
|
||||
/// var creationDate: Date
|
||||
/// }
|
||||
/// ```
|
||||
public enum DatabaseDateEncodingStrategy: Sendable {
|
||||
public enum DatabaseDateEncodingStrategy: @unchecked Sendable {
|
||||
// @unchecked Sendable because of `DateFormatter`, which lost its
|
||||
// `Sendable` conformance with Xcode 16.3 beta. See
|
||||
// <https://github.com/swiftlang/swift/issues/78635>.
|
||||
// TODO: remove @unchecked when the compiler issue is fixed.
|
||||
|
||||
/// The strategy that uses formatting from the Date structure.
|
||||
///
|
||||
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -929,7 +929,12 @@ public enum DatabaseDataDecodingStrategy: Sendable {
|
||||
/// var name: String
|
||||
/// var registrationDate: Date // decoded from epoch timestamp
|
||||
/// }
|
||||
public enum DatabaseDateDecodingStrategy: Sendable {
|
||||
public enum DatabaseDateDecodingStrategy: @unchecked Sendable {
|
||||
// @unchecked Sendable because of `DateFormatter`, which lost its
|
||||
// `Sendable` conformance with Xcode 16.3 beta. See
|
||||
// <https://github.com/swiftlang/swift/issues/78635>.
|
||||
// TODO: remove @unchecked when the compiler issue is fixed.
|
||||
|
||||
/// The strategy that uses formatting from the Date structure.
|
||||
///
|
||||
/// It decodes numeric values as a number of seconds since Epoch
|
||||
|
||||
@@ -98,6 +98,7 @@ import Foundation
|
||||
/// - ``select(literal:as:)``
|
||||
/// - ``select(sql:arguments:)``
|
||||
/// - ``select(sql:arguments:as:)``
|
||||
/// - ``selectID()``
|
||||
/// - ``selectPrimaryKey(as:)``
|
||||
/// - ``with(_:)``
|
||||
///
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#
|
||||
# make test - Run all tests but performance tests
|
||||
# make test_performance - Run performance tests
|
||||
# make test_performance_comparison - Run performance comparison tests
|
||||
# make doc - Generate DocC documentation
|
||||
# make clean - Remove build artifacts
|
||||
# make distclean - Restore repository to a pristine state
|
||||
@@ -387,9 +386,6 @@ test_GRDBDemo:
|
||||
$(XCPRETTY)
|
||||
|
||||
test_performance:
|
||||
GRDB_PERFORMANCE_TESTS=1 $(SWIFT) test --configuration release --filter GRDBPerformanceTests
|
||||
|
||||
test_performance_comparison:
|
||||
$(XCODEBUILD) \
|
||||
-project Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj \
|
||||
-scheme GRDBOSXPerformanceComparisonTests \
|
||||
|
||||
+1
-42
@@ -27,24 +27,6 @@ if ProcessInfo.processInfo.environment["SPI_BUILDER"] == "1" {
|
||||
dependencies.append(.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"))
|
||||
}
|
||||
|
||||
var targetDependencies: [Target.Dependency] = ["GRDBSQLite"]
|
||||
|
||||
|
||||
var GRDBCIPHER = ProcessInfo.processInfo.environment["GRDBCIPHER"]
|
||||
// e.g.:
|
||||
//GRDBCIPHER="https://github.com/skiptools/swift-sqlcipher.git#1.2.1"
|
||||
if let SQLCipherRepo = GRDBCIPHER?.split(separator: "#").first,
|
||||
let SQLCipherVersion = GRDBCIPHER?.split(separator: "#").last,
|
||||
let SQLCipherRepoURL = URL(string: SQLCipherRepo.description) {
|
||||
swiftSettings.append(.define("GRDBCIPHER"))
|
||||
targetDependencies = [.product(name: "SQLCipher", package: SQLCipherRepoURL.deletingPathExtension().lastPathComponent)]
|
||||
if let version = Version(SQLCipherVersion.description) { // numeric version
|
||||
dependencies.append(.package(url: SQLCipherRepoURL.absoluteString, from: version))
|
||||
} else { // branch
|
||||
dependencies.append(.package(url: SQLCipherRepoURL.absoluteString, branch: SQLCipherVersion.description))
|
||||
}
|
||||
}
|
||||
|
||||
let package = Package(
|
||||
name: "GRDB",
|
||||
defaultLocalization: "en", // for tests
|
||||
@@ -66,7 +48,7 @@ let package = Package(
|
||||
providers: [.apt(["libsqlite3-dev"])]),
|
||||
.target(
|
||||
name: "GRDB",
|
||||
dependencies: targetDependencies,
|
||||
dependencies: ["GRDBSQLite"],
|
||||
path: "GRDB",
|
||||
resources: [.copy("PrivacyInfo.xcprivacy")],
|
||||
cSettings: cSettings,
|
||||
@@ -103,26 +85,3 @@ let package = Package(
|
||||
],
|
||||
swiftLanguageModes: [.v6]
|
||||
)
|
||||
|
||||
// The GRDB_PERFORMANCE_TESTS environment variable enables
|
||||
// the performance tests to be included in the package, which can be run with:
|
||||
// GRDB_PERFORMANCE_TESTS=1 swift test --filter GRDBPerformanceTests
|
||||
if ProcessInfo.processInfo.environment["GRDB_PERFORMANCE_TESTS"] == "1" {
|
||||
package.targets.append(
|
||||
Target.testTarget(
|
||||
name: "GRDBPerformanceTests",
|
||||
dependencies: ["GRDB"],
|
||||
path: "Tests/Performance/GRDBPerformance",
|
||||
exclude: [
|
||||
"PerformanceModel.xcdatamodeld",
|
||||
"Info.plist",
|
||||
],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings + [
|
||||
// Tests still use the Swift 5 language mode.
|
||||
.swiftLanguageMode(.v5),
|
||||
.enableUpcomingFeature("InferSendableFromCaptures"),
|
||||
.enableUpcomingFeature("GlobalActorIsolatedTypesUsability"),
|
||||
])
|
||||
)
|
||||
}
|
||||
@@ -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**: January 26, 2025 • [version 7.0.0](https://github.com/groue/GRDB.swift/tree/v7.0.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
|
||||
**Latest release**: March 22, 2025 • [version 7.4.0](https://github.com/groue/GRDB.swift/tree/v7.4.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ • SQLite 3.20.0+ • Swift 6+ / Xcode 16+
|
||||
|
||||
@@ -3341,6 +3341,16 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.select(nameColumn, as: String.self)
|
||||
```
|
||||
|
||||
- [`selectID()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/selectID()) is available on [Identifiable Records]. It supports all tables that have a single-column primary key:
|
||||
|
||||
```swift
|
||||
// SELECT id FROM player
|
||||
Player.selectID()
|
||||
|
||||
// SELECT id FROM player WHERE name IS NOT NULL
|
||||
Player.filter(nameColumn != nil).selectID()
|
||||
```
|
||||
|
||||
- [`annotated(with: expression...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/selectionrequest/annotated(with:)-6ehs4) extends the selection.
|
||||
|
||||
```swift
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>7.0.0</string>
|
||||
<string>7.4.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#if canImport(CoreGraphics)
|
||||
import XCTest
|
||||
import CoreGraphics
|
||||
import GRDB
|
||||
@@ -22,4 +21,3 @@ class CGFloatTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
#if !os(Android)
|
||||
class DatabaseMigratorTests : GRDBTestCase {
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
@@ -1111,4 +1110,3 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
} catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -3,7 +3,6 @@ import Dispatch
|
||||
import Foundation
|
||||
@testable import GRDB
|
||||
|
||||
#if canImport(Darwin) // needs NSFileCoordinator
|
||||
class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
|
||||
func testDatabasePoolFundamental1() throws {
|
||||
@@ -1349,4 +1348,3 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -2,7 +2,6 @@ import XCTest
|
||||
import Dispatch
|
||||
import GRDB
|
||||
|
||||
#if canImport(Darwin) // needed for __dispatch_get_global_queue
|
||||
class DatabaseQueueTests: GRDBTestCase {
|
||||
func testJournalModeConfiguration() throws {
|
||||
do {
|
||||
@@ -474,4 +473,3 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
dbQueue.releaseMemory()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -2,7 +2,6 @@ import XCTest
|
||||
import GRDB
|
||||
|
||||
class DatabaseRegionObservationTests: GRDBTestCase {
|
||||
#if canImport(Combine)
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
func testAnyDatabaseWriter(writer: any DatabaseWriter) throws {
|
||||
@@ -11,8 +10,7 @@ class DatabaseRegionObservationTests: GRDBTestCase {
|
||||
_ = observation.start(in: writer, onError: { _ in }, onChange: { _ in })
|
||||
_ = observation.publisher(in: writer)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
func testDatabaseRegionObservation_FullDatabase() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import XCTest
|
||||
@testable import GRDB
|
||||
|
||||
#if !os(Android)
|
||||
class DatabaseSnapshotTests: GRDBTestCase {
|
||||
/// A helper type
|
||||
private struct Counter {
|
||||
@@ -433,4 +432,3 @@ class DatabaseSnapshotTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -415,6 +415,57 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
|
||||
// MARK: - Task Cancellation
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1715>.
|
||||
func test_write_is_possible_after_read_cancelled_after_database_access() async throws {
|
||||
// When a read access is cancelled, DatabaseQueue needs to execute
|
||||
// `PRAGMA query_only=0` in order to restore the read/write access.
|
||||
//
|
||||
// Here we test that this pragma can run from a cancelled read.
|
||||
//
|
||||
// Small difficulty: some SQLite versions (seen with 3.43.2) execute
|
||||
// the `query_only` pragma at compile time, not only at execution
|
||||
// time (yeah, that's an SQLite bug). The problem of this bug is
|
||||
// that even if the `PRAGMA query_only=0` is not executed due to
|
||||
// Task cancellation, its side effect is still executed when it is
|
||||
// compiled, unintentionally. A cancelled `PRAGMA query_only=0`
|
||||
// still works!
|
||||
//
|
||||
// To avoid this SQLite bug from messing with our test, we perform
|
||||
// two reads: one that compiles and cache `PRAGMA query_only`
|
||||
// statements, and a second read that we cancel. This time the
|
||||
// `PRAGMA query_only=0` triggers its side effect if and only if it
|
||||
// is actually executed (the behavior we are testing).
|
||||
func test(_ dbWriter: some DatabaseWriter) async throws {
|
||||
let semaphore = AsyncSemaphore(value: 0)
|
||||
let cancelledTaskMutex = Mutex<Task<Void, any Error>?>(nil)
|
||||
let task = Task {
|
||||
await semaphore.wait()
|
||||
|
||||
// First read, not cancelled, so that all `query_only`
|
||||
// pragma statements are compiled (see above).
|
||||
try await dbWriter.read { db in }
|
||||
|
||||
// Second read, cancelled.
|
||||
try await dbWriter.read { db in
|
||||
try XCTUnwrap(cancelledTaskMutex.load()).cancel()
|
||||
}
|
||||
}
|
||||
cancelledTaskMutex.store(task)
|
||||
semaphore.signal()
|
||||
// Wait until reads are completed
|
||||
try? await task.value
|
||||
|
||||
// Write access is restored after read cancellation (no error is thrown)
|
||||
try await dbWriter.write { db in
|
||||
try db.execute(sql: "CREATE TABLE test(a)")
|
||||
}
|
||||
}
|
||||
|
||||
try await test(makeDatabaseQueue())
|
||||
try await test(makeDatabasePool())
|
||||
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
|
||||
}
|
||||
|
||||
func test_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws {
|
||||
func test(_ dbWriter: some DatabaseWriter) async throws {
|
||||
let semaphore = AsyncSemaphore(value: 0)
|
||||
|
||||
@@ -13,7 +13,29 @@ class FTS3TableBuilderTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testOptions() throws {
|
||||
func test_option_ifNotExists() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS3())
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts3")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func test_option_temporary() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .temporary, using: FTS3())
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts3")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testLegacyOptions() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS3())
|
||||
|
||||
@@ -13,7 +13,29 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testOptions() throws {
|
||||
func test_option_ifNotExists() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS4())
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts4")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func test_option_temporary() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .temporary, using: FTS4())
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts4")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testLegacyOptions() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS4())
|
||||
@@ -193,8 +215,8 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testFTS4SynchronizationIfNotExists() throws {
|
||||
|
||||
func testFTS4Synchronization_with_ifNotExists_option() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.create(table: "documents") { t in
|
||||
@@ -202,7 +224,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
t.column("content", .text)
|
||||
}
|
||||
assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)")
|
||||
try db.create(virtualTable: "ft_documents", ifNotExists: true, using: FTS4()) { t in
|
||||
try db.create(virtualTable: "ft_documents", options: .ifNotExists, using: FTS4()) { t in
|
||||
t.synchronize(withTable: "documents")
|
||||
t.column("content")
|
||||
}
|
||||
@@ -210,7 +232,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
assertDidExecute(sql: "CREATE TRIGGER IF NOT EXISTS \"__ft_documents_bu\" BEFORE UPDATE ON \"documents\" BEGIN\n DELETE FROM \"ft_documents\" WHERE docid=old.\"id\";\nEND")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testFTS4SynchronizationCleanup() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
import XCTest
|
||||
import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
class FTS5TableBuilderTests: GRDBTestCase {
|
||||
func testWithoutBody() throws {
|
||||
@@ -19,7 +16,33 @@ class FTS5TableBuilderTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testOptions() throws {
|
||||
func test_option_ifNotExists() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS5()) { t in
|
||||
t.column("content")
|
||||
}
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts5(content)")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func test_option_temporary() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .temporary, using: FTS5()) { t in
|
||||
t.column("content")
|
||||
}
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts5(content)")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testLegacyOptions() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS5()) { t in
|
||||
@@ -254,8 +277,8 @@ class FTS5TableBuilderTests: GRDBTestCase {
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testFTS5SynchronizationIfNotExists() throws {
|
||||
|
||||
func testFTS5Synchronization_with_ifNotExists_option() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.create(table: "documents") { t in
|
||||
@@ -263,7 +286,7 @@ class FTS5TableBuilderTests: GRDBTestCase {
|
||||
t.column("content", .text)
|
||||
}
|
||||
assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)")
|
||||
try db.create(virtualTable: "ft_documents", ifNotExists: true, using: FTS5()) { t in
|
||||
try db.create(virtualTable: "ft_documents", options: .ifNotExists, using: FTS5()) { t in
|
||||
t.synchronize(withTable: "documents")
|
||||
t.column("content")
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Inspired by https://github.com/groue/CombineExpectations
|
||||
import XCTest
|
||||
|
||||
#if canImport(Darwin) // needed for XCTIssue
|
||||
/// A XCTestCase subclass that can test its own failures.
|
||||
class FailureTestCase: XCTestCase {
|
||||
private struct Failure: Hashable {
|
||||
@@ -208,4 +207,3 @@ class FailureTestCaseTests: FailureTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,7 +1,6 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
#if canImport(Darwin) // needed for NSDecimalNumber
|
||||
class FoundationNSDecimalNumberTests: GRDBTestCase {
|
||||
|
||||
func testNSDecimalNumberPreservesIntegerValues() {
|
||||
@@ -158,4 +157,3 @@ class FoundationNSDecimalNumberTests: GRDBTestCase {
|
||||
try test("18446744073709551615", isDecodedAs: NSDecimalNumber(string: "18446744073709551615"))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,7 +1,6 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
#if canImport(Darwin) // needed for NSDecimalNumber
|
||||
class FoundationNSNumberTests: GRDBTestCase {
|
||||
|
||||
func testNSNumberDatabaseValueToSwiftType() {
|
||||
@@ -193,4 +192,3 @@ class FoundationNSNumberTests: GRDBTestCase {
|
||||
try test("18446744073709551615", isDecodedAs: NSDecimalNumber(value: UInt64(18446744073709551615)))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,7 +1,6 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
#if canImport(Darwin) // needed for NSURL
|
||||
class FoundationNSURLTests: GRDBTestCase {
|
||||
|
||||
func testNSURLDatabaseRoundTrip() throws {
|
||||
@@ -47,4 +46,3 @@ class FoundationNSURLTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
@@ -1,7 +1,6 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
#if canImport(Darwin) // needed for NSUUID
|
||||
class FoundationNSUUIDTests: GRDBTestCase {
|
||||
private func assert(_ value: (any DatabaseValueConvertible)?, isDecodedAs expectedUUID: NSUUID?) throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
@@ -51,4 +50,3 @@ class FoundationNSUUIDTests: GRDBTestCase {
|
||||
try assert("abcdefghijklmnopq".data(using: .utf8)!, isDecodedAs: nil)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -28,9 +28,7 @@ class FoundationUUIDTests: GRDBTestCase {
|
||||
try assert(string.lowercased(), isDecodedAs: uuid)
|
||||
try assert(string.uppercased(), isDecodedAs: uuid)
|
||||
try assert(uuid, isDecodedAs: uuid)
|
||||
#if canImport(Darwin) // needed for NSUUID
|
||||
try assert(uuid as NSUUID, isDecodedAs: uuid)
|
||||
#endif
|
||||
try assert(data, isDecodedAs: uuid)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
@@ -269,5 +269,7 @@ struct AnyValueReducerFetcher<Fetched>: _ValueReducerFetcher {
|
||||
}
|
||||
}
|
||||
|
||||
// Assume this is correct :-/
|
||||
#if compiler(<6.1)
|
||||
// XCTestExpectation is Sendable starting Xcode 16.3 beta.
|
||||
extension XCTestExpectation: @unchecked Sendable { }
|
||||
#endif
|
||||
@@ -1,8 +1,5 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
final class JSONColumnTests: GRDBTestCase {
|
||||
func test_JSONColumn_derived_from_CodingKey() throws {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
final class JSONExpressionsTests: GRDBTestCase {
|
||||
/// The SQL function used to build JSON expressions
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
private struct MutablePersistableRecordPerson : MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
private struct PersistableRecordPerson : PersistableRecord {
|
||||
var name: String?
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import XCTest
|
||||
@testable import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
private struct Col {
|
||||
static let id = Column("id")
|
||||
@@ -1562,7 +1559,18 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT LENGTH(\"name\") FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testMinExpression() throws {
|
||||
func testMultiArgumentMinExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(min(Col.age, 1000))),
|
||||
"SELECT MIN(\"age\", 1000) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(min(Col.age, 1000, Col.id))),
|
||||
"SELECT MIN(\"age\", 1000, \"id\") FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testAggregateMinExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
@@ -1573,7 +1581,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT MIN(\"age\" / 2) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testMinExpression_filter() throws {
|
||||
func testAggregateMinExpression_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard Database.sqliteLibVersionNumber >= 3030000 else {
|
||||
@@ -1595,7 +1603,18 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT MIN(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testMaxExpression() throws {
|
||||
func testMultiArgumentMaxExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(max(Col.age, 1000))),
|
||||
"SELECT MAX(\"age\", 1000) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(max(Col.age, 1000, Col.id))),
|
||||
"SELECT MAX(\"age\", 1000, \"id\") FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testAggregateMaxExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
@@ -1606,7 +1625,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT MAX(\"age\" / 2) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testMaxExpression_filter() throws {
|
||||
func testAggregateMaxExpression_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard Database.sqliteLibVersionNumber >= 3030000 else {
|
||||
|
||||
@@ -800,6 +800,16 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_static_selectID() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID")
|
||||
try record.insert(db)
|
||||
let ids: [String] = try MinimalSingle.selectID().fetchAll(db)
|
||||
XCTAssertEqual(ids, ["theUUID"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_request_selectPrimaryKey() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
@@ -811,4 +821,14 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows, [["id": "theUUID"]])
|
||||
}
|
||||
}
|
||||
|
||||
func test_request_selectID() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID")
|
||||
try record.insert(db)
|
||||
let ids: [String] = try MinimalSingle.all().selectID().fetchAll(db)
|
||||
XCTAssertEqual(ids, ["theUUID"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -844,6 +844,16 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_static_selectID() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalRowID()
|
||||
try record.insert(db)
|
||||
let ids: [Int64?] = try MinimalRowID.selectID().fetchAll(db)
|
||||
XCTAssertEqual(ids, [1])
|
||||
}
|
||||
}
|
||||
|
||||
func test_request_selectPrimaryKey() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
@@ -855,4 +865,14 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
|
||||
XCTAssertEqual(rows, [["id": 1]])
|
||||
}
|
||||
}
|
||||
|
||||
func test_request_selectID() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalRowID()
|
||||
try record.insert(db)
|
||||
let ids: [Int64?] = try MinimalRowID.all().selectID().fetchAll(db)
|
||||
XCTAssertEqual(ids, [1])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -375,7 +375,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
|
||||
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - Fetch With Key Request
|
||||
|
||||
@@ -661,7 +661,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
|
||||
_ = try MinimalSingle.find(db, key: id)
|
||||
XCTFail("Expected RecordError")
|
||||
} catch RecordError.recordNotFound(databaseTableName: "minimalSingles", key: ["UUID": .null]) { }
|
||||
|
||||
|
||||
do {
|
||||
let fetchedRecord = try MinimalSingle.find(db, key: record.UUID)
|
||||
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
|
||||
@@ -680,7 +680,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - Fetch With Primary Key Request
|
||||
|
||||
@@ -861,7 +861,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
// MARK: Select PrimaryKey
|
||||
|
||||
|
||||
func test_static_selectPrimaryKey() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
@@ -875,6 +875,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_static_selectID() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalSingle()
|
||||
record.UUID = "theUUID"
|
||||
try record.insert(db)
|
||||
let ids: [String] = try MinimalSingle.selectID().fetchAll(db)
|
||||
XCTAssertEqual(ids, ["theUUID"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_request_selectPrimaryKey() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
@@ -887,4 +898,15 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows, [["UUID": "theUUID"]])
|
||||
}
|
||||
}
|
||||
|
||||
func test_request_selectID() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = MinimalSingle()
|
||||
record.UUID = "theUUID"
|
||||
try record.insert(db)
|
||||
let ids: [String] = try MinimalSingle.all().selectID().fetchAll(db)
|
||||
XCTAssertEqual(ids, ["theUUID"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
private struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
private struct Hacker : TableRecord {
|
||||
static let databaseTableName = "hackers"
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable {
|
||||
var id: Int64
|
||||
|
||||
@@ -133,6 +133,8 @@ class TableTests: GRDBTestCase {
|
||||
try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """
|
||||
SELECT * FROM "player" WHERE "id" IN (1, 2, 3)
|
||||
""")
|
||||
|
||||
try XCTAssertEqual(t.selectID().fetchOne(db), 1)
|
||||
}
|
||||
|
||||
do {
|
||||
@@ -148,6 +150,8 @@ class TableTests: GRDBTestCase {
|
||||
try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """
|
||||
SELECT * FROM "player" WHERE "id" IN (1, 2, 3)
|
||||
""")
|
||||
|
||||
try XCTAssertEqual(t.selectID().fetchOne(db), 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif SWIFT_PACKAGE
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import Dispatch
|
||||
import XCTest
|
||||
|
||||
#if canImport(Darwin) // needed for FailureTestCase
|
||||
class ValueObservationRecorderTests: FailureTestCase {
|
||||
// MARK: - NextOne
|
||||
|
||||
@@ -782,4 +781,3 @@ class ValueObservationRecorderTests: FailureTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,11 +1,7 @@
|
||||
import XCTest
|
||||
import Dispatch
|
||||
@testable import GRDB
|
||||
#if GRDBCIPHER
|
||||
import SQLCipher
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
class ValueObservationTests: GRDBTestCase {
|
||||
// Test passes if it compiles.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1541>
|
||||
@@ -1356,5 +1352,58 @@ class ValueObservationTests: GRDBTestCase {
|
||||
XCTAssertEqual(value, true)
|
||||
})
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/discussions/1746>
|
||||
@MainActor func testIssue1746() async throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try await dbQueue.write { db in
|
||||
try db.execute(sql: "CREATE TABLE test (id INTEGER PRIMARY KEY)")
|
||||
}
|
||||
|
||||
// Start a task that waits for writeContinuation before it writes.
|
||||
let (writeStream, writeContinuation) = AsyncStream.makeStream(of: Void.self)
|
||||
let task = Task {
|
||||
for await _ in writeStream { }
|
||||
try? await dbQueue.write { db in
|
||||
XCTAssertFalse(Task.isCancelled) // Required for the test to be meaningful
|
||||
try db.execute(sql: "INSERT INTO test DEFAULT VALUES")
|
||||
}
|
||||
}
|
||||
|
||||
// A transaction observer that cancels a Task after commit.
|
||||
class CancelObserver: TransactionObserver {
|
||||
let task: Task<Void, Never>
|
||||
init(task: Task<Void, Never>) {
|
||||
self.task = task
|
||||
}
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true }
|
||||
func databaseDidChange(with event: DatabaseEvent) { }
|
||||
func databaseDidRollback(_ db: Database) { }
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
task.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// Register CancelObserver first, so no other observer could access
|
||||
// the database before the task is cancelled.
|
||||
dbQueue.add(transactionObserver: CancelObserver(task: task), extent: .databaseLifetime)
|
||||
|
||||
// Start observing.
|
||||
// We expect to see 0, then 1.
|
||||
let values = ValueObservation
|
||||
.tracking(Table("test").fetchCount)
|
||||
.values(in: dbQueue)
|
||||
for try await value in values {
|
||||
if value == 0 {
|
||||
// Perform the write.
|
||||
writeContinuation.finish()
|
||||
} else if value == 1 {
|
||||
// Test passes
|
||||
break
|
||||
} else {
|
||||
XCTFail("Unexpected value \(value)")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user