Compare commits

...
13 changed files with 259 additions and 41 deletions

No files matched your search

+8
View File
@@ -7,6 +7,7 @@ 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)
@@ -135,6 +136,13 @@ 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
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.3.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.'
+3 -5
View File
@@ -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
}
+33 -3
View File
@@ -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 {
@@ -1303,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
}
+14 -4
View File
@@ -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()
+47 -7
View File
@@ -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.
>
@@ -2209,8 +2209,10 @@ extension SQLExpressible where Self == Column {
/// - ``localizedLowercased``
/// - ``localizedUppercased``
/// - ``lowercased``
/// - ``min(_:_:_:)``
/// - ``min(_:)``
/// - ``min(_:filter:)``
/// - ``max(_:_:_:)``
/// - ``max(_:)``
/// - ``max(_:filter:)``
/// - ``sum(_:)``
+47 -15
View File
@@ -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:
///
@@ -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 -1
View File
@@ -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**: February 23, 2025 • [version 7.3.0](https://github.com/groue/GRDB.swift/tree/v7.3.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+ &bull; SQLite 3.20.0+ &bull; Swift 6+ / Xcode 16+
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.3.0</string>
<string>7.4.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -1559,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(
@@ -1570,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 {
@@ -1592,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(
@@ -1603,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 {
@@ -1352,4 +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
}
}
}
}