Fix more typos in public documentation

This commit is contained in:
Gwendal Roué committed 2026-11-01 21:01:03 +01:00
1 parent 5d9e853f24
commit 909f7455e6
71 files changed
+207 -207

No files matched your search

+19 -19
View File
@@ -228,7 +228,7 @@ Associations to [common table expressions] are specific enough and are documente
## BelongsTo
The **BelongsTo** association sets up a one-to-one connection from a record type to another record type, such as each instance of the declaring record "belongs to" an instance of the other record.
The **BelongsTo** association sets up a one-to-one connection from a record type to another record type, such that each instance of the declaring record "belongs to" an instance of the other record.
For example, if your application includes authors and books, and each book is assigned its author, you'd declare the `Book.author` association as below:
@@ -252,7 +252,7 @@ See [Convention for the BelongsTo Association] for some sample code that defines
## HasMany
The **HasMany** association indicates a one-to-many connection between two record types, such as each instance of the declaring record "has many" instances of the other record. You'll often find this association on the other side of a **BelongsTo** association.
The **HasMany** association indicates a one-to-many connection between two record types, such that each instance of the declaring record "has many" instances of the other record. You'll often find this association on the other side of a **BelongsTo** association.
For example, if your application includes authors and books, and each author is assigned zero or more books, you'd declare the `Author.books` association as below:
@@ -946,7 +946,7 @@ let bookInfos = try Book
### `including(optional:)`
For example, fetch books along with their eventual author:
For example, fetch books along with their optional author:
```swift
// SELECT book.*, author.*
@@ -960,7 +960,7 @@ This method accepts any association. It has the base record fetched along with o
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with their eventual author
// Fetch all books along with their optional author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author? // The optional associated record
@@ -976,7 +976,7 @@ let bookInfos = try Book
**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record:
```swift
// Fetch all books along with the name and country of their eventual author
// Fetch all books along with the name and country of their optional author
struct BookInfo: Decodable, FetchableRecord {
struct PartialAuthor: Decodable {
var name: String
@@ -994,7 +994,7 @@ let bookInfos = try Book
But if you'd rather avoid this extra partial type, prefer [`annotated(withOptional:)`]:
```swift
// Fetch all books along with the country of their eventual author
// Fetch all books along with the country of their optional author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var country: String?
@@ -1133,7 +1133,7 @@ let bookInfos = try Book
### `annotated(withOptional:)`
For example, fetch books along with the name and country of their eventual author:
For example, fetch books along with the name and country of their optional author:
```swift
// SELECT book.*, author.name, author.country
@@ -1147,7 +1147,7 @@ This method accepts any association. The base record is annotated with the selec
**To fetch results from such a request**, you define a dedicated record type:
```swift
// Fetch all books along with the name of their eventual author
// Fetch all books along with the name of their optional author
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var name: String? // A column of the optional associated record
@@ -1162,7 +1162,7 @@ let bookInfos = try Book
If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type:
```swift
// Fetch all books along with the name of their eventual author
// Fetch all books along with the name of their optional author
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var authorName: String?
@@ -1216,7 +1216,7 @@ In the description of the [joining methods] above, we have seen that you need to
In this chapter, we take the reversed perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need.
> **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord].
> **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level APIs described in [Decoding a Joined Request with FetchableRecord].
- [`including(required:)`]
@@ -1270,7 +1270,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var author: Author? // The eventual associated record
var author: Author? // The optional associated record
}
let bookInfos = try Book
@@ -1286,7 +1286,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
var country: String
}
var book: Book // The base record
var author: PartialAuthor? // The eventual partial associated record
var author: PartialAuthor? // The optional partial associated record
}
let bookInfos = try Book
@@ -1300,8 +1300,8 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book // The base record
var authorName: String? // A column of the eventual associated record
var country: String? // A column of the eventual associated record
var authorName: String? // A column of the optional associated record
var country: String? // A column of the optional associated record
}
let bookInfos = try Book
@@ -1381,7 +1381,7 @@ struct BookInfo: FetchableRecord, Decodable {
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
```
The request above fetches all books, along with their author and eventual translator.
The request above fetches all books, along with their author and optional translator.
You can chain associations in order to jump from a record to another:
@@ -1762,7 +1762,7 @@ Associations support more refinements:
In all examples we have seen so far, all associated records are joined, included, filtered, and sorted independently. We could not filter them on conditions that involve several records, for example.
Let's say we look for posthumous books, published after their author has died. We need to compare a book publication date with an author eventual death date.
Let's say we look for posthumous books, published after their author has died. We need to compare a book publication date with an author's possible death date.
Let's first see a wrong way to do it:
@@ -2230,7 +2230,7 @@ let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
## Debugging Request Decoding
When you have difficulties building a Decodable record that successfully decodes a joined request, we advise to temporarily decode raw database rows, and inspect them.
When you have difficulties building a Decodable record that successfully decodes a joined request, we advise you to temporarily decode raw database rows, and inspect them.
```swift
let request = Book
@@ -2843,7 +2843,7 @@ But in the following example, we use the same association `Author.books` twice,
## DerivableRequest Protocol
The `DerivableRequest` protocol is adopted by both [query interface requests] such as `Author.all()` and associations such as `Book.author`. It is intended for you to use as a customization point when you want to extend the built-in GRDB apis.
The `DerivableRequest` protocol is adopted by both [query interface requests] such as `Author.all()` and associations such as `Book.author`. It is intended for you to use as a customization point when you want to extend the built-in GRDB APIs.
For example, we may want to define `orderedByName()` and `filter(country:)` request methods that make our requests easier to read:
@@ -2905,7 +2905,7 @@ See [Recommended Practices for Designing Record Types] for more information.
.filter { $0.publishDate >= authorAlias.deathDate })
```
- **You can't use the `including(all:)` method with a [HasMany] and a [HasManyThrough] associations that share the same base association in the same request**:
- **You can't use the `including(all:)` method with a [HasMany] and a [HasManyThrough] association that share the same base association in the same request**:
```swift
// NOT IMPLEMENTED
+4 -4
View File
@@ -134,7 +134,7 @@ let players = dbQueue.readPublisher { db in
Any attempt at modifying the database completes subscriptions with an error.
When you use a [database queue] or a [database snapshot], the read has to wait for any eventual concurrent database access performed by this queue or snapshot to complete.
When you use a [database queue] or a [database snapshot], the read has to wait for any concurrent database access performed by this queue or snapshot to complete.
When you use a [database pool], 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].
@@ -223,11 +223,11 @@ let publisher = observation.publisher(in: dbQueue)
This publisher has the same behavior as ValueObservation:
- It notifies an initial value before the eventual changes.
- It notifies an initial value before subsequent changes.
- It may coalesce subsequent changes into a single notification.
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
- It only completes when it is cancelled.
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
- By default, it notifies the initial value, as well as subsequent changes and errors, on the main thread, asynchronously.
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservationscheduler).
@@ -310,7 +310,7 @@ When you compose database publishers together with Combine operators such as `co
This is because each database publisher is isolated from others: each one of them sees its own state of the database. Whenever some database change is interleaved between publisher operations, publishers will process or publish values that may not fit well together.
In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent eventual concurrent database writes from messing with your app, and introducing bugs.
In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent concurrent database writes from messing with your app, and introducing bugs.
To this end, remember that *all database publishers can perform several requests*.
+1 -1
View File
@@ -132,7 +132,7 @@ let request = Player
>
> **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
>
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be confused with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
>
> ```swift
> cte.all().select(...).filter(...).group(...).order(...)
+3 -3
View File
@@ -9,7 +9,7 @@ GRDBDemo Application
The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to set up a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
@@ -23,13 +23,13 @@ The topics covered in this demo are:
- [AppDatabase.swift](GRDBDemo/Database/AppDatabase.swift)
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and provides methods that read and write.
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator) in order to set up the database schema, and provides methods that read and write.
`AppDatabase` is [tested](GRDBDemoTests/AppDatabaseTests.swift).
- [Persistence.swift](GRDBDemo/Database/Persistence.swift)
This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for SwiftUI previews.
This file instantiates various `AppDatabase` for the various projects' needs: one database on disk for the application, and in-memory databases for SwiftUI previews.
- [Player.swift](GRDBDemo/Database/Models/Player.swift)
+4 -4
View File
@@ -301,7 +301,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
FTS3Pattern instances are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
@@ -550,7 +550,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
FTS5Pattern instances are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
@@ -614,7 +614,7 @@ try db.create(virtualTable: "book_ft", using: FTS4()) { t in // or FTS5()
}
```
The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
Any content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
For more information, see the SQLite documentation about external content tables: [FTS4](https://www.sqlite.org/fts3.html#_external_content_fts4_tables_), [FTS5](https://sqlite.org/fts5.html#external_content_tables).
@@ -661,7 +661,7 @@ try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.
But if you need to load columns from the regular table, and in the same time perform a full-text search, then you will need to query both tables at the same time.
But if you need to load columns from the regular table, and also perform a full-text search, then you will need to query both tables at the same time.
That is because SQLite will throw an error when you try to perform a full-text search on a regular table:
+1 -1
View File
@@ -273,7 +273,7 @@ The changes can quite impact your application. We'll describe them below, as wel
observation.start(in: dbQueue, scheduling: .async(onQueue: queue), onError: ..., onChange: ...)
```
The GRDB 4 `startImmediately` parameter is no longer supported: ValueObservation now always emits an initial value, without waiting for eventual changes. It is up to your application to ignore this initial value if it wants to.
The GRDB 4 `startImmediately` parameter is no longer supported: ValueObservation now always emits an initial value, without waiting for changes. It is up to your application to ignore this initial value if it wants to.
### Removed ValueObservation Methods
+2 -2
View File
@@ -24,7 +24,7 @@ Before upgrading, ensure you are using the [latest GRDB 6 release](https://githu
GRDB 7 requires Xcode 16+ and a Swift 6 compiler.
Depending on the language mode and level of concurrency checkings used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice.
Depending on the language mode and level of concurrency checking used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice.
## New requirements
@@ -237,7 +237,7 @@ Subclassing the [Record] class is **discouraged** in GRDB 7. Present in GRDB 1.0
It is not recommended to define any new type that subclasses `Record`.
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checkings or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checking or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
For example:
+1 -1
View File
@@ -477,7 +477,7 @@ This chapter lists all kinds of supported interpolations.
"SELECT * FROM player WHERE \(literal: condition)"
```
- Plain SQL strings and eventual arguments:
- Plain SQL strings and optional arguments:
```swift
// SELECT * FROM player
+3 -3
View File
@@ -155,7 +155,7 @@ public struct Configuration: Sendable {
/// }
/// ```
///
/// For debugging purpose, you can set this flag to true, and get more
/// For debugging purposes, you can set this flag to true, and get more
/// precise database reports. It is your responsibility to prevent sensitive
/// information from leaking in unexpected locations, so you should not set
/// this flag in release builds (think about GDPR and other
@@ -253,13 +253,13 @@ public struct Configuration: Sendable {
/// ```swift
/// let dbQueue = try DatabaseQueue()
///
/// // fatal error: A transaction has been left opened at the end of a database access
/// // fatal error: A transaction has been left open at the end of a database access
/// try dbQueue.inDatabase { db in
/// try db.beginTransaction()
/// }
/// ```
///
/// When true, one can leave an opened transaction at the end of a database
/// When true, one can leave an open transaction at the end of a database
/// access method:
///
/// ```swift
+2 -2
View File
@@ -1520,7 +1520,7 @@ public struct ForeignKeyViolation: Sendable {
/// The returned error has the extended code `SQLITE_CONSTRAINT_FOREIGNKEY`.
public func databaseError(_ db: Database) -> DatabaseError {
// Grab detailed information, if possible, for better error message.
// If detailed information is not available, fallback to plain description.
// If detailed information is not available, fall back to plain description.
let message = (try? failureDescription(db)) ?? String(describing: self)
return DatabaseError(
resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY,
@@ -1737,7 +1737,7 @@ public struct PrimaryKeyInfo: Sendable {
return columns[0]
} else {
// WITHOUT ROWID table or view customized with the schemaSource
// with a multi-columns primary key
// with a multi-column primary key
return nil
}
}
+1 -1
View File
@@ -143,7 +143,7 @@ extension Database {
/// ```
///
/// The returned statement may have already been used: it may or may not
/// contain values for its eventual arguments.
/// contain values for its arguments, if any.
///
/// - parameter sql: An SQL string.
/// - returns: A prepared statement.
+2 -2
View File
@@ -1179,7 +1179,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// A suspended database makes everything to avoid acquiring a lock on the
/// A suspended database does everything to avoid acquiring a lock on the
/// database. All database operations may throw a ``DatabaseError`` of code
/// `SQLITE_INTERRUPT` or `SQLITE_ABORT`, except reads in WAL mode.
///
@@ -1431,7 +1431,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
throw CancellationError()
case .abort:
// Attempt at releasing an eventual lock with ROLLBACk,
// Attempt to release a possible lock with ROLLBACK,
// as explained in Database.suspend().
try? rollback()
+5 -5
View File
@@ -353,10 +353,10 @@ public struct DatabaseError: Error {
///
/// - parameters:
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
/// - message: An eventual error message. If nil, the error message is
/// - message: An optional error message. If nil, the error message is
/// derived from the result code.
/// - sql: An eventual SQL string.
/// - arguments: Eventual statement arguments.
/// - sql: An optional SQL string.
/// - arguments: Optional statement arguments.
/// - publicStatementArguments: If false (the default), statement
/// arguments are not visible in the error's ``description`` property.
public init(
@@ -375,7 +375,7 @@ public struct DatabaseError: Error {
/// Creates a Database Error with a raw CInt result code.
///
/// This initializer is not public because library user is not supposed to
/// This initializer is not public because library users are not supposed to
/// be exposed to raw result codes.
@usableFromInline
init(resultCode: CInt, message: String? = nil, sql: String? = nil) {
@@ -387,7 +387,7 @@ public struct DatabaseError: Error {
/// Creates a Database Error with a raw CInt result code.
///
/// This initializer is not public because library user is not supposed to
/// This initializer is not public because library users are not supposed to
/// be exposed to raw result codes.
@usableFromInline
init(
+5 -5
View File
@@ -59,7 +59,7 @@ public final class DatabasePool {
// Readers can't allow dangling transactions because there's no
// guarantee that one can get the same reader later in order to close
// an opened transaction.
// an open transaction.
readerConfiguration.allowsUnsafeTransactions = false
readerPool = Pool(
@@ -178,7 +178,7 @@ extension DatabasePool {
// documented.
//
// Without the barrier, connections would only close _eventually_ (after
// their eventual concurrent jobs have completed).
// their concurrent jobs have completed).
readerPool?.barrier {
readerPool?.removeAll()
}
@@ -505,8 +505,8 @@ extension DatabasePool: DatabaseReader {
/// any transaction. You'll get a fatal error otherwise.
///
/// The `value` function is guaranteed to see the database in the last
/// committed state at the moment this method is called. Eventual
/// concurrent database updates are not visible from the function.
/// committed state at the moment this method is called. Concurrent
/// database updates are not visible from the function.
///
/// This method returns as soon as the isolation guarantee described above
/// has been established.
@@ -646,7 +646,7 @@ extension DatabasePool: DatabaseReader {
/// After this method is called, read-only database access methods will use
/// new SQLite connections.
///
/// Eventual concurrent read-only accesses are not interrupted, and
/// Concurrent read-only accesses are not interrupted, and
/// proceed until completion.
///
/// - This method closes all read-only connections, even if the
+4 -4
View File
@@ -168,7 +168,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// ```
///
/// Database operations are isolated in a transaction: they do not see
/// changes performed by eventual concurrent writes (even writes performed
/// changes performed by concurrent writes (even writes performed
/// by other processes).
///
/// The database connection is read-only: attempts to write throw a
@@ -200,7 +200,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// ```
///
/// Database operations are isolated in a transaction: they do not see
/// changes performed by eventual concurrent writes (even writes performed
/// changes performed by concurrent writes (even writes performed
/// by other processes).
///
/// The database connection is read-only: attempts to write throw a
@@ -235,7 +235,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// ```
///
/// Database operations are isolated in a transaction: they do not see
/// changes performed by eventual concurrent writes (even writes performed
/// changes performed by concurrent writes (even writes performed
/// by other processes).
///
/// The database connection is read-only: attempts to write throw a
@@ -517,7 +517,7 @@ extension DatabaseReader {
/// ```
///
/// Database operations are isolated in a transaction: they do not see
/// changes performed by eventual concurrent writes (even writes performed
/// changes performed by concurrent writes (even writes performed
/// by other processes).
///
/// The database connection is read-only: attempts to write throw a
+1 -1
View File
@@ -109,7 +109,7 @@ public protocol DatabaseSchemaSource: Sendable {
/// When you are developing a schema source for a library, some extra
/// care is necessary whenever the database file is owned by the users
/// of your library. Your users may define views for their own purposes,
/// and your library knows nothing about the eventual primary key of
/// and your library knows nothing about the possible primary key of
/// those views.
///
/// In this case, make your schema source `public`, and have this method
+2 -2
View File
@@ -278,7 +278,7 @@ extension DatabaseValue: Equatable {
/// 1.databaseValue == 1.0.databaseValue // true
/// ```
///
/// For a comparison that distinguishes integer and doubles, compare
/// For a comparison that distinguishes integers and doubles, compare
/// storages instead:
///
/// ```swift
@@ -366,7 +366,7 @@ extension DatabaseValue: CustomStringConvertible {
/// This comparison is not public because it does not handle text collations,
/// and may be dangerous when put in user hands.
///
/// So far, the only goal of this sorting method so far is aesthetic, and
/// So far, the only goal of this sorting method is aesthetic, and
/// easier testing.
func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
switch (lhs.storage, rhs.storage) {
+1 -1
View File
@@ -336,7 +336,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// any transaction. You'll get a fatal error otherwise.
///
/// Database operations performed by the `value` closure are isolated in a
/// transaction: they do not see changes performed by eventual concurrent
/// transaction: they do not see changes performed by concurrent
/// writes (even writes performed by other processes).
///
/// They see the database in the state left by the last updates performed
+2 -2
View File
@@ -134,7 +134,7 @@ public struct PreparedRequest {
/// A prepared statement with bound parameters.
public var statement: Statement
/// An eventual adapter for rows fetched by the select statement.
/// An optional adapter for rows fetched by the select statement.
public var adapter: (any RowAdapter)?
/// A closure that performs supplementary fetches.
@@ -166,7 +166,7 @@ extension FetchRequest {
///
/// The returned request performs an identical database query, but adapts
/// the fetched rows. See ``RowAdapter``, and
/// ``splittingRowAdapters(columnCounts:)`` for a sample code that uses
/// ``splittingRowAdapters(columnCounts:)`` for sample code that uses
/// `adapted(_:)`.
///
/// - parameter adapter: A closure that accepts a database connection and
+4 -4
View File
@@ -815,7 +815,7 @@ extension Row {
try! decode(Record.self, forKey: scope)
}
/// Returns the eventual record associated to the given key.
/// Returns the record associated to the given key, if any.
///
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
@@ -842,7 +842,7 @@ extension Row {
///
/// struct Country: TableRecord, FetchableRecord { }
///
/// // Fetch a book, with its eventual author, and the country of its author.
/// // Fetch a book, with its optional author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
@@ -1393,7 +1393,7 @@ extension Row {
// MARK: - Throwing Record Decoding Methods
extension Row {
/// Returns the eventual record associated to the given key.
/// Returns the record associated to the given key, if any.
///
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
@@ -1420,7 +1420,7 @@ extension Row {
///
/// struct Country: TableRecord, FetchableRecord { }
///
/// // Fetch a book, with its eventual author, and the country of its author.
/// // Fetch a book, with its optional author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
+3 -3
View File
@@ -65,7 +65,7 @@ import Foundation
/// ```
///
/// You can package this technique in a dedicated type, as in the next
/// example. It enhances the previous sample codes with:
/// example. It enhances the previous code samples with:
///
/// - Support for record types that customize their fetched columns
/// with ``TableRecord/databaseSelection-7iphs``.
@@ -343,7 +343,7 @@ extension RowAdapter {
/// Returns an adapter based on self, with added scopes.
///
/// If self already defines scopes, the added scopes replace
/// eventual existing scopes with the same name.
/// any existing scopes with the same name.
///
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
@@ -586,7 +586,7 @@ public struct ScopeAdapter: RowAdapter {
/// row.scopes["suffix"] // [2, 3]
///
/// If the base adapter already defines scopes, the given scopes replace
/// eventual existing scopes with the same name.
/// any existing scopes with the same name.
///
/// This initializer is equivalent to `baseAdapter.addingScopes(scopes)`.
///
+3 -3
View File
@@ -63,7 +63,7 @@ public struct SQL: Sendable {
/// .filter(date(Column("createdAt")) == "2022-08-17")
/// .including(required: Player.team)
enum Element {
/// A raw SQL literal with eventual arguments.
/// A raw SQL literal with optional arguments.
case sql(String, StatementArguments = StatementArguments())
/// A subquery.
@@ -144,7 +144,7 @@ public struct SQL: Sendable {
}
/// Creates an `SQL` literal from a plain SQL string, and
/// eventual arguments.
/// optional arguments.
///
/// For example:
///
@@ -240,7 +240,7 @@ extension SQL {
self += sqlLiteral
}
/// Appends a plain SQL string to the receiver, and eventual arguments.
/// Appends a plain SQL string to the receiver, and optional arguments.
///
/// For example:
///
+1 -1
View File
@@ -11,7 +11,7 @@ public struct SQLInterpolation: StringInterpolationProtocol {
elements.append(.sql(sql))
}
/// Appends a raw SQL snippet, with eventual arguments.
/// Appends a raw SQL snippet, with optional arguments.
///
/// For example:
///
+2 -2
View File
@@ -293,10 +293,10 @@ final class SerializedDatabase {
SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line)
}
/// Fatal error if a transaction has been left opened.
/// Fatal error if a transaction has been left open.
private func preconditionNoUnsafeTransactionLeft(
_ db: Database,
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
_ message: @autoclosure() -> String = "A transaction has been left open at the end of a database access",
file: StaticString = #file,
line: UInt = #line)
{
+2 -2
View File
@@ -106,7 +106,7 @@ public final class Statement {
/// is executed (reported by `sqlite3_set_authorizer`).
private(set) var invalidatesDatabaseSchemaCache = false
/// The eventual effect of transactions, as reported by `sqlite3_set_authorizer`.
/// The optional effect of transactions, as reported by `sqlite3_set_authorizer`.
private(set) var transactionEffect: TransactionEffect?
/// The effects on the database (reported by `sqlite3_set_authorizer`).
@@ -925,7 +925,7 @@ func withBindings<T>(
/// - `@AAAA` (e.g. `@name`): named argument
/// - `$AAAA` (e.g. `$name`): named argument
///
/// All forms are supported, but GRDB does not allow you to distinguish between
/// All forms are supported, but GRDB does not allow you to distinguish between
/// the `:AAAA`, `@AAAA`, and `$AAAA` syntaxes. You are encouraged to write
/// named arguments with a colon prefix: `:name`.
///
+1 -1
View File
@@ -19,7 +19,7 @@ extension NSNumber: DatabaseValueConvertible {
/// Otherwise, returns an INTEGER or REAL database value, according to the
/// value stored in the `NSNumber`.
public var databaseValue: DatabaseValue {
// Don't lose precision: store integers that fits in Int64 as Int64
// Don't lose precision: store integers that fit in Int64 as Int64
if let decimal = self as? NSDecimalNumber,
decimal == decimal.rounding(accordingToBehavior: integerRoundingBehavior), // integer
decimal.compare(NSDecimalNumber(value: Int64.max)) != .orderedDescending, // decimal <= Int64.max
+11 -11
View File
@@ -356,7 +356,7 @@ class DatabaseObservationBroker {
statementObservations = []
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Reset transactionCompletion before databaseDidRollback eventually
// Reset transactionCompletion before databaseDidRollback possibly
// executes other statements.
let transactionCompletion = self.transactionCompletion
self.transactionCompletion = .none
@@ -433,7 +433,7 @@ class DatabaseObservationBroker {
}
// Reset transactionCompletion before databaseDidCommit or
// databaseDidRollback eventually execute other statements.
// databaseDidRollback possibly execute other statements.
let transactionCompletion = self.transactionCompletion
self.transactionCompletion = .none
@@ -733,7 +733,7 @@ class DatabaseObservationBroker {
#endif
}
/// The various SQLite transactions completions, as reported by the
/// The various SQLite transaction completions, as reported by the
/// `sqlite3_commit_hook` and `sqlite3_rollback_hook` callbacks.
fileprivate enum TransactionCompletion {
/// Transaction state is unchanged.
@@ -851,7 +851,7 @@ public protocol TransactionObserver: AnyObject {
/// not automatically detected. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
/// and ``Database/notifyChanges(in:)`` for more information.
///
/// The exact nature of changes is unknown, but they comply to the
/// The exact nature of changes is unknown, but they comply with the
/// ``observes(eventsOfKind:)`` test.
func databaseDidChange()
@@ -884,7 +884,7 @@ public protocol TransactionObserver: AnyObject {
///
/// - precondition: This method must not access the observed writer
/// database connection.
/// - throws: The eventual error that rollbacks pending changes.
/// - throws: The error that rolls back pending changes.
func databaseWillCommit() throws
/// Called when a transaction has been committed on disk.
@@ -996,7 +996,7 @@ final class TransactionObservation {
let extent: Database.TransactionObservationExtent
/// A disabled observation is not interested in individual database changes.
/// It is still interested in transactions commits & rollbacks.
/// It is still interested in transaction commits & rollbacks.
var isEnabled = true
private weak var weakObserver: (any TransactionObserver)?
@@ -1052,8 +1052,8 @@ final class TransactionObservation {
return nil
case 1:
// We'll execute a simple statement without any side effect.
// Eventual database events will thus all have the same kind. All
// detabase events can be notified to interested observations.
// All database events will thus have the same kind. All
// database events can be notified to interested observations.
//
// For example, if one observes all deletions in the table T, then
// all individual deletions of DELETE FROM T are notified:
@@ -1068,7 +1068,7 @@ final class TransactionObservation {
trackingEvents: .all)
default:
// We'll execute a complex statement with side effects performed by
// an SQL trigger or a foreign key action. Eventual database events
// an SQL trigger or a foreign key action. Any database events
// may not all have the same kind: we need to filter them before
// notifying interested observations.
//
@@ -1119,7 +1119,7 @@ final class TransactionObservation {
if let observer = self.observer {
// Observer must not get any further notification.
// So we "forget" the observer before its `databaseDidCommit`
// implementation eventually triggers another database change.
// implementation possibly triggers another database change.
assert(weakObserver == nil, "expected observer to be stored in strongObserver")
strongObserver = nil
observer.databaseDidCommit(db)
@@ -1135,7 +1135,7 @@ final class TransactionObservation {
if let observer = self.observer {
// Observer must not get any further notification.
// So we "forget" the observer before its `databaseDidRollback`
// implementation eventually triggers another database change.
// implementation possibly triggers another database change.
assert(weakObserver == nil, "expected observer to be stored in strongObserver")
strongObserver = nil
observer.databaseDidRollback(db)
+2 -2
View File
@@ -29,7 +29,7 @@ Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the
#### Rule 2: Mind your transactions
Database operations that are grouped in a transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions guarantee a stable and immutable view of the database, and do not see changes performed by eventual concurrent writes.
Database operations that are grouped in a transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions guarantee a stable and immutable view of the database, and do not see changes performed by concurrent writes.
In other words, transactions are the one and single tool that helps you enforce and rely on the invariants of your database (such as "all authors must have at least one book").
@@ -168,7 +168,7 @@ Concurrent reads can not see partial database updates (even reads performed by o
**All reads are wrapped in a transaction.**
An isolated read sees a stable and immutable state of the database, and does not see changes performed by eventual concurrent writes (even writes performed by other processes). See [Isolation In SQLite](https://www.sqlite.org/isolation.html) for more information.
An isolated read sees a stable and immutable state of the database, and does not see changes performed by concurrent writes (even writes performed by other processes). See [Isolation In SQLite](https://www.sqlite.org/isolation.html) for more information.
#### Forbidden Writes
@@ -41,7 +41,7 @@ try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... }
Reference: ``TableOptions``
**Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`, `any`, and `jsonText`) - see [SQLite data types](https://www.sqlite.org/datatype3.html) and <doc:JSON>:
**Add regular columns** with their name and optional type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`, `any`, and `jsonText`) - see [SQLite data types](https://www.sqlite.org/datatype3.html) and <doc:JSON>:
```swift
// CREATE TABLE player (
+1 -1
View File
@@ -224,7 +224,7 @@ do {
Post ``Database/resumeNotification`` in order to resume suspended databases. You can safely post this notification when the app comes back to foreground.
In applications that use the background modes supported by iOS, post `resumeNotification` method from each and every background mode callback that may use the database, and don't forget to post `suspendNotification` again before the app turns suspended.
In applications that use the background modes supported by iOS, post `resumeNotification` from each and every background mode callback that may use the database, and don't forget to post `suspendNotification` again before the app turns suspended.
## How to perform cross-process database observation
@@ -4,7 +4,7 @@
## Overview
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign key actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
See <doc:GRDB/DatabaseRegionObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
@@ -91,7 +91,7 @@ protocol DatabaseValueConvertible {
import Tagged
struct Player: Identifiable {
// Thanks to Tagged, Player.ID can not be mismatched with Team.ID or
// Thanks to Tagged, Player.ID can not be confused with Team.ID or
// Award.ID, even though they all wrap strings.
typealias ID = Tagged<Player, String>
var id: ID
@@ -17,7 +17,7 @@ let observer = MyObserver()
dbQueue.add(transactionObserver: observer)
```
By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See <doc:TransactionObserver#Observation-Extent> for more options.
By default, the database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See <doc:TransactionObserver#Observation-Extent> for more options.
## Database Changes And Transactions
@@ -76,7 +76,7 @@ try dbQueue.inTransaction { db in
}
```
Eventual errors thrown from `databaseWillCommit` are exposed to the application code:
Errors thrown from `databaseWillCommit` are exposed to the application code:
```swift
do {
@@ -162,7 +162,7 @@ dbQueue.inDatabase { db in
- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, the observer is notified of all changes and transactions.
- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` callback is called. Hereafter the observer won't get any further notification.
- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` callback is called. After that, the observer won't get any further notification.
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
@@ -4,7 +4,7 @@
## Overview
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign key actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
@@ -72,13 +72,13 @@ See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the li
## ValueObservation Behavior
`ValueObservation` notifies an initial value before the eventual changes.
`ValueObservation` notifies an initial value before subsequent changes.
`ValueObservation` only notifies changes committed to disk.
By default, `ValueObservation` notifies a fresh value whenever any component of its fetched value is modified (any fetched column, row, etc.). This can be configured: see <doc:ValueObservation#Specifying-the-Tracked-Region>.
By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main actor, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, on the main actor, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
By default, `ValueObservation` fetches a fresh value immediately after a change is committed in the database. In particular, modifying the database on the main thread triggers a fetch on the main thread as well. This behavior can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
@@ -98,7 +98,7 @@ The database observation stops when the cancellable returned by the `start` meth
## ValueObservation Scheduling
By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main actor, asynchronously:
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, on the main actor, asynchronously:
```swift
// The default scheduling
+2 -2
View File
@@ -76,7 +76,7 @@ try dbQueue.read { db in
**Each migration runs in a separate transaction.** Should one throw an error, its transaction is rolled back, subsequent migrations do not run, and the error is eventually thrown by ``DatabaseMigrator/migrate(_:)``.
**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). See <doc:Migrations#Foreign-Key-Checks> below for more information.
**Migrations run with deferred foreign key checks.** This means that foreign key violations are only checked at the end of the migration (and they make the migration fail). See <doc:Migrations#Foreign-Key-Checks> below for more information.
**The memory of applied migrations is stored in the database itself** (in a reserved table).
@@ -234,7 +234,7 @@ When you register a migration with `.immediate` foreign key checks, the migratio
migrator.registerMigration("Fast migration", foreignKeyChecks: .immediate) { db in ... }
```
Such a migration is faster, and it still guarantees database integrity. But it must only execute schema alterations directly supported by SQLite. Migrations that recreate tables as described in <doc:Migrations#Defining-the-Database-Schema-from-a-Migration> **must not** run with immediate foreign keys checks. You'll need to use the second mitigation technique:
Such a migration is faster, and it still guarantees database integrity. But it must only execute schema alterations directly supported by SQLite. Migrations that recreate tables as described in <doc:Migrations#Defining-the-Database-Schema-from-a-Migration> **must not** run with immediate foreign key checks. You'll need to use the second mitigation technique:
**Your second mitigation technique is to disable deferred foreign key checks.**
@@ -172,7 +172,7 @@ let books = try dbQueue.read { db in
### Record Types Hide Intimate Database Details
In the previous sample codes, the `Book` and `Author` structs have one property per database column, and their types are natively supported by SQLite (`String`, `Int`, etc.)
In the previous code samples, the `Book` and `Author` structs have one property per database column, and their types are natively supported by SQLite (`String`, `Int`, etc.)
But it happens that raw database column names, or raw column types, are not a very good fit for the application.
@@ -515,7 +515,7 @@ let authorships: [Authorship] = try dbQueue.read { db in
}
```
In the above sample codes, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `LiteraryCareer`, and `Authorship`.
In the above code samples, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `LiteraryCareer`, and `Authorship`.
Those record types conform to both [`Decodable`] and ``FetchableRecord``, so that they can feed from database rows. They do not provide any persistence methods, though. **All database writes are performed from persistable record instances** (of type `Author` or `Book`).
+3 -3
View File
@@ -16,13 +16,13 @@ We will also aim at providing a default value for a given configuration, even wh
## The Single-Row Table
As always with SQLite, everything starts at the level of the database schema. When we put the database engine on our side, we have to write less code, and this helps ship less bugs.
As always with SQLite, everything starts at the level of the database schema. When we put the database engine on our side, we have to write less code, and this helps ship fewer bugs.
We want to instruct SQLite that our table must never contain more than one row. We will never have to wonder what to do if we were unlucky enough to find two rows with conflicting values in this table.
SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, or it contains one row.
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app deal with updates in the <doc:SingleRowTables#The-Single-Row-Record> section below. Right now, we instruct SQLite to just replace the eventual existing row in case of conflicting inserts.
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app deal with updates in the <doc:SingleRowTables#The-Single-Row-Record> section below. Right now, we instruct SQLite to just replace any existing row in case of conflicting inserts.
```swift
migrator.registerMigration("appConfiguration") { db in
@@ -48,7 +48,7 @@ Note how the database table is defined in a migration. That's because most apps
We have defined a `storedFlag` column that can be NULL. That may be surprising, because optional booleans are usually a bad idea! But we can deal with this NULL at runtime, and nullable columns have a few advantages:
- NULL means that the application user had not made a choice yet. When `storedFlag` is NULL, the app can use a default value, such as `true`.
- As application evolves, application will need to add new configuration columns. It is not always possible to provide a sensible default value for these new columns, at the moment the table is modified. On the other side, it is generally possible to deal with those NULL values at runtime.
- As the application evolves, it will need to add new configuration columns. It is not always possible to provide a sensible default value for these new columns, at the moment the table is modified. On the other hand, it is generally possible to deal with those NULL values at runtime.
Despite those arguments, some apps absolutely require a value. In this case, don't weaken the application logic and make sure the database can't store a NULL value:
+4 -4
View File
@@ -35,7 +35,7 @@ for try await players in observation.values(in: writer) {
`DatabaseQueue` serializes all database accesses, when `DatabasePool` allows parallel reads and writes. The common ``DatabaseWriter`` protocol provides the [SQLite isolation guarantees](https://www.sqlite.org/isolation.html) that abstract away the differences between the two connection types, without sacrificing data integrity. See the <doc:Concurrency> guide for more information.
All safety guarantees of Swift 6 are enforced during database accesses. They are controlled by the language mode and level of concurrency checkings used by your application, as described in [Migrating to Swift 6] on swift.org.
All safety guarantees of Swift 6 are enforced during database accesses. They are controlled by the language mode and level of concurrency checking used by your application, as described in [Migrating to Swift 6] on swift.org.
The following sections describe, with more details, how GRDB interacts with Swift Concurrency.
@@ -83,7 +83,7 @@ This language feature is not enabled by default, because it can potentially [aff
### Non-Sendable Configuration of Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checking, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
```swift
extension Player: FetchableRecord, PersistableRecord {
@@ -114,7 +114,7 @@ extension Player: FetchableRecord, PersistableRecord {
### Non-Sendable Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when the application reads, writes, or observes a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type.
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checking, the compiler emits an error or a warning when the application reads, writes, or observes a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type.
By default, Swift classes are not Sendable. They are not thread-safe. With GRDB, record classes will typically trigger compiler diagnostics:
@@ -162,7 +162,7 @@ struct Player: Codable, Identifiable {
extension Player: FetchableRecord, PersistableRecord { }
```
You do not need to perform this refactoring right away: you can compile your application in the Swift 5 language mode, with minimal concurrency checkings. Take your time, and only when your application is ready, enable strict concurrency checkings or the Swift 6 language mode.
You do not need to perform this refactoring right away: you can compile your application in the Swift 5 language mode, with minimal concurrency checking. Take your time, and only when your application is ready, enable strict concurrency checking or the Swift 6 language mode.
#### FAQ: My application defines record classes, because…
+3 -3
View File
@@ -142,7 +142,7 @@ try dbQueue.writeWithoutTransaction { db in
}
```
Make sure all transactions opened from a database access are committed or rolled back from that same database access, because it is a programmer error to leave an opened transaction:
Make sure all transactions opened from a database access are committed or rolled back from that same database access, because it is a programmer error to leave an open transaction:
```swift
// fatal error: A transaction has been left
@@ -155,7 +155,7 @@ try dbQueue.writeWithoutTransaction { db in
In particular, since commits may throw an error, make sure you perform a rollback when a commit fails.
This restriction can be left with the ``Configuration/allowsUnsafeTransactions`` configuration flag.
This restriction can be lifted with the ``Configuration/allowsUnsafeTransactions`` configuration flag.
It is possible to ask if a transaction is currently opened:
@@ -196,7 +196,7 @@ try dbQueue.write { db in
If an error is thrown from the savepoint block, the savepoint is rolled back and the error is rethrown by the `inSavepoint` method. If the savepoint closure returns `.rollback` instead of `.commit`, the savepoint is also rolled back, 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:
**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if none 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
+1 -1
View File
@@ -117,7 +117,7 @@ try dbQueue.write { db in
## Specifying the primary key of a view
SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the eventual primary key.
SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the primary key, if any.
To instruct GRDB about the primary key, define a **schema source**, a type that conforms to ``DatabaseSchemaSource``. In this sample code, the schema only contains the "captain" view, so our schema source does not need to be very complicated. Check the documentation of the protocol for more detailed instructions:
+1 -1
View File
@@ -138,7 +138,7 @@ public struct FTS5TokenizerDescriptor: Sendable {
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#porter_tokenizer>
///
/// - parameter base: An eventual wrapping tokenizer which replaces the
/// - parameter base: An optional wrapping tokenizer which replaces the
/// default unicode61() base tokenizer.
public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor {
if let base {
+1 -1
View File
@@ -343,7 +343,7 @@ extension Database {
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
///
/// - parameter value: The tested value.
/// - parameter options: See eventual second argument of the
/// - parameter options: See the optional second argument of the
/// `JSON_VALID` function. See <https://www.sqlite.org/json1.html#the_json_valid_function>.
public static func jsonIsValid(
_ value: some SQLExpressible,
@@ -1,5 +1,5 @@
/// The `BelongsToAssociation` sets up a one-to-one connection from a record
/// type to another record type, such as each instance of the declaring record
/// type to another record type, such that each instance of the declaring record
/// "belongs to" an instance of the other record.
///
/// For example, if your application includes authors and books, and each book
@@ -1,5 +1,5 @@
/// The `HasManyAssociation` indicates a one-to-many connection between two
/// record types, such as each instance of the declaring record "has many"
/// record types, such that each instance of the declaring record "has many"
/// instances of the other record.
///
/// For example, if your application includes authors and books, and each author
@@ -1,5 +1,5 @@
/// The `HasOneAssociation` indicates a one-to-one connection between two
/// record types, such as each instance of the declaring record "has one"
/// record types, such that each instance of the declaring record "has one"
/// instance of the other record.
///
/// For example, if your application has one database table for countries, and
@@ -1576,10 +1576,10 @@ extension JoinableRequest {
_including(all: association._sqlAssociation)
}
/// Returns a request that fetches the eventual record associated with each
/// Returns a request that fetches the optional record associated with each
/// record of this request.
///
/// For example, we can fetch books along with their eventual author:
/// For example, we can fetch books along with their optional author:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable { }
@@ -1628,7 +1628,7 @@ extension JoinableRequest {
}
/// Returns a request that joins each record of this request to its
/// eventual associated record.
/// optional associated record.
public func joining<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
_joining(optional: association._sqlAssociation)
}
@@ -1661,7 +1661,7 @@ extension JoinableRequest {
}
extension JoinableRequest where Self: SelectionRequest {
/// Appends the columns of the eventual associated record to the
/// Appends the columns of the optional associated record to the
/// selected columns.
///
/// For example:
+6 -6
View File
@@ -192,7 +192,7 @@ public struct SQLExpression: Sendable {
/// An expression that picks the fastest available primary key.
///
/// It crashes for WITHOUT ROWID table with a multi-columns primary key.
/// It crashes for WITHOUT ROWID tables with a multi-column primary key.
/// Future versions of GRDB may use [row values](https://www.sqlite.org/rowvalue.html).
///
/// id
@@ -1141,20 +1141,20 @@ extension SQLExpression {
// MARK: Deferred
// TODO: replace with something that can work for WITHOUT ROWID table with a multi-columns primary key.
// TODO: replace with something that can work for WITHOUT ROWID tables with a multi-column primary key.
/// An expression that picks the fastest available primary key.
///
/// It crashes for WITHOUT ROWID table with a multi-columns primary key.
/// It crashes for WITHOUT ROWID tables with a multi-column primary key.
///
/// id
/// rowid
/// code
static let fastPrimaryKey = SQLExpression(impl: .fastPrimaryKey)
// TODO: replace with something that can work for WITHOUT ROWID table with a multi-columns primary key.
// TODO: replace with something that can work for WITHOUT ROWID tables with a multi-column primary key.
/// A qualified "fast primary key" (see `SQLExpression.fastPrimaryKey`).
///
/// It crashes for WITHOUT ROWID table with a multi-columns primary key.
/// It crashes for WITHOUT ROWID tables with a multi-column primary key.
///
/// player.id
/// document.rowid
@@ -1464,7 +1464,7 @@ extension SQLExpression {
case let .qualifiedFastPrimaryKey(alias):
let primaryKey = try context.db.primaryKey(alias.tableName)
guard let column = primaryKey.fastPrimaryKeyColumn else {
fatalError("Not implemented for WITHOUT ROWID table with a multi-columns primary key")
fatalError("Not implemented for WITHOUT ROWID tables with a multi-column primary key")
}
return try SQLExpression
.qualifiedColumn(column, alias)
@@ -1,7 +1,7 @@
/// SQLForeignKeyRequest looks for the foreign keys associations need to
/// join tables.
///
/// Columns mapping come from foreign keys, when they exist in the
/// Column mappings come from foreign keys, when they exist in the
/// database schema.
///
/// When the schema does not define any foreign key, we can still infer complete
+1 -1
View File
@@ -956,7 +956,7 @@ extension JoinMapping {
//
// Since a single NULL value satisfies the foreign key constraint
// without requiring a matching matching parent row, below we'll ignore
// left rows (children) that attempt at matching on NULL.
// left rows (children) that attempt to match on NULL.
if mappings.count == 1 {
// Join on a single right column.
// table.a IN (1, 2, 3, ...)
+10 -10
View File
@@ -1188,7 +1188,7 @@ extension Table {
/// - destination: The record type at the other side of the association.
/// - key: The association key. By default, it
/// is `Destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func belongsTo<Destination>(
@@ -1213,7 +1213,7 @@ extension Table {
/// - destination: The record type at the other side of the association.
/// - key: The association key. By default, it
/// is `Destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func hasMany<Destination>(
@@ -1238,7 +1238,7 @@ extension Table {
/// - destination: The record type at the other side of the association.
/// - key: The association key. By default, it
/// is `Destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func hasOne<Destination>(
@@ -1267,7 +1267,7 @@ extension Table {
/// - destination: The table at the other side of the association.
/// - key: The association key. By default, it
/// is `destination.tableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func belongsTo<Destination>(
@@ -1291,7 +1291,7 @@ extension Table {
/// - destination: The table at the other side of the association.
/// - key: The association key. By default, it
/// is `destination.tableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func hasMany<Destination>(
@@ -1315,7 +1315,7 @@ extension Table {
/// - destination: The table at the other side of the association.
/// - key: The association key. By default, it
/// is `destination.tableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func hasOne<Destination>(
@@ -1416,7 +1416,7 @@ extension Table {
/// - pivot: An association from Self to the intermediate type.
/// - target: A target association from the intermediate type to the
/// destination type.
/// - key: An eventual decoding key for the association. By default, it
/// - key: An optional decoding key for the association. By default, it
/// is the same key as the target.
public func hasOne<Pivot, Target>(
_ destination: Target.RowDecoder.Type,
@@ -1454,7 +1454,7 @@ extension Table {
all().including(all: association)
}
/// Returns a request that fetches the eventual row associated with each
/// Returns a request that fetches the optional row associated with each
/// row of this request.
///
/// See the ``TableRecord`` method ``TableRecord/including(optional:)``
@@ -1479,7 +1479,7 @@ extension Table {
}
/// Returns a request that joins each row of this request to its
/// eventual associated row.
/// optional associated row.
///
/// See the ``TableRecord`` method ``TableRecord/joining(optional:)``
/// for more information.
@@ -1502,7 +1502,7 @@ extension Table {
all().joining(required: association)
}
/// Returns a request with the columns of the eventual associated row
/// Returns a request with the columns of the optional associated row
/// appended to the table columns.
///
/// See the ``TableRecord`` method ``TableRecord/annotated(withOptional:)``
@@ -157,7 +157,7 @@ final class SQLGenerationContext {
/// by `tableName`.
///
/// - parameter tableName: The table name.
/// - parameter excludedColumns: The eventual set of excluded columns.
/// - parameter excludedColumns: The optional set of excluded columns.
func columnCount(
in tableName: String,
excluding excludedColumns: Set<CaseInsensitiveIdentifier>
@@ -542,7 +542,7 @@ struct SQLQueryGenerator: Refinable {
/// expressions, etc, are qualified with table aliases.
///
/// All those aliases let us disambiguate tables at the SQL level, and
/// prefix columns names. For example, the following request...
/// prefix column names. For example, the following request...
///
/// Book.filter(Column("kind") == Book.Kind.novel)
/// .including(optional: Book.author)
@@ -98,7 +98,7 @@ extension Database {
///
/// ### Add columns
///
/// Add columns with their name and eventual type (`text`, `integer`,
/// Add columns with their name and optional type (`text`, `integer`,
/// `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`
/// and `any`) - see ``Database/ColumnType``:
///
@@ -240,7 +240,7 @@ public final class TableDefinition {
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#tablecoldef>
///
/// - parameter name: the column name.
/// - parameter type: the eventual column type.
/// - parameter type: the optional column type.
/// - returns: A ``ColumnDefinition`` that allows you to refine the
/// column definition.
@discardableResult
@@ -15,7 +15,7 @@
///
/// ## Topics
///
/// ### Configuration Virtual Table Creation
/// ### Configuring Virtual Table Creation
///
/// - ``VirtualTableConfiguration``
public protocol VirtualTableModule {
@@ -56,7 +56,7 @@ extension TableRecord {
/// - destination: The record type at the other side of the association.
/// - key: The association key. By default, it
/// is `Destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public static func belongsTo<Destination>(
@@ -127,7 +127,7 @@ extension TableRecord {
/// - destination: The record type at the other side of the association.
/// - key: The association key. By default, it
/// is `Destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public static func hasMany<Destination>(
@@ -158,7 +158,7 @@ extension TableRecord {
/// The association lets you define requests that involve both the source
/// and the destination type.
///
/// For example, we can fetch all countries with their eventual demographics:
/// For example, we can fetch all countries with their optional demographics:
///
/// ```swift
/// struct CountryInfo: FetchableRecord, Decodable {
@@ -203,7 +203,7 @@ extension TableRecord {
/// - destination: The record type at the other side of the association.
/// - key: The association key. By default, it
/// is `Destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public static func hasOne<Destination>(
@@ -232,7 +232,7 @@ extension TableRecord {
/// - destination: The table at the other side of the association.
/// - key: The association key. By default, it
/// is `destination.tableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public static func belongsTo<Destination>(
@@ -256,7 +256,7 @@ extension TableRecord {
/// - destination: The table at the other side of the association.
/// - key: The association key. By default, it
/// is `destination.tableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public static func hasMany<Destination>(
@@ -280,7 +280,7 @@ extension TableRecord {
/// - destination: The table at the other side of the association.
/// - key: The association key. By default, it
/// is `destination.tableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// - foreignKey: An optional foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public static func hasOne<Destination>(
@@ -586,7 +586,7 @@ extension TableRecord where Self: EncodableRecord {
case let .foreignKey(foreignKey):
// Build the sendable persistence container before building the
// request, and catch the eventual error in a Result, so that it
// request, and catch any error in a Result, so that it
// is thrown later, when the request is executed. This allows
// this method to not throw:
//
@@ -645,10 +645,10 @@ extension TableRecord {
all().including(all: association)
}
/// Returns a request that fetches the eventual record associated with each
/// Returns a request that fetches the optional record associated with each
/// record of this request.
///
/// For example, we can fetch books along with their eventual author:
/// For example, we can fetch books along with their optional author:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord, Decodable { }
@@ -703,7 +703,7 @@ extension TableRecord {
}
/// Returns a request that joins each record of this request to its
/// eventual associated record.
/// optional associated record.
public static func joining<A: Association>(optional association: A)
-> QueryInterfaceRequest<Self>
where A.OriginRowDecoder == Self
@@ -740,7 +740,7 @@ extension TableRecord {
all().joining(required: association)
}
/// Returns a request with the columns of the eventual associated record
/// Returns a request with the columns of the optional associated record
/// appended to the record selection.
///
/// The record selection is determined by
+3 -3
View File
@@ -303,7 +303,7 @@ extension EncodableRecord {
/// share the same value. Values are the database values from the
/// `other` record.
///
/// Note that the `other` record does not have to have the same type of the
/// Note that the `other` record does not have to have the same type as the
/// receiver record. When the two records don't define the same set of
/// columns in their <doc:/documentation/GRDB/EncodableRecord/encode(to:)-k9pf>
/// method, only the columns defined by the receiver are considered.
@@ -321,7 +321,7 @@ extension EncodableRecord {
/// returns a dictionary of changed values.
///
/// The keys of the dictionary are the changed column names. Values are
/// the database values from the initial version record.
/// the database values from the initial version of the record.
///
/// For example:
///
@@ -485,7 +485,7 @@ public enum DatabaseDataEncodingStrategy: Sendable {
/// Encodes `Data` columns as SQL text. Data must contain valid UTF8 bytes.
case text
/// Encodes `Data` column as the result of the user-provided function.
/// Encodes `Data` columns as the result of the user-provided function.
case custom(@Sendable (Data) -> (any DatabaseValueConvertible)?)
func encode(_ data: Data) throws -> DatabaseValue {
+1 -1
View File
@@ -1066,7 +1066,7 @@ public enum DatabaseDateDecodingStrategy: @unchecked Sendable {
/// midnight UTC on 1 January 1970
case millisecondsSince1970
/// Decodes dates according to the ISO 8601 standards
/// Decodes dates according to the ISO 8601 standard
case iso8601
/// Decodes a String, according to the provided formatter
@@ -379,7 +379,7 @@ extension MutablePersistableRecord {
fetch: (Statement) throws -> T)
throws -> (PersistenceSuccess, T)
{
// Attempt at updating if the record has a primary key
// Attempt to update if the record has a primary key
if let key = try primaryKey(db) {
let databaseTableName = type(of: self).databaseTableName
do {
@@ -77,7 +77,7 @@ extension MutablePersistableRecord {
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target are the columns of the uniqueness constraint
/// The conflict target consists of the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraints are considered.
///
@@ -262,7 +262,7 @@ extension MutablePersistableRecord {
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target are the columns of the uniqueness constraint
/// The conflict target consists of the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraints are considered.
///
+5 -5
View File
@@ -148,7 +148,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
///
/// If you provide a custom implementation of this method, you must call
/// the `insert` parameter at some point in your implementation, and you
/// must rethrow its eventual error.
/// must rethrow any error.
///
/// For example:
///
@@ -207,7 +207,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
///
/// If you provide a custom implementation of this method, you must call
/// the `update` parameter at some point in your implementation, and you
/// must rethrow its eventual error.
/// must rethrow any error.
///
/// For example:
///
@@ -246,7 +246,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
///
/// If you provide a custom implementation of this method, you must call
/// the `save` parameter at some point in your implementation, and you
/// must rethrow its eventual error.
/// must rethrow any error.
///
/// For example:
///
@@ -285,7 +285,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
///
/// If you provide a custom implementation of this method, you must call
/// the `delete` parameter at some point in your implementation, and you
/// must rethrow its eventual error.
/// must rethrow any error.
///
/// For example:
///
@@ -410,7 +410,7 @@ public struct InsertionSuccess {
/// To learn about rowids, see <https://www.sqlite.org/lang_createtable.html#rowids_and_the_integer_primary_key>.
public var rowID: Int64
/// The name of the eventual INTEGER PRIMARY KEY column.
/// The name of the INTEGER PRIMARY KEY column, if any.
public var rowIDColumn: String?
// Used by the Record class in order to manage its `hasDatabaseChanges` flag.
+1 -1
View File
@@ -258,7 +258,7 @@ extension PersistableRecord {
fetch: (Statement) throws -> T)
throws -> (PersistenceSuccess, T)
{
// Attempt at updating if the record has a primary key
// Attempt to update if the record has a primary key
if let key = try primaryKey(db) {
do {
let databaseTableName = type(of: self).databaseTableName
+2 -2
View File
@@ -77,7 +77,7 @@ extension PersistableRecord {
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target are the columns of the uniqueness constraint
/// The conflict target consists of the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraints are considered.
///
@@ -262,7 +262,7 @@ extension PersistableRecord {
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target are the columns of the uniqueness constraint
/// The conflict target consists of the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraints are considered.
///
+1 -1
View File
@@ -420,7 +420,7 @@ open class Record {
/// - returns: Whether the record had changes and was updated.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` is thrown
/// if the primary key does not match any row in the database and record
/// if the primary key does not match any row in the database and the record
/// could not be updated.
@discardableResult
public final func updateChanges(_ db: Database) throws -> Bool {
+1 -1
View File
@@ -11,7 +11,7 @@ import Foundation
/// that it starts producing its value on demand, **synchronously**, and that
/// it produces its value on promise completion, **synchronously**.
///
/// Both two extra scheduling guarantees are used by GRDB in order to be
/// Both extra scheduling guarantees are used by GRDB in order to be
/// able to spawn concurrent database reads right from the database writer
/// queue, and fulfill GRDB preconditions.
///
+3 -3
View File
@@ -102,7 +102,7 @@ extension Sequence {
}
/// Makes sure the `finally` function is executed even if `execute` throws, and
/// rethrows the eventual first thrown error.
/// rethrows the first thrown error, if any.
///
/// Usage:
///
@@ -210,8 +210,8 @@ extension NSLocking {
// return try block()
// }
/// Performs the side effect outside of the synchronized block. This allows
/// avoiding deadlocks, when the side effect feedbacks.
/// Performs the side effect outside of the synchronized block. This avoids
/// deadlocks, when the side effect triggers a reentrant call.
func synchronized(
_ message: @autoclosure () -> String = #function,
_ block: (inout (() -> Void)?) -> Void)
@@ -284,7 +284,7 @@ extension ValueConcurrentObserver {
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
// Start from a read access. The whole point of using a DatabasePool
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
// without having to wait for a possible long-running write
// transaction to complete.
//
// We perform the initial read from a long-lived WAL snapshot
@@ -341,7 +341,7 @@ extension ValueConcurrentObserver {
private func asyncStart(from databaseAccess: DatabaseAccess) {
// Start from a read access. The whole point of using a DatabasePool
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
// without having to wait for a possible long-running write
// transaction to complete.
//
// We perform the initial read from a long-lived WAL snapshot
@@ -550,7 +550,7 @@ extension ValueConcurrentObserver {
private func syncStartWithoutWALSnapshot(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
// Start from a read access. The whole point of using a DatabasePool
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
// without having to wait for a possible long-running write
// transaction to complete.
let fetchedValue: Reducer.Fetcher.Value
let initialRegion: DatabaseRegion
@@ -591,7 +591,7 @@ extension ValueConcurrentObserver {
private func asyncStartWithoutWALSnapshot(from databaseAccess: DatabaseAccess) {
// Start from a read access. The whole point of using a DatabasePool
// for observing the database is to be able to fetch the initial value
// without having to wait for an eventual long-running write
// without having to wait for a possible long-running write
// transaction to complete.
databaseAccess.dbPool.asyncRead { dbResult in
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
@@ -23,7 +23,7 @@ public protocol _ValueReducer: GRDBSendableMetatype {
/// on the state of the reducer.
func _makeFetcher() -> Fetcher
/// Transforms a fetched value into an eventual observed value. Returns nil
/// Transforms a fetched value into an optional observed value. Returns nil
/// when observer should not be notified.
///
/// This method runs in some unspecified dispatch queue.
@@ -58,7 +58,7 @@ extension ValueObservationMainActorScheduler {
// MARK: - AsyncValueObservationScheduler
/// A scheduler that asynchronously notifies fresh value of a `DispatchQueue`.
/// A scheduler that asynchronously notifies fresh values on a `DispatchQueue`.
public struct AsyncValueObservationScheduler: ValueObservationScheduler {
var queue: DispatchQueue
@@ -74,7 +74,7 @@ public struct AsyncValueObservationScheduler: ValueObservationScheduler {
}
extension ValueObservationScheduler where Self == AsyncValueObservationScheduler {
/// A scheduler that asynchronously notifies fresh value of the
/// A scheduler that asynchronously notifies fresh values on the
/// given `DispatchQueue`.
///
/// For example:
+17 -17
View File
@@ -353,7 +353,7 @@ See [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) for the installa
The [Swift Package Manager](https://swift.org/package-manager/) automates the distribution of Swift code. To use GRDB with SPM, add a dependency to `https://github.com/groue/GRDB.swift.git`
GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in doubt, prefer `GRDB`. The `GRDB-dynamic` library can reveal useful if you are going to link it with multiple targets within your app and only wish to link to a shared, dynamic framework once. See [How to link a Swift Package as dynamic](https://forums.swift.org/t/how-to-link-a-swift-package-as-dynamic/32062) for more information.
GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in doubt, prefer `GRDB`. The `GRDB-dynamic` library can prove useful if you are going to link it with multiple targets within your app and only wish to link to a shared, dynamic framework once. See [How to link a Swift Package as dynamic](https://forums.swift.org/t/how-to-link-a-swift-package-as-dynamic/32062) for more information.
> **Note**: Linux support is provided by contributors. It is not automatically tested, and not officially maintained. If you notice a build or runtime failure on Linux, please open a pull request with the necessary fix, thank you!
@@ -480,7 +480,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [`StatementArguments`] for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statement arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported argument types (Bool, Int, String, Date, Swift enums, etc.), and [`StatementArguments`] for a detailed documentation of SQLite arguments.
You can also embed query arguments right into your SQL queries, with [`execute(literal:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/execute(literal:)), as in the example below. See [SQL Interpolation] for more details.
@@ -800,7 +800,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [`StatementArguments`] for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported argument types (Bool, Int, String, Date, Swift enums, etc.), and [`StatementArguments`] for a detailed documentation of SQLite arguments.
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
@@ -2175,7 +2175,7 @@ For more information about batch updates, see [Update Requests](#update-requests
**All primary keys are supported**, including composite primary keys that span several columns, and the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html).
**To customize persistence methods**, you provide [Persistence Callbacks], described below. Do not attempt at overriding the ready-made persistence methods.
**To customize persistence methods**, you provide [Persistence Callbacks], described below. Do not attempt to override the ready-made persistence methods.
### Upsert
@@ -2219,7 +2219,7 @@ For more information about batch updates, see [Update Requests](#update-requests
If empty (the default), all uniqueness constraints are considered.
- `doUpdate`: a closure that returns columns assignments to perform in case of conflict. Depending on the `updating` parameter, other columns are overwritten with the inserted values, or not.
- `doUpdate`: a closure that returns column assignments to perform in case of conflict. Depending on the `updating` parameter, other columns are overwritten with the inserted values, or not.
By default, all inserted columns but the primary key and the conflict target are overwritten.
@@ -3530,7 +3530,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.order(\.score).order(\.name)
```
- [`reversed()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/orderedrequest/reversed()) reverses the eventual orderings.
- [`reversed()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/orderedrequest/reversed()) reverses the orderings, if any.
```swift
// SELECT * FROM player ORDER BY score ASC, name DESC
@@ -3609,7 +3609,7 @@ You can refine requests by chaining those methods:
Player.order(\.name).filter { $0.email != nil }
```
The `select`, `order`, `group`, and `limit` methods ignore and replace previously applied selection, orderings, grouping, and limits. On the opposite, `filter`, `matching`, and `having` methods extend the query:
The `select`, `order`, `group`, and `limit` methods ignore and replace previously applied selection, orderings, grouping, and limits. Conversely, `filter`, `matching`, and `having` methods extend the query:
```swift
Player // SELECT * FROM player
@@ -3623,7 +3623,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
Raw SQL snippets are also accepted, with optional [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -4523,7 +4523,7 @@ try request.fetchOne(db) // Player?
try request.fetchCount(db) // Int
```
**When the query interface can not generate the SQL you need**, you can still fallback to [raw SQL](#fetch-queries):
**When the query interface can not generate the SQL you need**, you can still fall back to [raw SQL](#fetch-queries):
```swift
// Custom SQL is always welcome
@@ -4580,7 +4580,7 @@ try Player.customRequest().fetchAll(db) // [Player]
try request.fetchAll(db)
```
- The [`adapted(_:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/fetchrequest/adapted(_:)) method eases the consumption of complex rows with row adapters. See [`RowAdapter`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter) and [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)) for a sample code that uses `adapted(_:)`.
- The [`adapted(_:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/fetchrequest/adapted(_:)) method eases the consumption of complex rows with row adapters. See [`RowAdapter`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter) and [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)) for sample code that uses `adapted(_:)`.
Encryption
@@ -5020,14 +5020,14 @@ do {
// The extended error code: 787 (SQLITE_CONSTRAINT_FOREIGNKEY)
error.extendedResultCode
// The eventual SQLite message: FOREIGN KEY constraint failed
// The optional SQLite message: FOREIGN KEY constraint failed
error.message
// The eventual erroneous SQL query
// The optional erroneous SQL query
// "INSERT INTO pet (masterId, name) VALUES (?, ?)"
error.sql
// The eventual SQL arguments
// The optional SQL arguments
// [1, "Bobby"]
error.arguments
@@ -5040,7 +5040,7 @@ do {
If you want to see statement arguments in the error description, [make statement arguments public](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration/publicstatementarguments).
**SQLite uses [results codes](https://www.sqlite.org/rescode.html) to distinguish between various errors**.
**SQLite uses [result codes](https://www.sqlite.org/rescode.html) to distinguish between various errors**.
You can catch a DatabaseError and match on result codes:
@@ -5496,7 +5496,7 @@ try dbQueue.read { db in
}
```
Another option is to setup a tracing function that prints out the executed SQL requests. For example, provide a tracing function when you connect to the database:
Another option is to set up a tracing function that prints out the executed SQL requests. For example, provide a tracing function when you connect to the database:
```swift
// Prints all SQL statements
@@ -5637,7 +5637,7 @@ let books: [Book] = try dbQueue.read { db in
}
```
This request uses a TableAlias in order to be able to filter on the eventual associated author. We make sure, with `!authorAlias.exists`, that the associated author does not exist: the book has no author.
This request uses a TableAlias in order to be able to filter on the optional associated author. We make sure, with `!authorAlias.exists`, that the associated author does not exist: the book has no author.
See [How do I filter records and only keep those that are associated to another record?](#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record) above for the opposite question.
@@ -5700,7 +5700,7 @@ By using `asRequest(of:)`, you enhance the type-safety of your request.
### Why is ValueObservation not publishing value changes?
Sometimes it looks that a [ValueObservation] does not notify the changes you expect.
Sometimes it looks like a [ValueObservation] does not notify the changes you expect.
There may be four possible reasons for this:
@@ -902,7 +902,7 @@ class DatabaseWriterTests : GRDBTestCase {
func test(_ dbWriter: some DatabaseWriter) async throws {
// Numbers that have the test fail more or less reliably
// (on my machine) unless the #1838 patch is applied.
// When the test fails, we have a fatal error: A transaction has been left opened at the end of a database access.
// When the test fails, we have a fatal error: A transaction has been left open at the end of a database access.
let repeatCount = 400
let taskCount = 50
for _ in 0..<repeatCount {