From 2c5a86479a54ccbc1db6d642acd91c6f10489496 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Dec 2022 21:33:19 +0100 Subject: [PATCH] DocC: Transactions and Savepoints --- GRDB/Core/Configuration.swift | 9 + GRDB/Core/DatabasePool.swift | 60 ----- GRDB/Core/DatabaseQueue.swift | 45 ---- GRDB/Documentation.docc/Concurrency.md | 2 +- .../Documentation.docc/DatabaseConnections.md | 19 +- GRDB/Documentation.docc/Documentation.md | 1 + .../Extension/DatabasePool.md | 96 +++++++ .../Extension/DatabaseQueue.md | 102 ++++++++ GRDB/Documentation.docc/SQLSupport.md | 2 +- GRDB/Documentation.docc/Transactions.md | 239 ++++++++++++++++++ README.md | 235 +---------------- 11 files changed, 471 insertions(+), 339 deletions(-) create mode 100644 GRDB/Documentation.docc/Extension/DatabasePool.md create mode 100644 GRDB/Documentation.docc/Extension/DatabaseQueue.md create mode 100644 GRDB/Documentation.docc/Transactions.md diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 174e96965..13f5fd213 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -64,6 +64,15 @@ public struct Configuration { /// A boolean value indicating whether an SQLite connection is read-only. /// /// The default is false. + /// + /// ```swift + /// var config = Configuration() + /// config.readonly = true + /// + /// let dbQueue = try DatabaseQueue( // or DatabasePool + /// path: "/path/to/database.sqlite", + /// configuration: config) + /// ``` public var readonly = false /// A label that describes a database connection. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5c5afa1d1..198526cf1 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -4,66 +4,6 @@ import Foundation import UIKit #endif -/// A database connection that allows concurrent accesses to an SQLite database. -/// -/// ## Overview -/// -/// Unless ``Configuration/readonly``, a `DatabasePool` opens an SQLite database -/// in the [WAL mode](https://sqlite.org/wal.html). -/// -/// It creates one writer SQLite connection, and a pool of up to -/// ``Configuration/maximumReaderCount`` read-only SQLite connections. All -/// write accesses are executed in a serial **writer dispatch queue**. All -/// read accesses are executed in **reader dispatch queues** (one per read-only -/// SQLite connection). SQLite connections are closed when the `DatabasePool` -/// is deallocated. -/// -/// See for more information about concurrent -/// database accesses. -/// -/// ## Usage -/// -/// ```swift -/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") -/// -/// let playerCount = try dbPool.read { db in -/// try Player.fetchCount(db) -/// } -/// -/// let newPlayerCount = try dbPool.write { db -> Int in -/// try Player(name: "Arthur").insert(db) -/// return try Player.fetchCount(db) -/// } -/// ``` -/// -/// `DatabasePool` inherits most of its database access methods from the -/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few -/// specific database access methods as well. -/// -/// ## Topics -/// -/// ### Creating a DatabasePool -/// -/// - ``init(path:configuration:)`` -/// -/// ### Accessing the Database -/// -/// See ``DatabaseReader`` and ``DatabaseWriter`` for more database -/// access methods. -/// -/// - ``asyncConcurrentRead(_:)`` -/// - ``writeInTransaction(_:_:)`` -/// -/// ### Creating Database Snapshots -/// -/// - ``makeSnapshot()`` -/// - ``makeSnapshotPool()`` -/// -/// ### Managing SQLite Connections -/// -/// - ``invalidateReadOnlyConnections()`` -/// - ``releaseMemory()`` -/// - ``releaseMemoryEventually()`` public final class DatabasePool { private let writer: SerializedDatabase diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 1e8268467..5da64d673 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -4,51 +4,6 @@ import Foundation import UIKit #endif -/// A database connection that serializes accesses to an SQLite database. -/// -/// ## Overview -/// -/// A `DatabaseQueue` creates one single SQLite connection. All database -/// accesses are executed in a serial **writer dispatch queue**. The SQLite -/// connection is closed when the `DatabaseQueue` is deallocated. -/// -/// ```swift -/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") -/// -/// let playerCount = try dbQueue.read { db in -/// try Player.fetchCount(db) -/// } -/// -/// let newPlayerCount = try dbQueue.write { db -> Int in -/// try Player(name: "Arthur").insert(db) -/// return try Player.fetchCount(db) -/// } -/// ``` -/// -/// ## Usage -/// -/// `DatabaseQueue` inherits most of its database access methods from the -/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few -/// specific database access methods as well. -/// -/// ## Topics -/// -/// ### Creating a DatabaseQueue -/// -/// - ``init(named:configuration:)`` -/// - ``init(path:configuration:)`` -/// -/// ### Accessing the Database -/// -/// See ``DatabaseReader`` and ``DatabaseWriter`` for more database -/// access methods. -/// -/// - ``inDatabase(_:)`` -/// - ``inTransaction(_:_:)`` -/// -/// ### Managing the SQLite Connection -/// -/// - ``releaseMemory()`` public final class DatabaseQueue { private let writer: SerializedDatabase diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index 4f6efbe02..24a69c248 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -45,7 +45,7 @@ try dbQueue.read { db } ``` -Alternatively, you can open an explicit transaction or savepoint with ``Database/inTransaction(_:_:)`` and ``Database/inSavepoint(_:)``. +Alternatively, you can open an explicit transaction or savepoint: see . - *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task. Transactions also avoid concurrency problems, as described in the section below. diff --git a/GRDB/Documentation.docc/DatabaseConnections.md b/GRDB/Documentation.docc/DatabaseConnections.md index db6321bd9..074eb7aaa 100644 --- a/GRDB/Documentation.docc/DatabaseConnections.md +++ b/GRDB/Documentation.docc/DatabaseConnections.md @@ -17,25 +17,34 @@ let dbPool = try DatabasePool(path: "/path/to/database.sqlite") The differences are: - `DatabasePool` allows concurrent database accesses (this can improve the performance of multithreaded applications). -- `DatabasePool` opens your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) (unless read-only). -- `DatabaseQueue` supports [in-memory databases](https://www.sqlite.org/inmemorydb.html). +- `DatabasePool` opens your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) (unless ``Configuration/readonly``). +- `DatabaseQueue` supports . **If you are not sure, choose `DatabaseQueue`.** You will always be able to switch to `DatabasePool` later. +Once connected, you can define the database schema, and access the database with raw SQL or high-level Swift apis: + +- +- +- + ## Topics -### Configuring Database Connections +### Configuring database connections - ``Configuration`` -### Database Connections +### Connections for read and write accesses - ``DatabaseQueue`` - ``DatabasePool`` + +### Read-only connections on an unchanging database content + - ``DatabaseSnapshot`` - ``DatabaseSnapshotPool`` -### Using Database Connections +### Using database connections - ``Database`` - ``DatabaseError`` diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md index e6531907b..eead88397 100644 --- a/GRDB/Documentation.docc/Documentation.md +++ b/GRDB/Documentation.docc/Documentation.md @@ -21,6 +21,7 @@ Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMD - - - +- ### Migrations and The Database Schema diff --git a/GRDB/Documentation.docc/Extension/DatabasePool.md b/GRDB/Documentation.docc/Extension/DatabasePool.md new file mode 100644 index 000000000..d6bce4603 --- /dev/null +++ b/GRDB/Documentation.docc/Extension/DatabasePool.md @@ -0,0 +1,96 @@ +# ``GRDB/DatabasePool`` + +A database connection that allows concurrent accesses to an SQLite database. + +## Usage + +**Open a `DatabasePool`** with the path to a database file: + +```swift +import GRDB + +let dbPool = try DatabasePool(path: "/path/to/database.sqlite") +``` + +SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated. + +**A `DatabasePool` can be used from any thread.** The ``DatabaseWriter/write(_:)-76inz`` and ``DatabaseReader/read(_:)-3806d`` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: + +```swift +// Modify the database: +try dbPool.write { db in + try Player(name: "Arthur").insert(db) +} + +// Read values: +try dbPool.read { db in + let players = try Player.fetchAll(db) + let playerCount = try Player.fetchCount(db) +} +``` + +Database access methods can return values: + +```swift +let playerCount = try dbPool.read { db in + try Place.fetchCount(db) +} + +let newPlayerCount = try dbPool.write { db -> Int in + try Player(name: "Arthur").insert(db) + return try Player.fetchCount(db) +} +``` + +The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown. + +When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method, because several threads can perform reads in parallel. + +When precise transaction handling is required, see . + +Asynchronous database accesses are described in . + +`DatabasePool` can take snapshots of the database: see ``DatabaseSnapshot`` and ``DatabaseSnapshotPool``. + +`DatabasePool` can be configured with ``Configuration``. + +## Concurrency + +A `DatabasePool` creates one writer SQLite connection, and a pool of read-only SQLite connections. + +Unless ``Configuration/readonly``, the database is set to the [WAL mode](https://sqlite.org/wal.html). The WAL mode makes it possible for reads and writes to proceed concurrently. + +All write accesses are executed in a serial **writer dispatch queue**, which means that there is never more than one thread that writes in the database. + +All read accesses are executed in **reader dispatch queues** (one per read-only SQLite connection). Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be configured with ``Configuration/maximumReaderCount``. + +SQLite connections are closed when the `DatabasePool` is deallocated. + +`DatabasePool` inherits most of its database access methods from the ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few specific database access methods as well, listed below. + +A `DatabasePool` needs your application to follow rules in order to deliver its safety guarantees. See for more information. + +## Topics + +### Creating a DatabasePool + +- ``init(path:configuration:)`` + +### Accessing the Database + +See ``DatabaseReader`` and ``DatabaseWriter`` for more database +access methods. + +- ``asyncConcurrentRead(_:)`` +- ``writeInTransaction(_:_:)`` + +### Creating Database Snapshots + +- ``makeSnapshot()`` +- ``makeSnapshotPool()`` + +### Managing SQLite Connections + +- ``invalidateReadOnlyConnections()`` +- ``releaseMemory()`` +- ``releaseMemoryEventually()`` diff --git a/GRDB/Documentation.docc/Extension/DatabaseQueue.md b/GRDB/Documentation.docc/Extension/DatabaseQueue.md new file mode 100644 index 000000000..df9abe58d --- /dev/null +++ b/GRDB/Documentation.docc/Extension/DatabaseQueue.md @@ -0,0 +1,102 @@ +# ``GRDB/DatabaseQueue`` + +A database connection that serializes accesses to an SQLite database. + +## Usage + +**Open a `DatabaseQueue`** with the path to a database file: + +```swift +import GRDB + +let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") +``` + +SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated. + +**A `DatabaseQueue` can be used from any thread.** The ``DatabaseWriter/write(_:)-76inz`` and ``DatabaseReader/read(_:)-3806d`` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: + +```swift +// Modify the database: +try dbQueue.write { db in + try Player(name: "Arthur").insert(db) +} + +// Read values: +try dbQueue.read { db in + let players = try Player.fetchAll(db) + let playerCount = try Player.fetchCount(db) +} +``` + +Database access methods can return values: + +```swift +let playerCount = try dbQueue.read { db in + try Place.fetchCount(db) +} + +let newPlayerCount = try dbQueue.write { db -> Int in + try Player(name: "Arthur").insert(db) + return try Player.fetchCount(db) +} +``` + +The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown. + +When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method: it prevents any modification to the database. + +When precise transaction handling is required, see . + +Asynchronous database accesses are described in . + +`DatabaseQueue` can be configured with ``Configuration``. + +## In-Memory Databases + +`DatabaseQueue` can open a connection to an [in-memory SQLite database](https://www.sqlite.org/inmemorydb.html). + +Such connections are quite handy for tests and SwiftUI previews, since you do not have to perform any cleanup of the file system. + +```swift +let dbQueue = try DatabaseQueue() +``` + +In order to create several connections to the same in-memory database, give this database a name: + +```swift +// A shared in-memory database +let dbQueue1 = try DatabaseQueue(named: "myDatabase") + +// Another connection to the same database +let dbQueue2 = try DatabaseQueue(named: "myDatabase") +``` + +See ``init(named:configuration:)``. + +## Concurrency + +A `DatabaseQueue` creates one single SQLite connection. All database accesses are executed in a serial **writer dispatch queue**, which means that there is never more than one thread that uses the database. The SQLite connection is closed when the `DatabaseQueue` is deallocated. + +`DatabaseQueue` inherits most of its database access methods from the ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few specific database access methods as well, listed below. + +A `DatabaseQueue` needs your application to follow rules in order to deliver its safety guarantees. See for more information. + +## Topics + +### Creating a DatabaseQueue + +- ``init(named:configuration:)`` +- ``init(path:configuration:)`` + +### Accessing the Database + +See ``DatabaseReader`` and ``DatabaseWriter`` for more database +access methods. + +- ``inDatabase(_:)`` +- ``inTransaction(_:_:)`` + +### Managing the SQLite Connection + +- ``releaseMemory()`` diff --git a/GRDB/Documentation.docc/SQLSupport.md b/GRDB/Documentation.docc/SQLSupport.md index f857f08ef..7fbdb7cd0 100644 --- a/GRDB/Documentation.docc/SQLSupport.md +++ b/GRDB/Documentation.docc/SQLSupport.md @@ -23,7 +23,7 @@ try dbQueue.write { db in } ``` -Build prepared ``Statement`` and lazily iterate fetched rows with an efficient and fast ``DatabaseCursor``: +Build a prepared ``Statement`` and lazily iterate a ``DatabaseCursor`` of ``Row``: ```swift try dbQueue.read { db in diff --git a/GRDB/Documentation.docc/Transactions.md b/GRDB/Documentation.docc/Transactions.md new file mode 100644 index 000000000..b12c3f32f --- /dev/null +++ b/GRDB/Documentation.docc/Transactions.md @@ -0,0 +1,239 @@ +# Transactions and Savepoints + +## Transactions and Safety + +**A transaction is a fundamental tool of SQLite** that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. It is at the core of GRDB guarantees. + +To profit from database transactions, all you have to do is group related database statements in a single database access method such as ``DatabaseWriter/write(_:)-76inz`` or ``DatabaseReader/read(_:)-3806d``: + +```swift +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbQueue.write { db in + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) +} + +// BEGIN TRANSACTION +// SELECT * FROM credit +// SELECT * FROM debit +// COMMIT +let (credits, debits) = try dbQueue.read { db in + let credits = try Credit.fetchAll(db) + let debits = try Debit.fetchAll(db) + return (credits, debits) +} +``` + +In the following sections we'll explore how you can avoid transactions, and how to perform explicit transactions and savepoints. + +## Database Accesses without Transactions + +When needed, you can write outside of any transaction with ``DatabaseWriter/writeWithoutTransaction(_:)-4qh1w`` (also named `inDatabase(_:)`, for `DatabaseQueue`): + +```swift +// INSERT INTO credit ... +// INSERT INTO debit ... +try dbQueue.writeWithoutTransaction { db in + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) +} +``` + +For reads, use ``DatabaseReader/unsafeRead(_:)-5i7tf``: + +```swift +// SELECT * FROM credit +// SELECT * FROM debit +let (credits, debits) = try dbPool.unsafeRead { db in + let credits = try Credit.fetchAll(db) + let debits = try Debit.fetchAll(db) + return (credits, debits) +} +``` + +Those method names, `writeWithoutTransaction` and `unsafeRead`, are longer and "scarier" than the regular `write` and `read` in order to draw your attention to the dangers of those unisolated accesses. + +In our credit/debit example, a credit may be successfully inserted, but the debit insertion may fail, ending up with unbalanced accounts (oops). + +```swift +// UNSAFE DATABASE INTEGRITY +try dbQueue.writeWithoutTransaction { db in // or dbPool.writeWithoutTransaction + try Credit(destinationAccount, amount).insert(db) + // 😬 May fail after credit was successfully written to disk: + try Debit(sourceAccount, amount).insert(db) +} +``` + +Transactions avoid this kind of bug. + +``DatabasePool`` concurrent reads can see an inconsistent state of the database: + +```swift +// UNSAFE CONCURRENCY +try dbPool.writeWithoutTransaction { db in + try Credit(destinationAccount, amount).insert(db) + // <- 😬 Here a concurrent read sees a partial db update (unbalanced accounts) + try Debit(sourceAccount, amount).insert(db) +} +``` + +Transactions avoid this kind of bug, too. + +Finally, reads performed outside of any transaction are not isolated from concurrent writes. It is possible to see unbalanced accounts, even though the invariant is never broken on disk: + +```swift +// UNSAFE CONCURRENCY +let (credits, debits) = try dbPool.unsafeRead { db in + let credits = try Credit.fetchAll(db) + // <- 😬 Here a concurrent write can modify the balance before debits are fetched + let debits = try Debit.fetchAll(db) + return (credits, debits) +} +``` + +Yes, transactions also avoid this kind of bug. + +## Explicit Transactions + +To open explicit transactions, use `inTransaction()` or `writeInTransaction()`: + +```swift +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return .commit +} + +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbQueue.writeWithoutTransaction { db in + try db.inTransaction { + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return .commit + } +} +``` + +If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the transaction method. If the transaction closure returns `.rollback` instead of `.commit`, the transaction is also rollbacked, but no error is thrown. + +Full manual transaction management is also possible: + +```swift +try dbQueue.writeWithoutTransaction { db + try db.beginTransaction() + ... + try db.commit() + + try db.execute(sql: "BEGIN TRANSACTION") + ... + try db.execute(sql: "ROLLBACK") +} +``` + +Transactions can't be left opened unless the ``Configuration/allowsUnsafeTransactions`` configuration flag is set: + +```swift +// fatal error: A transaction has been left opened at the end of a database access +try dbQueue.writeWithoutTransaction { db in + try db.execute(sql: "BEGIN TRANSACTION") + // <- no commit or rollback +} +``` + +It is possible to ask if a transaction is currently opened: + +```swift +func myCriticalMethod(_ db: Database) throws { + precondition(db.isInsideTransaction, "This method requires a transaction") + try ... +} +``` + +Yet, there is a better option than checking for transactions. Critical database sections should use savepoints, described below: + +```swift +func myCriticalMethod(_ db: Database) throws { + try db.inSavepoint { + // Here the database is guaranteed to be inside a transaction. + try ... + } +} +``` + +## Savepoints + +**Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:** + +```swift +try dbQueue.write { db in + // Makes sure both inserts succeed, or none: + try db.inSavepoint { + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return .commit + } + + // Other savepoints, etc... +} +``` + +If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If the savepoint closure returns `.rollback` instead of `.commit`, the savepoint is also rollbacked, but no error is thrown. + +**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed: + +```swift +try dbQueue.writeWithoutTransaction { db in + try db.inSavepoint { + ... + try db.inSavepoint { + ... + return .commit + } + ... + return .commit // Writes changes to disk + } +} +``` + +SQLite savepoints are more than nested transactions, though. For advanced uses, use [SQLite savepoint documentation](https://www.sqlite.org/lang_savepoint.html). + + +## Transaction Kinds + +SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive. + +The transaction kind can be chosen for individual transaction: + +```swift +let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") + +// BEGIN EXCLUSIVE TRANSACTION ... +try dbQueue.inTransaction(.exclusive) { db in ... } +``` + +It is also possible to configure the ``Configuration/defaultTransactionKind``: + +```swift +var config = Configuration() +config.defaultTransactionKind = .immediate + +let dbQueue = try DatabaseQueue( + path: "/path/to/database.sqlite", + configuration: config) + +// BEGIN IMMEDIATE TRANSACTION ... +try dbQueue.write { db in ... } + +// BEGIN IMMEDIATE TRANSACTION ... +try dbQueue.inTransaction { db in ... } +``` diff --git a/README.md b/README.md index 1606288bf..42e33ed64 100644 --- a/README.md +++ b/README.md @@ -500,7 +500,7 @@ See the [Concurrency] guide for asynchronous database accesses. - The `write` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown. - When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). + When precise transaction handling is required, see [Transactions and Savepoints]. **A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency] guide. @@ -565,7 +565,7 @@ See the [Concurrency] guide for asynchronous database accesses. - The `write` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown. - When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). + When precise transaction handling is required, see [Transactions and Savepoints]. - Database pools can take [snapshots](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot) of the database. @@ -635,7 +635,7 @@ SQLite API - [NSNumber, NSDecimalNumber, and Decimal](#nsnumber-nsdecimalnumber-and-decimal) - [Swift enums](#swift-enums) - [Custom Value Types](#custom-value-types) -- [Transactions and Savepoints](#transactions-and-savepoints) +- [Transactions and Savepoints] - [SQL Interpolation] Advanced topics: @@ -1665,230 +1665,6 @@ In order to customize the JSON format, provide a custom implementation of the `D > **Note**: standard sequences such as `Array`, `Set`, or `Dictionary` do not conform to `DatabaseValueConvertible`, even conditionally. You won't be able to directly fetch or store arrays, sets, or dictionaries as JSON database values. You can get free JSON support from these standard types when they are embedded as properties of [Codable Records], though. -## Transactions and Savepoints - -- [Transactions and Safety](#transactions-and-safety) -- [Explicit Transactions](#explicit-transactions) -- [Savepoints](#savepoints) -- [Transaction Kinds](#transaction-kinds) - - -### Transactions and Safety - -**A transaction** is a fundamental tool of SQLite that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. - -GRDB generally opens transactions for you, as a way to enforce its [concurrency guarantees](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency), and provide maximal security for both your application data and application logic: - -```swift -// BEGIN TRANSACTION -// INSERT INTO credit ... -// INSERT INTO debit ... -// COMMIT -try dbQueue.write { db in - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) -} - -// BEGIN TRANSACTION -// INSERT INTO credit ... -// INSERT INTO debit ... -// COMMIT -try dbPool.write { db in - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) -} -``` - -Yet you may need to exactly control when transactions take place: - - -### Explicit Transactions - -`DatabaseQueue.inDatabase()` and `DatabasePool.writeWithoutTransaction()` execute your database statements outside of any transaction: - -```swift -// INSERT INTO credit ... -// INSERT INTO debit ... -try dbQueue.inDatabase { db in - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) -} - -// INSERT INTO credit ... -// INSERT INTO debit ... -try dbPool.writeWithoutTransaction { db in - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) -} -``` - -**Writing outside of any transaction is dangerous,** for two reasons: - -- In our credit/debit example, you may successfully insert a credit, but fail inserting the debit, and end up with unbalanced accounts (oops). - - ```swift - // UNSAFE DATABASE INTEGRITY - try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - try Credit(destinationAccount, amount).insert(db) // may succeed - try Debit(sourceAccount, amount).insert(db) // may fail - } - ``` - - Transactions avoid this kind of bug. - -- [Database pool](#database-pools) concurrent reads can see an inconsistent state of the database: - - ```swift - // UNSAFE CONCURRENCY - try dbPool.writeWithoutTransaction { db in - try Credit(destinationAccount, amount).insert(db) - // <- Concurrent dbPool.read sees a partial db update here - try Debit(sourceAccount, amount).insert(db) - } - ``` - - Transactions avoid this kind of bug, too. - -To open explicit transactions, use one of the `Database.inTransaction`, `DatabaseQueue.inTransaction`, or `DatabasePool.writeInTransaction` methods: - -```swift -// BEGIN TRANSACTION -// INSERT INTO credit ... -// INSERT INTO debit ... -// COMMIT -try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - try db.inTransaction { - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) - return .commit - } -} - -// BEGIN TRANSACTION -// INSERT INTO credit ... -// INSERT INTO debit ... -// COMMIT -try dbQueue.inTransaction { db in // or dbPool.writeInTransaction - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) - return .commit -} -``` - -If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the `inTransaction` method. If you return `.rollback` instead of `.commit`, the transaction is also rollbacked, but no error is thrown. - -You can also perform manual transaction management: - -```swift -try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - try db.beginTransaction() - ... - try db.commit() - - try db.execute(sql: "BEGIN TRANSACTION") - ... - try db.execute(sql: "ROLLBACK") -} -``` - -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/allowsunsafetransactions) configuration flag: - -```swift -// fatal error: A transaction has been left opened at the end of a database access -try dbQueue.inDatabase { db in - try db.execute(sql: "BEGIN TRANSACTION") - // <- no commit or rollback -} -``` - -You can ask if a transaction is currently opened: - -```swift -func myCriticalMethod(_ db: Database) throws { - precondition(db.isInsideTransaction, "This method requires a transaction") - try ... -} -``` - -Yet, you have a better option than checking for transactions: critical database sections should use savepoints, described below: - -```swift -func myCriticalMethod(_ db: Database) throws { - try db.inSavepoint { - // Here the database is guaranteed to be inside a transaction. - try ... - } -} -``` - - -### Savepoints - -**Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:** - -```swift -try dbQueue.write { db in - // Makes sure both inserts succeed, or none: - try db.inSavepoint { - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) - return .commit - } - - // Other savepoints, etc... -} -``` - -If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If you return `.rollback` instead of `.commit`, the savepoint is also rollbacked, but no error is thrown. - -**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed: - -```swift -try dbQueue.inDatabase { db in - try db.inSavepoint { - ... - try db.inSavepoint { - ... - return .commit - } - ... - return .commit // writes changes to disk - } -} -``` - -SQLite savepoints are more than nested transactions, though. For advanced uses, use [SQLite savepoint documentation](https://www.sqlite.org/lang_savepoint.html). - - -### Transaction Kinds - -SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive. - -The transaction kind can be changed in the database configuration, or for each transaction: - -```swift -// 1) Default configuration: -let dbQueue = try DatabaseQueue(path: "...") - -// BEGIN DEFERRED TRANSACTION ... -dbQueue.write { db in ... } - -// BEGIN EXCLUSIVE TRANSACTION ... -dbQueue.inTransaction(.exclusive) { db in ... } - -// 2) Customized default transaction kind: -var config = Configuration() -config.defaultTransactionKind = .immediate -let dbQueue = try DatabaseQueue(path: "...", configuration: config) - -// BEGIN IMMEDIATE TRANSACTION ... -dbQueue.write { db in ... } - -// BEGIN EXCLUSIVE TRANSACTION ... -dbQueue.inTransaction(.exclusive) { db in ... } -``` - - ## Prepared Statements **Prepared Statements** let you prepare an SQL query and execute it later, several times if you need, with different arguments. @@ -7366,6 +7142,10 @@ This protocol has been renamed [FetchableRecord] in GRDB 3.0. This protocol has been renamed [TableRecord] in GRDB 3.0. +#### Transactions and Savepoints + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions). + #### Transaction Hook This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)). @@ -7431,3 +7211,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Persistence Methods]: #persistence-methods [persistence methods]: #persistence-methods [RecordError]: #recorderror +[Transactions and Savepoints]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions \ No newline at end of file