mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-22 04:00:39 +00:00
Fix typos in public documentation
This commit is contained in:
1 parent
92a554cd0d
commit
7a216d7d34
124 files changed
+428
-427
No files matched your search
@@ -444,7 +444,7 @@ migrator.registerMigration("Employees") { db in
|
||||
}
|
||||
```
|
||||
|
||||
Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
|
||||
Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consume this association. For example:
|
||||
|
||||
```swift
|
||||
struct EmployeeInfo: FetchableRecord, Decodable {
|
||||
@@ -490,7 +490,7 @@ Make them look like Swift identifiers: `book`, `author`, `postalAddress`.
|
||||
If the database schema does not follow this convention, and has, for example, database tables which are named with underscores (`postal_address`), you can still use associations. But you need to help row consumption by naming your associations with a customized key:
|
||||
|
||||
```swift
|
||||
// Setup for table names that does not follow the expected convention
|
||||
// Setup for table names that do not follow the expected convention
|
||||
|
||||
struct PostalAddress: TableRecord {
|
||||
// Customized table name
|
||||
@@ -665,7 +665,7 @@ migrator.registerMigration("Countries") { db in
|
||||
1. The `country` table has a primary key.
|
||||
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. This column is indexed in order to ease the selection of the demographics of a country. A foreign key is defined from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
|
||||
3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country.
|
||||
4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile.
|
||||
4. Create a unique index on the `demographics.countryCode` column in order to guarantee the uniqueness of any country's profile.
|
||||
|
||||
The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
|
||||
|
||||
@@ -777,7 +777,7 @@ struct Book: TableRecord {
|
||||
Building Requests from Associations
|
||||
===================================
|
||||
|
||||
**Once you have defined associations, you can define fetch request that involve several record types.**
|
||||
**Once you have defined associations, you can define fetch requests that involve several record types.**
|
||||
|
||||
Fetch requests do not visit the database until you fetch values from them. This will be covered in [Fetching Values from Associations]. But before you can fetch anything, you have to describe what you want to fetch. This is the topic of this chapter.
|
||||
|
||||
@@ -801,7 +801,7 @@ For example, given a `Book.author` **[BelongsTo]** association, you can build a
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord, EncodableRecord {
|
||||
/// The association from a book to is author
|
||||
/// The association from a book to its author
|
||||
static let author = belongsTo(Author.self)
|
||||
|
||||
/// The request for the author of a book
|
||||
@@ -1735,7 +1735,7 @@ Associations support more refinements:
|
||||
|
||||
- [Common Table Expressions]
|
||||
|
||||
Association can use their own CTEs:
|
||||
Associations can use their own CTEs:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
@@ -1811,7 +1811,7 @@ let request = Book
|
||||
.filter { $0.publishDate >= authorAlias[Author.Columns.deathDate] }
|
||||
```
|
||||
|
||||
Note that Swift 6.1 is required for the short syntac `alias.column`. From now on, we will only give examples in Swift 6.1.
|
||||
Note that Swift 6.1 is required for the short syntax `alias.column`. From now on, we will only give examples in Swift 6.1.
|
||||
|
||||
**Table aliases** can also improve control over the ordering of request results. In the example below, we override the [default ordering](#sorting-associations) of associated records by sorting on author names first:
|
||||
|
||||
@@ -1990,7 +1990,7 @@ Each association included in the request can feed a property of the decoded reco
|
||||
let employeeInfos: [EmployeeInfo] = try EmployeeInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
- `including(required:)` feeds an non-optional property:
|
||||
- `including(required:)` feeds a non-optional property:
|
||||
|
||||
```swift
|
||||
let request = Book.including(required: Book.author)
|
||||
@@ -2024,7 +2024,7 @@ Each association included in the request can feed a property of the decoded reco
|
||||
|
||||
## The Structure of a Joined Request
|
||||
|
||||
**Joined request defines a tree of associated records identified by "association keys".**
|
||||
**A joined request defines a tree of associated records identified by "association keys".**
|
||||
|
||||
Below, author and cover image are both associated to book, and country is associated to author:
|
||||
|
||||
@@ -2052,7 +2052,7 @@ struct BookInfo: FetchableRecord, Decodable {
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
By default, **association keys** are the names of the database tables of associated records. Keys are automatically [singularized or pluralized](#convention-for-database-table-names), depending of the cardinality of the included association:
|
||||
By default, **association keys** are the names of the database tables of associated records. Keys are automatically [singularized or pluralized](#convention-for-database-table-names), depending on the cardinality of the included association:
|
||||
|
||||
```swift
|
||||
extension Author {
|
||||
@@ -2108,7 +2108,7 @@ let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
|
||||
We see that a hierarchical tree has been flattened in the `BookInfo` record.
|
||||
|
||||
But sometimes your decoded records will have better reflect the hierarchical structure of the request:
|
||||
But sometimes your decoded records will better reflect the hierarchical structure of the request:
|
||||
|
||||
|
||||
### Decoding a Hierarchical Decodable Record
|
||||
@@ -2126,7 +2126,7 @@ let request = Book
|
||||
|
||||
This requests for all books, with their cover images, and their authors and translators. Those people are themselves decorated with their respective nationalities.
|
||||
|
||||
We plan to decode this request into is the following nested record:
|
||||
We plan to decode this request into the following nested record:
|
||||
|
||||
```swift
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
@@ -2168,9 +2168,9 @@ let bookInfos = try BookInfo.all().fetchAll(db, request) // [BookInfo]
|
||||
|
||||
## Decoding a Joined Request with FetchableRecord
|
||||
|
||||
When [Decodable](#decoding-a-joined-request-with-a-decodable-record) records provides convenient decoding of joined rows, you may want a little more control over row decoding.
|
||||
When [Decodable](#decoding-a-joined-request-with-a-decodable-record) records provide convenient decoding of joined rows, you may want a little more control over row decoding.
|
||||
|
||||
The `init(row:)` initializer of the [FetchableRecord] protocol is what you look after:
|
||||
The `init(row:)` initializer of the [FetchableRecord] protocol is what you look for:
|
||||
|
||||
```swift
|
||||
let request = Book
|
||||
@@ -2308,7 +2308,7 @@ let request = author.books.select { max($0.year) }
|
||||
let maxBookYear = try Int.fetchOne(db, request) // Int?
|
||||
```
|
||||
|
||||
When you need to compute aggregates **from several record**, in a single shot, you'll use an **association aggregate**. Those are the topic of this chapter.
|
||||
When you need to compute aggregates **from several records**, in a single shot, you'll use an **association aggregate**. Those are the topic of this chapter.
|
||||
|
||||
For example, you'll use the `isEmpty` aggregate when you want, say, to fetch all authors who wrote no book at all, or some books:
|
||||
|
||||
@@ -2354,7 +2354,7 @@ for info in authorInfos {
|
||||
|
||||
### Annotating a Request with Aggregates
|
||||
|
||||
The `annotated(with:)` method appends aggregated values to the selected columns of a request. You can append as many aggregates values as needed, from one or several associations.
|
||||
The `annotated(with:)` method appends aggregated values to the selected columns of a request. You can append as many aggregate values as needed, from one or several associations.
|
||||
|
||||
In order to access those values, you fetch records that have matching properties.
|
||||
|
||||
@@ -2697,7 +2697,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
|
||||
When you compute multiple aggregates, make sure they use as many distinct **[association keys](#the-structure-of-a-joined-request)** as there are distinct populations of associated records.
|
||||
|
||||
In the example below, we use compute two aggregates from the same association `Author.books`. Both aggregates are computed on the same population of associated records, and so we want them to share the same association key:
|
||||
In the example below, we compute two aggregates from the same association `Author.books`. Both aggregates are computed on the same population of associated records, and so we want them to share the same association key:
|
||||
|
||||
- Authors with the publishing year of their first and last book:
|
||||
|
||||
@@ -2927,7 +2927,7 @@ See [Recommended Practices for Designing Record Types] for more information.
|
||||
|
||||
---
|
||||
|
||||
This documentation owns a lot to the [Active Record Associations](http://guides.rubyonrails.org/association_basics.html) guide, which is an immensely well-written introduction to database relations. Many thanks to the Rails team and contributors.
|
||||
This documentation owes a lot to the [Active Record Associations](http://guides.rubyonrails.org/association_basics.html) guide, which is an immensely well-written introduction to database relations. Many thanks to the Rails team and contributors.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ let cancellable = publisher.sink(
|
||||
|
||||
# Asynchronous Database Access
|
||||
|
||||
GRDB provide publishers that perform asynchronous database accesses:
|
||||
GRDB provides publishers that perform asynchronous database accesses:
|
||||
|
||||
- [`readPublisher(receiveOn:value:)`]
|
||||
- [`writePublisher(receiveOn:updates:)`]
|
||||
@@ -123,7 +123,7 @@ GRDB provide publishers that perform asynchronous database accesses:
|
||||
|
||||
#### `DatabaseReader.readPublisher(receiveOn:value:)`
|
||||
|
||||
This methods returns a publisher that completes after database values have been asynchronously fetched.
|
||||
This method returns a publisher that completes after database values have been asynchronously fetched.
|
||||
|
||||
```swift
|
||||
// DatabasePublishers.Read<[Player]>
|
||||
@@ -311,7 +311,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 introduce 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 eventual concurrent database writes from messing with your app, and introducing bugs.
|
||||
|
||||
To this end, remember that *all database publishers can perform several requests*.
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ let request = Player
|
||||
.filter { $0.name == playerNameCTE.all() }
|
||||
```
|
||||
|
||||
> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
|
||||
> **Note**: the `with(_:)` method can be called as many times as there are common table expressions in your request.
|
||||
>
|
||||
> **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
>
|
||||
|
||||
@@ -9,7 +9,7 @@ A custom SQLite build can activate extra SQLite features, and extra GRDB feature
|
||||
|
||||
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
|
||||
|
||||
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion librairies such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
|
||||
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion libraries such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
|
||||
@@ -29,13 +29,13 @@ GRDB lets you define your own custom FTS5 tokenizers, and extend SQLite built-in
|
||||
|
||||
**A Tokenizer splits text into tokens**. For example, a tokenizer can split "SQLite is a database engine" into the five tokens "SQLite", "is", "a", "database", and "engine".
|
||||
|
||||
FTS5 use tokenizers to tokenize both indexed documents and search patterns. **A match between a document and a search pattern happens when both produce *identical* tokens.**
|
||||
FTS5 uses tokenizers to tokenize both indexed documents and search patterns. **A match between a document and a search pattern happens when both produce *identical* tokens.**
|
||||
|
||||
All SQLite [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers) tokenize both "SQLite" and "sqlite" into the common lowercase token "sqlite". This is why they are case-insensitive. Generally speaking, different tokenizers achieve different matching by applying different transformations to the input text.
|
||||
|
||||
- The [ascii](https://www.sqlite.org/fts5.html#ascii_tokenizer) tokenizer turns all ASCII characters to lowercase. "SQLite is a database engine" gives "sqlite", "is", "a", "database", and "engine". The query "SQLITE DATABASE" will match, because its tokens "sqlite" and "database" are found in the document.
|
||||
|
||||
- The [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer remove diacritics from latin characters. Unlike the ascii tokenizer, it will match "Jérôme" with "Jerome", as both produce the same "jerome" token.
|
||||
- The [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer removes diacritics from latin characters. Unlike the ascii tokenizer, it will match "Jérôme" with "Jerome", as both produce the same "jerome" token.
|
||||
|
||||
- The [porter](https://www.sqlite.org/fts5.html#porter_tokenizer) tokenizer turns English words into their root: "database engine" gives the "databas" and "engin" tokens. The query "database engines" will match, because it produces the same tokens.
|
||||
|
||||
@@ -43,7 +43,7 @@ However, built-in tokenizers don't match "first" with "1st", because they produc
|
||||
|
||||
Nor do they match "Grossmann" with "Großmann", because they produce the different "grossmann" and "großmann" tokens.
|
||||
|
||||
Custom tokenizers help dealing with these situations. We'll see how to match "Grossmann" and "Großmann" by tokenizing them into "grossmann" (see [latin script](#example-latin-script)). We'll also see how to have "first" and "1st" emit *synonym tokens*, so that they can match too (see [synonyms](#example-synonyms)).
|
||||
Custom tokenizers help deal with these situations. We'll see how to match "Grossmann" and "Großmann" by tokenizing them into "grossmann" (see [latin script](#example-latin-script)). We'll also see how to have "first" and "1st" emit *synonym tokens*, so that they can match too (see [synonyms](#example-synonyms)).
|
||||
|
||||
|
||||
## The Tokenizer Protocols
|
||||
@@ -54,7 +54,7 @@ GRDB lets you use and define FTS5 tokenizers through three protocols:
|
||||
|
||||
- [FTS5CustomTokenizer](#fts5customtokenizer): the low-level protocol that lets custom tokenizers use the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
|
||||
|
||||
- [FTS5WrapperTokenizer](#fts5wrappertokenizer): the high-level protocol for custom tokenizers that post-processes the tokens produced by another FTS5Tokenizer.
|
||||
- [FTS5WrapperTokenizer](#fts5wrappertokenizer): the high-level protocol for custom tokenizers that post-process the tokens produced by another FTS5Tokenizer.
|
||||
|
||||
|
||||
## Using a Custom Tokenizer
|
||||
@@ -161,7 +161,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
|
||||
FTS5CustomTokenizer inherits from [FTS5Tokenizer](#fts5tokenizer), and performs tokenization with its `tokenize(context:tokenization:pText:nText:tokenCallback:)` method. This low-level method matches the `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers.
|
||||
|
||||
This method arguments are:
|
||||
This method's arguments are:
|
||||
|
||||
- `context`: An opaque pointer that is the first argument to the `tokenCallback` function
|
||||
- `tokenization`: The reason why FTS5 is requesting tokenization.
|
||||
@@ -182,7 +182,7 @@ Since tokenization is hard, and pointers to byte buffers uneasy to deal with, yo
|
||||
|
||||
**FTS5WrapperTokenizer** is the high-level protocol for your custom tokenizers. It provides a default implementation for the low-level `tokenize(context:tokenization:pText:nText:tokenCallback:)` method, so that the adopting type does not have to deal with raw byte buffers of the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
|
||||
|
||||
A FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the "wrapped tokenizer", and post-processes the tokens produced by this wrapped tokenizer.
|
||||
An FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the "wrapped tokenizer", and post-processes the tokens produced by this wrapped tokenizer.
|
||||
|
||||
```swift
|
||||
protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
|
||||
@@ -240,7 +240,7 @@ The tokenization parameter tells the reason why tokens are produced, if FTS5 is
|
||||
|
||||
Finally, the tokenCallback is a function you call to output a custom token.
|
||||
|
||||
There are a two rules to observe when implementing the accept method:
|
||||
There are two rules to observe when implementing the accept method:
|
||||
|
||||
1. Errors thrown by the tokenCallback function must not be caught (they notify that FTS5 requires the tokenization process to stop immediately).
|
||||
2. The flags parameter should be given unmodified to the tokenCallback function along with the custom token, unless you union it with the `.colocated` flag when the tokenizer produces [synonyms](#example-synonyms).
|
||||
|
||||
@@ -148,7 +148,7 @@ try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
}
|
||||
```
|
||||
|
||||
The `content` option is involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
The `content` option is involved in "contentless" and "external content" full-text tables. GRDB can help you define full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
|
||||
|
||||
See [SQLite documentation](https://www.sqlite.org/fts3.html) for more information.
|
||||
@@ -254,7 +254,7 @@ FTS3.tokenize("Gustave Doré", withTokenizer: .unicode61()) // ["gustave", "dore
|
||||
|
||||
**Not all search patterns are valid**: they must follow the [Full-Text Index Queries Grammar](https://www.sqlite.org/fts3.html#full_text_index_queries).
|
||||
|
||||
The FTS3Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
|
||||
The FTS3Pattern type helps you validate patterns, and build valid patterns from untrusted strings (such as strings typed by users):
|
||||
|
||||
```swift
|
||||
struct FTS3Pattern {
|
||||
@@ -377,7 +377,7 @@ try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
}
|
||||
```
|
||||
|
||||
The `content` and `contentRowID` options are involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
The `content` and `contentRowID` options are involved in "contentless" and "external content" full-text tables. GRDB can help you define full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
|
||||
See [SQLite documentation](https://www.sqlite.org/fts5.html) for more information.
|
||||
|
||||
@@ -493,7 +493,7 @@ See the `FTS5_TOKEN_*` flags in https://www.sqlite.org/fts5.html#custom_tokenize
|
||||
|
||||
**Not all search patterns are valid**: they must follow the [Full-Text Query Syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax).
|
||||
|
||||
The FTS5Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
|
||||
The FTS5Pattern type helps you validate patterns, and build valid patterns from untrusted strings (such as strings typed by users):
|
||||
|
||||
```swift
|
||||
extension Database {
|
||||
@@ -583,7 +583,7 @@ let documents = try Document.fetchAll(db,
|
||||
let documents = try Document.matching(pattern).order(Column.rank).fetchAll(db)
|
||||
```
|
||||
|
||||
For more information about the ranking algorithm, as well as extra options, read [Sorting by Auxiliary Function Results](https://www.sqlite.org/fts5.html#sorting_by_auxiliary_function_results)
|
||||
For more information about the ranking algorithm, as well as extra options, read [Sorting by Auxiliary Function Results](https://www.sqlite.org/fts5.html#sorting_by_auxiliary_function_results).
|
||||
|
||||
GRDB does not provide any ranking for FTS3 and FTS4. See SQLite's [Search Application Tips](https://www.sqlite.org/fts3.html#appendix_a) if you really need it.
|
||||
|
||||
@@ -623,11 +623,11 @@ See also [WWDC Companion](https://github.com/groue/WWDCCompanion), a sample app
|
||||
|
||||
### Deleting Synchronized Full-Text Tables
|
||||
|
||||
Synchronization of full-text tables with their content table happens by the mean of SQL triggers.
|
||||
Synchronization of full-text tables with their content table happens by means of SQL triggers.
|
||||
|
||||
SQLite automatically deletes those triggers when the content (not full-text) table is dropped.
|
||||
|
||||
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertion, updates, and deletions in the content table, and the creation of a new full-text table.
|
||||
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertions, updates, and deletions in the content table, and the creation of a new full-text table.
|
||||
|
||||
To drop those triggers, use the `dropFTS4SynchronizationTriggers` or `dropFTS5SynchronizationTriggers` methods:
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Migrating From GRDB 4 to GRDB 5
|
||||
===============================
|
||||
|
||||
**This guide aims at helping you upgrading your applications from GRDB 4 to GRDB 5.**
|
||||
**This guide aims at helping you upgrade your applications from GRDB 4 to GRDB 5.**
|
||||
|
||||
- [Preparing the Migration to GRDB 5](#preparing-the-migration-to-grdb-5)
|
||||
- [New requirements](#new-requirements)
|
||||
@@ -65,7 +65,7 @@ let dbQueue = try DatabaseQueue(dbPath, configuration: config)
|
||||
|
||||
[ValueObservation] is the database observation tool that tracks changes in database values. It has quite changed in GRDB 5.
|
||||
|
||||
Those changes have the vanilla GRDB, its [Combine publishers], and [RxGRDB] offer a common API, and a common behavior. This greatly helps choosing or switching your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
|
||||
Those changes have the vanilla GRDB, its [Combine publishers], and [RxGRDB] offer a common API, and a common behavior. This greatly helps choose or switch your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
|
||||
|
||||
In the end, this migration step might require some work. But it's for the benefit of all!
|
||||
|
||||
@@ -111,7 +111,7 @@ let observation = ValueObservation.tracking(someFetchFunction)
|
||||
let observation = ValueObservation.tracking { db in ... }
|
||||
```
|
||||
|
||||
Finally, ValueObservation used to let application define custom "reducers" based on a protocol name ValueReducer, which was removed in GRDB 5. See the [#731](https://github.com/groue/GRDB.swift/pull/731) conversation for a solution towards a replacement.
|
||||
Finally, ValueObservation used to let application define custom "reducers" based on a protocol named ValueReducer, which was removed in GRDB 5. See the [#731](https://github.com/groue/GRDB.swift/pull/731) conversation for a solution towards a replacement.
|
||||
|
||||
<details>
|
||||
<summary>RxGRDB impact</summary>
|
||||
@@ -319,7 +319,7 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
}
|
||||
```
|
||||
|
||||
As is previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
|
||||
As in previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
|
||||
|
||||
|
||||
## Combine Integration
|
||||
@@ -344,7 +344,7 @@ let publisher = observation
|
||||
|
||||
## Other Changes
|
||||
|
||||
1. The `Configuration.trace` property has been removed. You know use the `Database.trace(options:_:)` method instead:
|
||||
1. The `Configuration.trace` property has been removed. You now use the `Database.trace(options:_:)` method instead:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -360,7 +360,7 @@ let publisher = observation
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
```
|
||||
|
||||
2. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
|
||||
2. [Batch updates] used to rely on the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -372,7 +372,7 @@ let publisher = observation
|
||||
|
||||
> :question: This change avoids conflicts with other libraries that define the same operator.
|
||||
|
||||
3. [SQL Interpolation] does no longer wrap subqueries in parenthesis:
|
||||
3. [SQL Interpolation] does no longer wrap subqueries in parentheses:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -382,7 +382,7 @@ let publisher = observation
|
||||
// NEW: GRDB 5
|
||||
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
let bestPlayers: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
|
||||
// extra parenthesis required: ^ ^
|
||||
// extra parentheses required: ^ ^
|
||||
```
|
||||
|
||||
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Migrating From GRDB 5 to GRDB 6
|
||||
===============================
|
||||
|
||||
**This guide aims at helping you upgrading your applications from GRDB 5 to GRDB 6.**
|
||||
**This guide aims at helping you upgrade your applications from GRDB 5 to GRDB 6.**
|
||||
|
||||
- [Preparing the Migration to GRDB 6](#preparing-the-migration-to-grdb-6)
|
||||
- [New requirements](#new-requirements)
|
||||
@@ -283,7 +283,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
// How to detect failed `INSERT OR IGNORE`:
|
||||
// INSERT OR IGNORE INTO player ... RETURNING *
|
||||
if let insertedPlayer = try player.insertAndFetch(db) {
|
||||
// Succesful insertion
|
||||
// Successful insertion
|
||||
} else {
|
||||
// Ignored failure
|
||||
}
|
||||
@@ -371,7 +371,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
```diff
|
||||
-db.afterNextTransactionCommit { db in
|
||||
+db.afterNextTransaction { db in
|
||||
print("Succesful commit")
|
||||
print("Successful commit")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -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 of 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 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.
|
||||
|
||||
## New requirements
|
||||
|
||||
@@ -79,7 +79,7 @@ In GRDB 6, asynchronous database accesses such as `try await read { ... }` or `t
|
||||
|
||||
In GRDB 7, asynchronous database accesses respect Task cancellation. If a Task is cancelled, reads and writes throw a `CancellationError`, pending transactions are rolled back, and the database is not modified. The only SQL statement that can execute in a cancelled database access is `ROLLBACK`.
|
||||
|
||||
The effect of this change on your application depends on how it uses tasks. For example, take care of database jobs initiated frop the [`task`](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) SwiftUI modifier.
|
||||
The effect of this change on your application depends on how it uses tasks. For example, take care of database jobs initiated from the [`task`](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) SwiftUI modifier.
|
||||
|
||||
If you want an asynchronous database access to always complete, regardless of Task cancellation, wrap it in an unstructured Task:
|
||||
|
||||
@@ -95,7 +95,7 @@ let task = Task {
|
||||
try await task.value
|
||||
```
|
||||
|
||||
Other asynchronous database accesses, such as methods accepting a completion blocks (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
|
||||
Other asynchronous database accesses, such as methods accepting a completion block (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
|
||||
|
||||
## Associations to record types named Bias, Focus, Gas, and Lens
|
||||
|
||||
@@ -235,7 +235,7 @@ In GRDB 7, you may need an additional import, depending on how GRDB is integrate
|
||||
|
||||
Subclassing the [Record] class is **discouraged** in GRDB 7. Present in GRDB 1.0, in 2017, it has served its purpose.
|
||||
|
||||
It is not recommended to define any new type that subclass `Record`.
|
||||
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.
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
SQL interpolation looks and feel just like regular [String interpolation]:
|
||||
SQL interpolation looks and feels just like regular [String interpolation]:
|
||||
|
||||
```swift
|
||||
let name = "World"
|
||||
@@ -183,7 +183,7 @@ let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
|
||||
The [record protocols] extend your application types with database abilities.
|
||||
|
||||
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contain the column names. And with [FetchableRecord], you can decode raw database rows.
|
||||
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contains the column names. And with [FetchableRecord], you can decode raw database rows.
|
||||
|
||||
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names. Let's start from this record:
|
||||
|
||||
@@ -203,7 +203,7 @@ Let's extend Player with database methods.
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
/// Deletes all player with no score
|
||||
/// Deletes all players with no score
|
||||
static func deleteAllWithoutScore(_ db: Database) throws {
|
||||
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
|
||||
}
|
||||
@@ -252,7 +252,7 @@ Let's extend Player with database methods.
|
||||
}
|
||||
```
|
||||
|
||||
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. It profits from SQL interpolation, and this is why this method simply returns an "SQL literal"".
|
||||
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. It profits from SQL interpolation, and this is why this method simply returns an "SQL literal".
|
||||
|
||||
The first "simple" version only embeds the `\(id)` [value].
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ We'll start with a few [core principles](#core-principles), so that you see wher
|
||||
|
||||
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow["name"]`, doesn't it?
|
||||
|
||||
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
|
||||
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that come with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
|
||||
|
||||
Yet recent ORMs such as Rust's [Diesel] have shown that it is possible to build record types that behave as plain and simple values. GRDB belongs to this family.
|
||||
|
||||
@@ -31,7 +31,7 @@ In the same vein, each application thread has its own version of a Realm databas
|
||||
Conversely, GRDB assumes that many apps want to use the database as a reliable and unambiguous storage.
|
||||
|
||||
|
||||
### Applications developers have specific needs.
|
||||
### Application developers have specific needs.
|
||||
|
||||
GRDB puts all bets on SQLite, and focuses on front-end GUI applications.
|
||||
|
||||
@@ -115,7 +115,7 @@ let player = Player(name: "arthur", score: 1000)
|
||||
let players = try Player.fetchAll(db)
|
||||
```
|
||||
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, or by observing database changes and react accordingly.
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, or by observing database changes and reacting accordingly.
|
||||
|
||||
In order to keep your views synchronized with the database content, you can use [ValueObservation]. It notifies fresh values after each database change, with convenient support for [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB).
|
||||
|
||||
@@ -137,13 +137,13 @@ let cancellable = observation.publisher(in: dbQueue).sink(
|
||||
|
||||
// RxGRDB
|
||||
let disposable = observation.rx.observe(in: dbQueue).subscribe(
|
||||
onNext: { (players: [Player]) in print("Fresh playerss") },
|
||||
onNext: { (players: [Player]) in print("Fresh players") },
|
||||
onError: { error in ... })
|
||||
```
|
||||
|
||||
No matter which observation technique you use, you have common guarantees:
|
||||
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rollbacked.
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rolled back.
|
||||
|
||||
Next, you choose the dispatch queue on which notifications happen (generally the main queue, by default, as in the examples above). GRDB makes sure notifications happen in the same order as database transactions.
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ public struct Configuration: Sendable {
|
||||
public var label: String?
|
||||
|
||||
/// A boolean value indicating whether SQLite 3.29+ interprets
|
||||
/// double-quoted strings as string literals when they does not match any
|
||||
/// double-quoted strings as string literals when they do not match any
|
||||
/// valid identifier.
|
||||
///
|
||||
/// The default and recommended value is false:
|
||||
@@ -126,7 +126,7 @@ public struct Configuration: Sendable {
|
||||
///
|
||||
/// Set this flag to true when you apply the technique described in
|
||||
/// <doc:DatabaseSharing#How-to-limit-the-0xDEAD10CC-exception>. See
|
||||
/// ``Database/suspendNotification`` for more informations about
|
||||
/// ``Database/suspendNotification`` for more information about
|
||||
/// suspended databases.
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
@@ -236,7 +236,7 @@ public struct Configuration: Sendable {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// On newly created databases files, ``DatabasePool`` activates the WAL
|
||||
/// On newly created database files, ``DatabasePool`` activates the WAL
|
||||
/// mode after the preparation functions have run.
|
||||
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
@@ -259,7 +259,7 @@ public struct Configuration: Sendable {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When true, one can leave opened transaction at the end of database
|
||||
/// When true, one can leave an opened transaction at the end of a database
|
||||
/// access method:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -323,7 +323,7 @@ public struct Configuration: Sendable {
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// Defines the how `SQLITE_BUSY` errors are handled.
|
||||
/// Defines how `SQLITE_BUSY` errors are handled.
|
||||
///
|
||||
/// The default is ``Database/BusyMode/immediateError``.
|
||||
///
|
||||
|
||||
@@ -25,7 +25,7 @@ extension Database {
|
||||
public static func file(_ path: String) -> Self { Self(rawValue: path) }
|
||||
}
|
||||
|
||||
/// Granularitly of SQLCipher log outputs.
|
||||
/// Granularity of SQLCipher log outputs.
|
||||
///
|
||||
/// Each log level is more verbose than the last. With ``debug`` and
|
||||
/// ``trace`` the logging system will generate a significant log volume.
|
||||
|
||||
@@ -94,7 +94,7 @@ extension Database {
|
||||
/// Clears the database schema cache if the database schema has changed
|
||||
/// since this method was last called.
|
||||
func clearSchemaCacheIfNeeded() throws {
|
||||
// `PRAGMA schema_version` fetches a 4-bytes integer (Int32), stored
|
||||
// `PRAGMA schema_version` fetches a 4-byte integer (Int32), stored
|
||||
// at offset 40 of the database header:
|
||||
// <https://sqlite.org/pragma.html#pragma_schema_version>
|
||||
// <https://sqlite.org/fileformat2.html#database_header>
|
||||
@@ -528,7 +528,7 @@ extension Database {
|
||||
/// Fetches a customized primary key for the database view identified
|
||||
/// by `view`.
|
||||
///
|
||||
/// Nil is returned in the view does not exist, or if `columns` is empty.
|
||||
/// Nil is returned if the view does not exist, or if `columns` is empty.
|
||||
///
|
||||
/// - precondition: If the view exists, columns must exist, must
|
||||
/// identify a unique row, and must be not null.
|
||||
@@ -948,7 +948,7 @@ extension Database {
|
||||
/// - parameter tableName: The name of the table to examine
|
||||
/// - parameter schemaName: The name of the schema to check
|
||||
/// - parameter introspector: An introspection function taking a
|
||||
/// `DatabaseObjectID` as the only parameter. It the result
|
||||
/// `DatabaseObjectID` as the only parameter. If the result
|
||||
/// is nil, introspection fails and this method throws
|
||||
/// `DatabaseError.noSuchTable`.
|
||||
private func introspect<T>(
|
||||
@@ -987,7 +987,7 @@ extension Database {
|
||||
/// ```
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist,or if no such table or view
|
||||
/// the specified schema does not exist, or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
/// database.
|
||||
public func columns(in tableName: String, in schemaName: String? = nil) throws -> [ColumnInfo] {
|
||||
@@ -1135,7 +1135,7 @@ extension Database {
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns the columns to check for NULL in order to check if the row exist.
|
||||
/// Returns the columns to check for NULL in order to check if the row exists.
|
||||
///
|
||||
/// The returned array is never empty.
|
||||
func existenceCheckColumns(in tableName: String) throws -> [String] {
|
||||
@@ -1419,7 +1419,7 @@ public struct IndexInfo: Sendable{
|
||||
///
|
||||
/// You get instances of `ForeignKeyViolation` from the `Database` methods
|
||||
/// ``Database/foreignKeyViolations()`` and
|
||||
/// ``Database/foreignKeyViolations(in:in:)`` methods.
|
||||
/// ``Database/foreignKeyViolations(in:in:)``.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -1464,7 +1464,7 @@ public struct ForeignKeyViolation: Sendable {
|
||||
|
||||
/// The rowid of the row that contains the foreign key violation.
|
||||
///
|
||||
/// If it nil if the origin table is a `WITHOUT ROWID` table.
|
||||
/// It is nil if the origin table is a `WITHOUT ROWID` table.
|
||||
public var originRowID: Int64?
|
||||
|
||||
/// The name of the table that is referred to.
|
||||
@@ -1714,7 +1714,7 @@ public struct PrimaryKeyInfo: Sendable {
|
||||
|
||||
/// The name of the fastest primary key column.
|
||||
///
|
||||
/// Returns nil for WITHOUT ROWID tables with a multi-columns primary key
|
||||
/// Returns nil for WITHOUT ROWID tables with a multi-column primary key
|
||||
var fastPrimaryKeyColumn: String? {
|
||||
if let rowIDColumn {
|
||||
// Prefer the user-provided name of the rowid
|
||||
@@ -1828,7 +1828,7 @@ struct SchemaObject: Hashable, FetchableRecord {
|
||||
struct SchemaInfo: Equatable {
|
||||
let objects: Set<SchemaObject>
|
||||
|
||||
/// Returns whether there exists a object of given type with this name
|
||||
/// Returns whether there exists an object of given type with this name
|
||||
/// (case-insensitive).
|
||||
func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool {
|
||||
let name = name.lowercased()
|
||||
|
||||
+12
-12
@@ -908,7 +908,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// Reports the database region to ``ValueObservation``.
|
||||
///
|
||||
/// Calling this method does not fetch any database values. It just
|
||||
/// helps optimizing `ValueObservation`. See
|
||||
/// helps optimize `ValueObservation`. See
|
||||
/// ``ValueObservation/trackingConstantRegion(_:)`` for more
|
||||
/// information, and some examples of usage.
|
||||
///
|
||||
@@ -1349,9 +1349,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// - When database access is cancelled, this method
|
||||
/// throws `CancellationError`.
|
||||
///
|
||||
/// - When database is suspensed, and if the statement would lock the
|
||||
/// - When database is suspended, and if the statement would lock the
|
||||
/// database in a way that may trigger the 0xDEAD10CC exception, this
|
||||
/// method rollbacks the current transaction and throws `SQLITE_ABORT`.
|
||||
/// method rolls back the current transaction and throws `SQLITE_ABORT`.
|
||||
///
|
||||
/// See `cancel()`, `suspend()` and
|
||||
/// ``Configuration/observesSuspensionNotifications``.
|
||||
@@ -1447,14 +1447,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - Transactions & Savepoint
|
||||
|
||||
/// Throws `SQLITE_ABORT` if called from a transaction-wrapping method and
|
||||
/// transaction has been aborted (for example, by `sqlite3_interrupt`, or a
|
||||
/// `ON CONFLICT ROLLBACK` clause.
|
||||
/// transaction has been aborted (for example, by `sqlite3_interrupt`, or an
|
||||
/// `ON CONFLICT ROLLBACK` clause).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// do {
|
||||
/// // Throws an error because the transaction was rollbacked.
|
||||
/// // Throws an error because the transaction was rolled back.
|
||||
/// try ...
|
||||
/// } catch {
|
||||
/// // Catch the error and continue.
|
||||
@@ -1493,9 +1493,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If `operations` throws an error, the transaction is rollbacked and the
|
||||
/// If `operations` throws an error, the transaction is rolled back and the
|
||||
/// error is rethrown. If it returns ``TransactionCompletion/rollback``, the
|
||||
/// transaction is also rollbacked, but no error is thrown.
|
||||
/// transaction is also rolled back, but no error is thrown.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
///
|
||||
@@ -1612,9 +1612,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If `operations` throws an error, the savepoint is rollbacked and the
|
||||
/// If `operations` throws an error, the savepoint is rolled back and the
|
||||
/// error is rethrown. If it returns ``TransactionCompletion/rollback``, the
|
||||
/// savepoint is also rollbacked, but no error is thrown.
|
||||
/// savepoint is also rolled back, but no error is thrown.
|
||||
///
|
||||
/// This method is reentrant: you can nest savepoints.
|
||||
///
|
||||
@@ -1738,7 +1738,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
|
||||
}
|
||||
|
||||
/// Rollbacks a database transaction.
|
||||
/// Rolls back a database transaction.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
///
|
||||
@@ -1810,7 +1810,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Resets all prepared statements.
|
||||
///
|
||||
/// This method helps clearing the interrupted state, as a workaround
|
||||
/// This method helps clear the interrupted state, as a workaround
|
||||
/// for https://sqlite.org/forum/forumpost/137c7662b3, discovered
|
||||
/// in https://github.com/groue/GRDB.swift/issues/1838.
|
||||
func resetAllPreparedStatements() {
|
||||
|
||||
@@ -21,7 +21,7 @@ public struct DatabaseBackupProgress: Sendable {
|
||||
|
||||
/// A boolean value indicating whether the backup is complete.
|
||||
///
|
||||
/// It is true if and only if the last call the `sqlite3_backup_step` has
|
||||
/// It is true if and only if the last call to `sqlite3_backup_step` has
|
||||
/// returned `SQLITE_DONE`.
|
||||
public let isCompleted: Bool
|
||||
}
|
||||
@@ -79,7 +79,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// - argumentCount: The number of arguments of the function. If
|
||||
/// omitted, or nil, the function accepts any number of arguments.
|
||||
/// - pure: Whether the function is "pure", which means that its results
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// only depend on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of ``DatabaseValue``
|
||||
@@ -167,7 +167,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// - argumentCount: The number of arguments of the aggregate. If
|
||||
/// omitted, or nil, the aggregate accepts any number of arguments.
|
||||
/// - pure: Whether the aggregate is "pure", which means that its
|
||||
/// results only depends on its inputs. When an aggregate is pure,
|
||||
/// results only depend on its inputs. When an aggregate is pure,
|
||||
/// SQLite has the opportunity to perform additional optimizations.
|
||||
/// Default value is false.
|
||||
/// - aggregate: A type that implements the ``DatabaseAggregate``
|
||||
|
||||
@@ -848,10 +848,10 @@ extension DatabasePool: DatabaseWriter {
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// If `updates` throws an error, the transaction is rolled back and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rollbacked, but no error is thrown.
|
||||
/// rolled back, but no error is thrown.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
|
||||
@@ -357,10 +357,10 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// If `updates` throws an error, the transaction is rolled back and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rollbacked, but no error is thrown.
|
||||
/// rolled back, but no error is thrown.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
|
||||
@@ -74,7 +74,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// every future database access will throw a ``DatabaseError`` of
|
||||
/// code `SQLITE_MISUSE`.
|
||||
///
|
||||
/// Otherwise, there exists concurrent database accesses or living prepared
|
||||
/// Otherwise, there exist concurrent database accesses or living prepared
|
||||
/// statements that prevent the database from closing, and this method
|
||||
/// throws a ``DatabaseError`` of code `SQLITE_BUSY`.
|
||||
/// See <https://www.sqlite.org/c3ref/close.html> for more information.
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// It is dedicated to help ``TransactionObserver`` types detect impactful
|
||||
/// It is dedicated to helping ``TransactionObserver`` types detect impactful
|
||||
/// database changes.
|
||||
///
|
||||
/// You get `DatabaseRegion` instances from a ``DatabaseRegionConvertible``
|
||||
|
||||
@@ -39,7 +39,7 @@ import Dispatch
|
||||
/// snapshot from within a write access, outside of any transaction.
|
||||
///
|
||||
/// For example, compare the two snapshots below. The first one is guaranteed to
|
||||
/// see an empty table of players, because is is created after all players have
|
||||
/// see an empty table of players, because it is created after all players have
|
||||
/// been deleted, and from the serialized writer dispatch queue which prevents
|
||||
/// any concurrent write. The second is created without this concurrency
|
||||
/// protection, which means that some other threads may already have created
|
||||
@@ -70,7 +70,7 @@ import Dispatch
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshot` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
/// ``DatabaseReader`` protocol.
|
||||
///
|
||||
/// `DatabaseSnapshot` serializes database accesses and can't perform concurrent
|
||||
/// reads. For concurrent reads, see ``DatabaseSnapshotPool``.
|
||||
|
||||
@@ -65,7 +65,7 @@ import GRDBSQLite
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshotPool` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
/// ``DatabaseReader`` protocol.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
|
||||
@@ -16,7 +16,7 @@ import Foundation
|
||||
///
|
||||
/// To get `DatabaseValue` instances, you can:
|
||||
///
|
||||
/// - Fetch `DatabaseValue` from a ``Database`` instace:
|
||||
/// - Fetch `DatabaseValue` from a ``Database`` instance:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
@@ -121,7 +121,7 @@ public struct DatabaseValue: Hashable {
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// A boolean value indicating is the database value is `NULL`.
|
||||
/// A boolean value indicating if the database value is `NULL`.
|
||||
public var isNull: Bool {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -270,7 +270,7 @@ extension DatabaseValue: Equatable {
|
||||
/// 1.databaseValue == 1.databaseValue // true
|
||||
/// ```
|
||||
///
|
||||
/// When comparing integers and doubles, the result is true if and only
|
||||
/// When comparing integers and doubles, the result is true if and only if
|
||||
/// values are equal, and if converting one type to the other does
|
||||
/// not lose information:
|
||||
///
|
||||
|
||||
@@ -227,7 +227,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
@available(*, unavailable)
|
||||
extension DatabaseValueCursor: Sendable { }
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow you to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
|
||||
@@ -392,7 +392,7 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rollbacked and the error is rethrown.
|
||||
/// error, the transaction is rolled back and the error is rethrown.
|
||||
///
|
||||
/// Concurrent database accesses can not see partial database updates (even
|
||||
/// when performed by other processes).
|
||||
@@ -442,7 +442,7 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations run by the `updates` closure are wrapped in
|
||||
/// a transaction. If they throw an error, the transaction is rollbacked.
|
||||
/// a transaction. If they throw an error, the transaction is rolled back.
|
||||
///
|
||||
/// The `completion` closure has two arguments: a database connection, and
|
||||
/// the result of the transaction. This result is a failure if the
|
||||
@@ -623,7 +623,7 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rollbacked and the error is rethrown.
|
||||
/// error, the transaction is rolled back and the error is rethrown.
|
||||
///
|
||||
/// Concurrent database accesses can not see partial database updates (even
|
||||
/// when performed by other processes).
|
||||
@@ -715,7 +715,7 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rollbacked and the error completes
|
||||
/// error, the transaction is rolled back and the error completes
|
||||
/// the publisher.
|
||||
///
|
||||
/// Concurrent database accesses can not see partial database updates (even
|
||||
|
||||
+9
-9
@@ -41,7 +41,7 @@ import Foundation
|
||||
///
|
||||
/// - ``copy()``
|
||||
///
|
||||
/// ### Row Informations
|
||||
/// ### Row Information
|
||||
///
|
||||
/// - ``columnNames``
|
||||
/// - ``containsNonNullValue``
|
||||
@@ -263,7 +263,7 @@ public final class Row {
|
||||
self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count`
|
||||
}
|
||||
|
||||
/// Creates a row that contain a copy of the current state of the
|
||||
/// Creates a row that contains a copy of the current state of the
|
||||
/// SQLite statement. Further calls to sqlite3_step() do not modify the row.
|
||||
///
|
||||
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
|
||||
@@ -327,7 +327,7 @@ extension Row {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line)
|
||||
}
|
||||
|
||||
/// Returns a boolean value indicating if the row contains one value this
|
||||
/// Returns a boolean value indicating if the row contains one value that
|
||||
/// is not `NULL`.
|
||||
///
|
||||
/// For example:
|
||||
@@ -662,7 +662,7 @@ extension Row {
|
||||
/// If the SQLite value is NULL, the result is nil. If the SQLite value can
|
||||
/// not be converted to Data, a fatal error is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// The returned data does not own its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
@available(*, deprecated, message: "Use withUnsafeData(atIndex:_:) instead.")
|
||||
public func dataNoCopy(atIndex index: Int) -> Data? {
|
||||
@@ -678,7 +678,7 @@ extension Row {
|
||||
/// nil. If the SQLite value can not be converted to Data, a fatal error
|
||||
/// is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// The returned data does not own its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
@available(*, deprecated, message: "Use withUnsafeData(named:_:) instead.")
|
||||
public func dataNoCopy(named columnName: String) -> Data? {
|
||||
@@ -697,7 +697,7 @@ extension Row {
|
||||
/// nil. If the SQLite value can not be converted to Data, a fatal error
|
||||
/// is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// The returned data does not own its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
@available(*, deprecated, message: "Use withUnsafeData(at:_:) instead.")
|
||||
public func dataNoCopy(_ column: some ColumnExpression) -> Data? {
|
||||
@@ -1021,7 +1021,7 @@ extension Row {
|
||||
ScopesTreeView(scopes: scopes)
|
||||
}
|
||||
|
||||
/// The row, without any scope of prefetched rows.
|
||||
/// The row, without any scope or prefetched rows.
|
||||
///
|
||||
/// This property is useful when testing the content of rows fetched from
|
||||
/// joined requests.
|
||||
@@ -2395,7 +2395,7 @@ extension Row: CustomDebugStringConvertible {
|
||||
|
||||
extension Row: ExpressibleByDictionaryLiteral {
|
||||
/// Creates a row initialized with elements. Column order is preserved, and
|
||||
/// duplicated columns names are allowed.
|
||||
/// duplicated column names are allowed.
|
||||
///
|
||||
/// let row: Row = ["foo": 1, "foo": "bar", "baz": nil]
|
||||
/// print(row)
|
||||
@@ -2567,7 +2567,7 @@ extension Row {
|
||||
// (we preserve the ordering of associations in the request)
|
||||
fileprivate var prefetches: OrderedDictionary<String, Prefetch> = [:]
|
||||
|
||||
/// A boolean value indicating if there is no prefetched
|
||||
/// A boolean value indicating if there are no prefetched
|
||||
/// associated rows.
|
||||
public var isEmpty: Bool {
|
||||
prefetches.isEmpty
|
||||
|
||||
@@ -16,7 +16,7 @@ import Foundation
|
||||
/// """
|
||||
/// ```
|
||||
///
|
||||
/// The resulting rows contains columns from both player and team tables:
|
||||
/// The resulting rows contain columns from both player and team tables:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [id: 1, name: "Arthur", teamId: 42, id: 42, name: "Reds"]
|
||||
@@ -222,7 +222,7 @@ extension _LayoutedColumnMapping: _RowLayout {
|
||||
|
||||
/// `_LayoutedRowAdapter` is a protocol that supports the `RowAdapter` protocol.
|
||||
///
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// GRDB ships with a ready-made type that adopts this protocol:
|
||||
/// `_LayoutedColumnMapping`.
|
||||
public protocol _LayoutedRowAdapter {
|
||||
/// A LayoutedColumnMapping that defines how to map a column name to a
|
||||
@@ -255,7 +255,7 @@ extension Statement: _RowLayout {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that helps two incompatible row interfaces working together.
|
||||
/// A type that helps two incompatible row interfaces work together.
|
||||
///
|
||||
/// Row adapters present database rows in the way expected by the
|
||||
/// row consumers.
|
||||
@@ -495,7 +495,7 @@ public struct RangeRowAdapter: RowAdapter, Sendable {
|
||||
/// `ScopeAdapter` is a row adapter that defines row scopes.
|
||||
///
|
||||
/// `ScopeAdapter` does not change the columns and values of the fetched
|
||||
/// row. Instead, it defines *scopes* based on other adapter, which you
|
||||
/// row. Instead, it defines *scopes* based on other adapters, which you
|
||||
/// access through the ``Row/scopes`` property of the fetched rows.
|
||||
///
|
||||
/// For example:
|
||||
@@ -559,7 +559,7 @@ public struct ScopeAdapter: RowAdapter {
|
||||
/// The scope adapters
|
||||
let scopes: [String: any RowAdapter]
|
||||
|
||||
/// Creates an adapter that preserves row contents and add scoped rows.
|
||||
/// Creates an adapter that preserves row contents and adds scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -575,7 +575,7 @@ public struct ScopeAdapter: RowAdapter {
|
||||
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
|
||||
}
|
||||
|
||||
/// Creates an adapter based on the base adapter, and add scoped rows.
|
||||
/// Creates an adapter based on the base adapter, and adds scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
|
||||
+1
-1
@@ -300,7 +300,7 @@ extension SQL: SQLOrderingTerm {
|
||||
/// let request = Player.order(ordering)
|
||||
/// ```
|
||||
///
|
||||
/// An ordering term is only valid if it represent a single ordering terms.
|
||||
/// An ordering term is only valid if it represents a single ordering term.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Valid
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// SchedulingWatchdog makes sure that databases connections are used on correct
|
||||
/// SchedulingWatchdog makes sure that database connections are used on correct
|
||||
/// dispatch queues, and warns the user with a fatal error whenever she misuses
|
||||
/// a database connection.
|
||||
///
|
||||
|
||||
@@ -235,7 +235,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
/// Returns true if and only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
SchedulingWatchdog.current?.allows(db) ?? false
|
||||
}
|
||||
@@ -248,7 +248,7 @@ final class SerializedDatabase {
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
/// Asynchrously executes the block.
|
||||
/// Asynchronously executes the block.
|
||||
func execute<T: Sendable>(
|
||||
_ block: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
|
||||
+12
-12
@@ -112,7 +112,7 @@ public final class Statement {
|
||||
/// The effects on the database (reported by `sqlite3_set_authorizer`).
|
||||
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
/// If true, the statement is a `PRAGMA QUERY_ONLY` statement.
|
||||
private(set) var isQueryOnlyPragma = false
|
||||
|
||||
/// A boolean value indicating if the prepared statement makes no direct
|
||||
@@ -288,7 +288,7 @@ public final class Statement {
|
||||
/// print(statement.arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If is a programmer error to set arguments that do not provide all
|
||||
/// It is a programmer error to set arguments that do not provide all
|
||||
/// values expected by the statement:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -547,7 +547,7 @@ public final class Statement {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When arguments are set at the moment of execution, with an non-nil
|
||||
/// When arguments are set at the moment of execution, with a non-nil
|
||||
/// `arguments` parameter, it is assumed that the statement won't be
|
||||
/// reused with the same arguments. When the number of arguments is
|
||||
/// small, execution is performed with temporary SQLite bindings that
|
||||
@@ -567,7 +567,7 @@ public final class Statement {
|
||||
/// ```
|
||||
///
|
||||
/// Both techniques have the same results, but when you care about
|
||||
/// performances, monitor your application in order to make the
|
||||
/// performance, monitor your application in order to make the
|
||||
/// best choice.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
@@ -616,7 +616,7 @@ public final class Statement {
|
||||
|
||||
/// Calls the given closure after each successful call to `sqlite3_step()`.
|
||||
///
|
||||
/// This method is slighly faster than calling `step(_:)` repeatedly, due
|
||||
/// This method is slightly faster than calling `step(_:)` repeatedly, due
|
||||
/// to the single `sqlite3_stmt_busy` check.
|
||||
@usableFromInline
|
||||
func forEachStep(_ body: (SQLiteStatement) throws -> Void) throws {
|
||||
@@ -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 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`.
|
||||
///
|
||||
@@ -1188,7 +1188,7 @@ public struct StatementArguments: Hashable {
|
||||
return replacedValues
|
||||
}
|
||||
|
||||
/// Creates a new `StatementArguments` by extending the left-hand size
|
||||
/// Creates a new `StatementArguments` by extending the left-hand side
|
||||
/// arguments with the right-hand side arguments.
|
||||
///
|
||||
/// Positional arguments are concatenated:
|
||||
@@ -1209,7 +1209,7 @@ public struct StatementArguments: Hashable {
|
||||
/// print(arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If the arguments on the right-hand side has named parameters that are
|
||||
/// If the arguments on the right-hand side have named parameters that are
|
||||
/// already defined on the left, a fatal error is raised:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -1236,7 +1236,7 @@ public struct StatementArguments: Hashable {
|
||||
return lhs
|
||||
}
|
||||
|
||||
/// Creates a new `StatementArguments` by extending the left-hand size
|
||||
/// Creates a new `StatementArguments` by extending the left-hand side
|
||||
/// arguments with the right-hand side arguments.
|
||||
///
|
||||
/// Positional arguments are concatenated:
|
||||
@@ -1257,7 +1257,7 @@ public struct StatementArguments: Hashable {
|
||||
/// print(arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If a named arguments is defined in both arguments, the right-hand
|
||||
/// If a named argument is defined in both arguments, the right-hand
|
||||
/// side wins:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -1282,7 +1282,7 @@ public struct StatementArguments: Hashable {
|
||||
return lhs
|
||||
}
|
||||
|
||||
/// Extends the left-hand size arguments with the right-hand side arguments.
|
||||
/// Extends the left-hand side arguments with the right-hand side arguments.
|
||||
///
|
||||
/// Positional arguments are concatenated:
|
||||
///
|
||||
@@ -1304,7 +1304,7 @@ public struct StatementArguments: Hashable {
|
||||
/// print(arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If the arguments on the right-hand side has named parameters that are
|
||||
/// If the arguments on the right-hand side have named parameters that are
|
||||
/// already defined on the left, a fatal error is raised:
|
||||
///
|
||||
/// ```swift
|
||||
|
||||
@@ -46,7 +46,7 @@ final class StatementAuthorizer {
|
||||
/// savepoint statement.
|
||||
var transactionEffect: Statement.TransactionEffect?
|
||||
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
/// If true, the statement is a `PRAGMA QUERY_ONLY` statement.
|
||||
var isQueryOnlyPragma = false
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
@@ -103,7 +103,7 @@ public protocol StatementColumnConvertible {
|
||||
/// database values are handled
|
||||
/// in ``StatementColumnConvertible/fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
/// For example, here is how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// ```swift
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
|
||||
@@ -50,7 +50,7 @@ extension Date: DatabaseValueConvertible {
|
||||
storageDateFormatter.string(from: self).databaseValue
|
||||
}
|
||||
|
||||
/// Creates an `Date` with the specified database value.
|
||||
/// Creates a `Date` with the specified database value.
|
||||
///
|
||||
/// If the database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
|
||||
@@ -21,9 +21,9 @@ extension Decimal: DatabaseValueConvertible {
|
||||
.databaseValue
|
||||
}
|
||||
|
||||
/// Creates an `Decimal` with the specified database value.
|
||||
/// Creates a `Decimal` with the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer or a double, returns a
|
||||
/// If the database value contains an integer or a double, returns a
|
||||
/// `Decimal` initialized from this number.
|
||||
///
|
||||
/// If the database value contains a string, parses the string with the
|
||||
|
||||
@@ -8,7 +8,7 @@ extension NSData: DatabaseValueConvertible {
|
||||
(self as Data).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `NSData` from the specified database value.
|
||||
/// Returns an `NSData` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a data blob, returns it.
|
||||
///
|
||||
|
||||
@@ -69,7 +69,7 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `NSNumber` from the specified database value.
|
||||
/// Returns an `NSNumber` from the specified database value.
|
||||
///
|
||||
/// If the database value is an integer or a double, returns an `NSNumber`
|
||||
/// initialized from this number.
|
||||
|
||||
@@ -8,11 +8,11 @@ extension NSString: DatabaseValueConvertible {
|
||||
(self as String).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `NSString` from the specified database value.
|
||||
/// Returns an `NSString` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, returns it.
|
||||
///
|
||||
/// If the database value contains a data blob, parses this data as an
|
||||
/// If the database value contains a data blob, parses this data as a
|
||||
/// UTF8 string.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
|
||||
@@ -23,9 +23,9 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `NSUUID` from the specified database value.
|
||||
/// Returns an `NSUUID` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, parses this string as an uuid.
|
||||
/// If the database value contains a string, parses this string as a uuid.
|
||||
///
|
||||
/// If the database value contains a data blob that contains 16 bytes,
|
||||
/// returns a uuid from those bytes.
|
||||
@@ -63,7 +63,7 @@ extension UUID: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a `UUID` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, parses this string as an uuid.
|
||||
/// If the database value contains a string, parses this string as a uuid.
|
||||
///
|
||||
/// If the database value contains a data blob that contains 16 bytes,
|
||||
/// returns a uuid from those bytes.
|
||||
|
||||
@@ -130,9 +130,9 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `Int` from the specified database value.
|
||||
/// Returns an `Int` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -169,9 +169,9 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `Int8` from the specified database value.
|
||||
/// Returns an `Int8` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -208,9 +208,9 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `Int16` from the specified database value.
|
||||
/// Returns an `Int16` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -247,9 +247,9 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `Int32` from the specified database value.
|
||||
/// Returns an `Int32` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -282,9 +282,9 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
DatabaseValue(storage: .int64(self))
|
||||
}
|
||||
|
||||
/// Returns a `Int64` from the specified database value.
|
||||
/// Returns an `Int64` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer, returns this integer.
|
||||
/// If the database value contains an integer, returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
@@ -331,7 +331,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -370,7 +370,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt8` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -409,7 +409,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt16` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -448,7 +448,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt32` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -487,7 +487,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt64` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -522,7 +522,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `Double` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer, returns the conversion.
|
||||
/// If the database value contains an integer, returns the conversion.
|
||||
///
|
||||
/// If the database value contains a double, returns this double.
|
||||
///
|
||||
@@ -562,7 +562,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `Float` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer, returns the conversion.
|
||||
/// If the database value contains an integer, returns the conversion.
|
||||
///
|
||||
/// If the database value contains a double, returns the conversion.
|
||||
///
|
||||
@@ -606,7 +606,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
///
|
||||
/// If the database value contains a string, returns it.
|
||||
///
|
||||
/// If the database value contains a data blob, parses this data as an
|
||||
/// If the database value contains a data blob, parses this data as a
|
||||
/// UTF8 string.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
@@ -652,7 +652,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs body over the content of this string as an UTF8 string. This
|
||||
/// Runs body over the content of this string as a UTF8 string. This
|
||||
/// method exists because it deals with the ASCII NUL (\0) characters,
|
||||
/// unlike C strings.
|
||||
///
|
||||
@@ -684,7 +684,7 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.capitalized` property.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
@@ -705,7 +705,7 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Swift
|
||||
/// `String.lowercased()` method.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
@@ -726,7 +726,7 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Swift
|
||||
/// `String.uppercased()` method.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
@@ -747,7 +747,7 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.localizedCapitalized` property.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
@@ -769,7 +769,7 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.localizedLowercase` property.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
@@ -790,7 +790,7 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.localizedUppercase` property.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
|
||||
@@ -72,7 +72,7 @@ extension Database {
|
||||
/// Registers closures to be executed after the next or current
|
||||
/// transaction completes.
|
||||
///
|
||||
/// This method helps synchronizing the database with other resources,
|
||||
/// This method helps synchronize the database with other resources,
|
||||
/// such as files, or system services.
|
||||
///
|
||||
/// In the example below, a `CLLocationManager` starts monitoring a
|
||||
@@ -104,10 +104,10 @@ extension Database {
|
||||
/// ```
|
||||
///
|
||||
/// The method above won't trigger the location manager if the transaction
|
||||
/// is eventually rollbacked (explicitly, or because of an error).
|
||||
/// is eventually rolled back (explicitly, or because of an error).
|
||||
///
|
||||
/// The `onCommit` and `onRollback` closures are executed in the writer
|
||||
/// dispatch queue, serialized will all database updates.
|
||||
/// dispatch queue, serialized with all database updates.
|
||||
///
|
||||
/// - precondition: Database connection is not read-only.
|
||||
/// - parameter onCommit: A closure executed on transaction commit.
|
||||
@@ -189,7 +189,7 @@ extension Database {
|
||||
/// The observation process starts when the statement is *compiled*:
|
||||
/// sqlite3_set_authorizer tells that the statement performs insertion into the
|
||||
/// `document` table. Generally speaking, statements may have many effects, by
|
||||
/// the mean of foreign key actions and SQL triggers. SQLite takes care of
|
||||
/// means of foreign key actions and SQL triggers. SQLite takes care of
|
||||
/// exposing all those effects to sqlite3_set_authorizer.
|
||||
///
|
||||
/// When the statement is *about to be executed*, the broker queries the
|
||||
@@ -218,7 +218,7 @@ extension Database {
|
||||
/// This time, when the statement is *executed* and SQLite tells that a row has
|
||||
/// been inserted, the broker buffers the change event instead of immediately
|
||||
/// notifying the activated observers. That is because the savepoint can be
|
||||
/// rollbacked, and GRDB guarantees observers that they are only notified of
|
||||
/// rolled back, and GRDB guarantees observers that they are only notified of
|
||||
/// changes that have an opportunity to be committed.
|
||||
///
|
||||
/// The savepoint is released:
|
||||
@@ -239,7 +239,7 @@ extension Database {
|
||||
/// During the statement *execution*, SQLite tells the broker that the
|
||||
/// transaction is about to be committed through sqlite3_commit_hook. The broker
|
||||
/// invokes observer.databaseWillCommit(). If the observer throws an error, the
|
||||
/// broker asks SQLite to rollback the transaction. Otherwise, the broker lets
|
||||
/// broker asks SQLite to roll back the transaction. Otherwise, the broker lets
|
||||
/// the transaction complete.
|
||||
///
|
||||
/// After the statement *has been executed*, the broker calls
|
||||
@@ -742,10 +742,10 @@ class DatabaseObservationBroker {
|
||||
/// Transaction turns committed.
|
||||
case commit
|
||||
|
||||
/// Transaction turns rollbacked.
|
||||
/// Transaction turns rolled back.
|
||||
case rollback
|
||||
|
||||
/// Transaction turns rollbacked because a transaction observer has
|
||||
/// Transaction turns rolled back because a transaction observer has
|
||||
/// cancelled a commit by throwing an error.
|
||||
case cancelledCommit(Error)
|
||||
}
|
||||
@@ -879,7 +879,7 @@ public protocol TransactionObserver: AnyObject {
|
||||
|
||||
/// Called when a transaction is about to be committed.
|
||||
///
|
||||
/// The transaction observer has an opportunity to rollback pending changes
|
||||
/// The transaction observer has an opportunity to roll back pending changes
|
||||
/// by throwing an error from this method.
|
||||
///
|
||||
/// - precondition: This method must not access the observed writer
|
||||
@@ -890,7 +890,7 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// Called when a transaction has been committed on disk.
|
||||
func databaseDidCommit(_ db: Database)
|
||||
|
||||
/// Called when a transaction has been rollbacked.
|
||||
/// Called when a transaction has been rolled back.
|
||||
func databaseDidRollback(_ db: Database)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
@@ -1689,13 +1689,13 @@ enum DatabaseEventPredicate {
|
||||
/// - know if there are currently active savepoints (isEmpty)
|
||||
/// - buffer database events when a savepoint is active, in order to avoid
|
||||
/// notifying transaction observers of database events that could be
|
||||
/// rollbacked.
|
||||
/// rolled back.
|
||||
class SavepointStack {
|
||||
/// The buffered events (see DatabaseObservationBroker.databaseDidChange(with:))
|
||||
var eventsBuffer: [(event: any DatabaseEventProtocol, statementObservations: [StatementObservation])] = []
|
||||
|
||||
/// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array).
|
||||
/// Indexes let us drop rollbacked events from the event buffer.
|
||||
/// Indexes let us drop rolled-back events from the event buffer.
|
||||
private var savepoints: [(name: String, index: Int)] = []
|
||||
|
||||
/// If true, there is no current save point.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// A long-live read-only WAL transaction.
|
||||
/// A long-lived read-only WAL transaction.
|
||||
///
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
|
||||
@@ -35,7 +35,7 @@ final class WALSnapshotTransaction: @unchecked Sendable {
|
||||
/// The state of the database at the beginning of the transaction.
|
||||
let walSnapshot: WALSnapshot
|
||||
|
||||
/// Creates a long-live WAL transaction on a read-only connection.
|
||||
/// Creates a long-lived WAL transaction on a read-only connection.
|
||||
///
|
||||
/// The `release` closure is always called. It is called when the
|
||||
/// `WALSnapshotTransaction` is deallocated, or if the initializer
|
||||
|
||||
@@ -20,7 +20,7 @@ Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the
|
||||
|
||||
- *Why does this rule exist?* - Since SQLite does not support parallel writes, each `DatabaseQueue` and `DatabasePool` makes sure application threads perform writes one by one, without overlap.
|
||||
|
||||
- *Practical advice* - An app that uses a single database will connect only once. A document-based app will connect each time a document is opened, and disconnect when the document is closed. See the [demo apps] in order to see how to setup a UIKit or SwiftUI application for a single database.
|
||||
- *Practical advice* - An app that uses a single database will connect only once. A document-based app will connect each time a document is opened, and disconnect when the document is closed. See the [demo apps] in order to see how to set up a UIKit or SwiftUI application for a single database.
|
||||
|
||||
- *What if you do not follow this rule?*
|
||||
|
||||
@@ -51,7 +51,7 @@ Alternatively, you can open an explicit transaction or savepoint: see <doc:Trans
|
||||
|
||||
- *Practical advice* - Take the time to identify the invariants of your database. Some of them can be enforced in the database schema itself, such as "all books must have a non-empty title", or "all books must have an author" (see <doc:DatabaseSchema>). Some invariants can only be enforced by transactions, such as "all account credits must have a matching debit", or "all authors must have at least one book".
|
||||
|
||||
- *What if you do not follow this rule?* - You will see broken database invariants, at runtime, or when your apps wakes up after a crash. These bugs corrupt user data, and are very difficult to fix.
|
||||
- *What if you do not follow this rule?* - You will see broken database invariants, at runtime, or when your app wakes up after a crash. These bugs corrupt user data, and are very difficult to fix.
|
||||
|
||||
|
||||
## Synchronous and Asynchronous Database Accesses
|
||||
@@ -101,7 +101,7 @@ try dbQueue.write { db in
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
The async database access methods honor task cancellation. Once an async Task is cancelled, reads and writes throw `CancellationError`, and any transaction is rollbacked.
|
||||
The async database access methods honor task cancellation. Once an async Task is cancelled, reads and writes throw `CancellationError`, and any transaction is rolled back.
|
||||
|
||||
See <doc:SwiftConcurrency> for more information about GRDB and Swift 6.
|
||||
|
||||
@@ -178,7 +178,7 @@ This enforces the immutability of the database during a read.
|
||||
|
||||
#### Non-Reentrancy
|
||||
|
||||
**Database accesses methods are not reentrant.**
|
||||
**Database access methods are not reentrant.**
|
||||
|
||||
This reduces the opportunities for deadlocks, and fosters the clear transaction boundaries of <doc:Concurrency#Rule-2:-Mind-your-transactions>.
|
||||
|
||||
@@ -202,7 +202,7 @@ Some applications need to relax this safety net, in order to achieve specific SQ
|
||||
|
||||
See ``DatabaseReader/unsafeReentrantRead(_:)``.
|
||||
|
||||
> Important: By using one of the methods above, you become responsible of the thread-safety of your application. Please understand the consequences of lifting each concurrency guarantee.
|
||||
> Important: By using one of the methods above, you become responsible for the thread-safety of your application. Please understand the consequences of lifting each concurrency guarantee.
|
||||
|
||||
Some concurrency guarantees can be restored at your convenience:
|
||||
|
||||
@@ -259,7 +259,7 @@ All you need is a little "concurrent thinking", based on those two basic facts:
|
||||
|
||||
Does this mean you can't rely on anything? Of course not:
|
||||
|
||||
- If you intend to display some database value on screen, use ``ValueObservation``: it always eventually notifies the latest state of the database. Your application won't display stale values for a long time: after the database has been changed on disk, the fresh value if fetched, and soon notified on the main thread where the screen can be updated.
|
||||
- If you intend to display some database value on screen, use ``ValueObservation``: it always eventually notifies the latest state of the database. Your application won't display stale values for a long time: after the database has been changed on disk, the fresh value is fetched, and soon notified on the main thread where the screen can be updated.
|
||||
|
||||
- As said above, the moment of truth is the next write access!
|
||||
|
||||
|
||||
@@ -51,9 +51,9 @@ if let dbPath {
|
||||
|
||||
> Tip: Regardless of the database location, it is recommended that you wrap the database file inside a dedicated directory. This directory will bundle the main database file and its related [SQLite temporary files](https://www.sqlite.org/tempfiles.html) together.
|
||||
>
|
||||
> The dedicated directory helps moving or deleting the whole database when needed: just move or delete the directory.
|
||||
> The dedicated directory helps move or delete the whole database when needed: just move or delete the directory.
|
||||
>
|
||||
> On iOS, the directory can be encrypted with [data protection](https://developer.apple.com/documentation/uikit/protecting_the_user_s_privacy/encrypting_your_app_s_files), in order to help securing all database files in one shot. When a database is protected, an application that runs in the background on a locked device won't be able to read or write from it. Instead, it will catch ``DatabaseError`` with code [`SQLITE_IOERR`](https://www.sqlite.org/rescode.html#ioerr) (10) "disk I/O error", or [`SQLITE_AUTH`](https://www.sqlite.org/rescode.html#auth) (23) "not authorized".
|
||||
> On iOS, the directory can be encrypted with [data protection](https://developer.apple.com/documentation/uikit/protecting_the_user_s_privacy/encrypting_your_app_s_files), in order to help secure all database files in one shot. When a database is protected, an application that runs in the background on a locked device won't be able to read or write from it. Instead, it will catch ``DatabaseError`` with code [`SQLITE_IOERR`](https://www.sqlite.org/rescode.html#ioerr) (10) "disk I/O error", or [`SQLITE_AUTH`](https://www.sqlite.org/rescode.html#auth) (23) "not authorized".
|
||||
|
||||
The sample code below creates or opens a database file inside its dedicated directory. On the first run, a new empty database file is created. On subsequent runs, the directory and database file already exist, so it just opens a connection:
|
||||
|
||||
|
||||
@@ -4,13 +4,13 @@ Observe database changes and transactions.
|
||||
|
||||
## Overview
|
||||
|
||||
**SQLite notifies its host application of changes performed to the database, as well of transaction commits and rollbacks.**
|
||||
**SQLite notifies its host application of changes performed to the database, as well as of transaction commits and rollbacks.**
|
||||
|
||||
GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways:
|
||||
|
||||
- ``ValueObservation``: Get notified when database values change.
|
||||
- ``DatabaseRegionObservation``: Get notified when a transaction impacts a database region.
|
||||
- ``Database/afterNextTransaction(onCommit:onRollback:)``: Handle transactions commits or rollbacks, one by one.
|
||||
- ``Database/afterNextTransaction(onCommit:onRollback:)``: Handle transaction commits or rollbacks, one by one.
|
||||
- ``TransactionObserver``: The low-level protocol that supports all database observation features.
|
||||
|
||||
## Topics
|
||||
|
||||
@@ -4,7 +4,7 @@ How to modify the database schema
|
||||
|
||||
## Overview
|
||||
|
||||
For modifying the database schema, prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
|
||||
For modifying the database schema, prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exists (when creating triggers, for example).
|
||||
|
||||
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ Recommendations for an ideal integration of the database schema with GRDB
|
||||
|
||||
## Overview
|
||||
|
||||
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
|
||||
Even though all schemas are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
|
||||
|
||||
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
|
||||
|
||||
@@ -139,7 +139,7 @@ try db.create(table: "player") { t in
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// The record type for the 'player' table'
|
||||
// The record type for the 'player' table
|
||||
struct Player: Codable {
|
||||
// Uniquely identifies a player.
|
||||
var rowid: Int64?
|
||||
@@ -214,7 +214,7 @@ struct Player: Identifiable {
|
||||
|
||||
## Unique keys should be supported by unique indexes
|
||||
|
||||
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
|
||||
Unique indexes make sure SQLite prevents the insertion of conflicting rows:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
|
||||
@@ -23,7 +23,7 @@ We'll address all of those challenges below.
|
||||
|
||||
## Use the WAL mode
|
||||
|
||||
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database because it allows multiple processes to access the database concurrently.
|
||||
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps share a database because it allows multiple processes to access the database concurrently.
|
||||
|
||||
It is also possible to use a ``DatabaseQueue``, with the `.wal` ``Configuration/journalMode``.
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ See <doc:DatabaseConnections>.
|
||||
|
||||
#### Tracing SQL Statements
|
||||
|
||||
You can setup a tracing function that prints out all executed SQL requests with ``prepareDatabase(_:)`` and ``Database/trace(options:_:)``:
|
||||
You can set up a tracing function that prints out all executed SQL requests with ``prepareDatabase(_:)`` and ``Database/trace(options:_:)``:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
|
||||
@@ -12,7 +12,7 @@ import GRDB
|
||||
let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
```
|
||||
|
||||
SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated.
|
||||
SQLite creates the database file if it does not already exist. The connection is closed when the database pool gets deallocated.
|
||||
|
||||
**A `DatabasePool` can be used from any thread.** The ``DatabaseWriter/write(_:)-76inz`` and ``DatabaseReader/read(_:)-3806d`` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:
|
||||
|
||||
@@ -42,7 +42,7 @@ let newPlayerCount = try dbPool.write { db -> Int in
|
||||
}
|
||||
```
|
||||
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rolled back, and the error is rethrown.
|
||||
|
||||
When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method, because several threads can perform reads in parallel.
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ let newPlayerCount = try dbQueue.write { db -> Int in
|
||||
}
|
||||
```
|
||||
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rolled back, and the error is rethrown.
|
||||
|
||||
When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method: it prevents any modification to the database.
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ A type that can convert itself into and out of a database value.
|
||||
|
||||
A `DatabaseValueConvertible` type supports conversion to and from database values (null, integers, doubles, strings, and blobs). `DatabaseValueConvertible` is adopted by `Bool`, `Int`, `String`, `Date`, etc.
|
||||
|
||||
> Note: Types that converts to and from multiple columns in a database row must not conform to the `DatabaseValueConvertible` protocol. Those types are called **record types**, and should conform to record protocols instead. See <doc:QueryInterface>.
|
||||
> Note: Types that convert to and from multiple columns in a database row must not conform to the `DatabaseValueConvertible` protocol. Those types are called **record types**, and should conform to record protocols instead. See <doc:QueryInterface>.
|
||||
|
||||
> Note: Standard collections `Array`, `Set`, and `Dictionary` do not conform to `DatabaseValueConvertible`. To store arrays, sets, or dictionaries in individual database values, wrap them as properties of `Codable` record types. They will automatically be stored as JSON objects and arrays. See <doc:QueryInterface>.
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ let player = try Player.fetchOne(selectStatement, arguments: ["Arthur"])
|
||||
|
||||
> Note: A prepared statement that has failed with an error can not be recovered. Create a new instance, or use a cached statement as described below.
|
||||
|
||||
> Tip: When you look after the best performance, take care about a difference between setting the arguments before execution, and setting the arguments at the moment of execution:
|
||||
> Tip: When you look for the best performance, take care about a difference between setting the arguments before execution, and setting the arguments at the moment of execution:
|
||||
>
|
||||
> ```swift
|
||||
> // First option
|
||||
@@ -190,7 +190,7 @@ let statements = try Array(db.allStatements(sql: """
|
||||
- ``validateArguments(_:)``
|
||||
- ``StatementArguments``
|
||||
|
||||
### Statement Informations
|
||||
### Statement Information
|
||||
|
||||
- ``columnCount``
|
||||
- ``columnNames``
|
||||
|
||||
@@ -129,7 +129,7 @@ let cancellable = observation
|
||||
// <- Here "Fresh value" has already been printed.
|
||||
```
|
||||
|
||||
The ``ValueObservationScheduler/async(onQueue:)`` scheduler asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial dispatch queue, because a concurrent one such as `DispachQueue.global(qos: .default)` would mess with the ordering of fresh value notifications:
|
||||
The ``ValueObservationScheduler/async(onQueue:)`` scheduler asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial dispatch queue, because a concurrent one such as `DispatchQueue.global(qos: .default)` would mess with the ordering of fresh value notifications:
|
||||
|
||||
```swift
|
||||
// Async scheduling notifies all values
|
||||
@@ -172,7 +172,7 @@ As described above, the `scheduling` argument controls the execution of the chan
|
||||
|
||||
- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the main actor, when the observation starts, so that the initial value can be notified immediately.
|
||||
|
||||
- With the default `.async` scheduling, the initial fetch is always performed asynchronouly. It never blocks the main thread.
|
||||
- With the default `.async` scheduling, the initial fetch is always performed asynchronously. It never blocks the main thread.
|
||||
|
||||
- By default, fresh values are fetched immediately after the database was changed. In particular, modifying the database on the main thread triggers a fetch on the main thread as well.
|
||||
|
||||
@@ -232,7 +232,7 @@ This ``tracking(region:_:fetch:)`` method lets you entirely separate the **obser
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
To have observations notify a fresh values after such an undetected change was performed, applications can take explicit action. For example, cancel and restart observations. Alternatively, call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
|
||||
To have observations notify fresh values after such an undetected change was performed, applications can take explicit action. For example, cancel and restart observations. Alternatively, call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -296,7 +296,7 @@ When needed, you can help GRDB optimize observations and reduce database content
|
||||
|
||||
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``tracking(regions:fetch:)`` or ``trackingConstantRegion(_:)`` methods. Make sure you read the documentation of those methods, or you might write an observation that misses some database changes.
|
||||
|
||||
**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility to create the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such a creating and dropping a dummy table).
|
||||
**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility to create the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such as creating and dropping a dummy table).
|
||||
|
||||
|
||||
## Topics
|
||||
|
||||
@@ -8,7 +8,7 @@ You can think of migrations as being 'versions' of the database. A database sche
|
||||
|
||||
GRDB can update the database schema along this timeline, bringing it from whatever point it is in the history to the latest version. When a user upgrades your application, only non-applied migrations are run.
|
||||
|
||||
You setup migrations in a ``DatabaseMigrator`` instance. For example:
|
||||
You set up migrations in a ``DatabaseMigrator`` instance. For example:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
@@ -74,7 +74,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
**Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by ``DatabaseMigrator/migrate(_:)``.
|
||||
**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.
|
||||
|
||||
@@ -110,7 +110,7 @@ migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
|
||||
}
|
||||
```
|
||||
|
||||
Note: migrations that run with `.immediate` foreign key checks can not be used to recreated database tables, as described below. When needed, define two migrations instead of one.
|
||||
Note: migrations that run with `.immediate` foreign key checks can not be used to recreate database tables, as described below. When needed, define two migrations instead of one.
|
||||
|
||||
#### How to Recreate a Database Table
|
||||
|
||||
@@ -133,7 +133,7 @@ migrator.registerMigration("Add NOT NULL check on author.name") { db in
|
||||
|
||||
The detailed sequence of operations for recreating a database table from a migration is:
|
||||
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in steps 6 below. One way to do this is to run the following statement and examine the output in the console:
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in step 6 below. One way to do this is to run the following statement and examine the output in the console:
|
||||
|
||||
```swift
|
||||
try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'")
|
||||
@@ -193,7 +193,7 @@ migrator.registerMigration("Create authors") { db in
|
||||
}
|
||||
```
|
||||
|
||||
In other words, migrations should talk to the database, only to the database, and use the database language. This makes sure the Swift code of any given migrations will never have to change in the future.
|
||||
In other words, migrations should talk to the database, only to the database, and use the database language. This makes sure the Swift code of any given migration will never have to change in the future.
|
||||
|
||||
Migrations and the rest of the application code do not live at the same "moment". Migrations describe the past states of the database, while the rest of the application code targets the latest one only. This difference is the reason why **migrations should not depend on application types.**
|
||||
|
||||
@@ -222,7 +222,7 @@ migrator.eraseDatabaseOnSchemaChange = true
|
||||
|
||||
By default, each migration temporarily disables foreign keys, and performs a full check of all foreign keys in the database before it is committed on disk.
|
||||
|
||||
When the database becomes very big, those checks may have a noticeable impact on migration performances. You'll know this by profiling migrations, and looking for the time spent in the `checkForeignKeys` method.
|
||||
When the database becomes very big, those checks may have a noticeable impact on migration performance. You'll know this by profiling migrations, and looking for the time spent in the `checkForeignKeys` method.
|
||||
|
||||
You can make those migrations faster, but this requires a little care.
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ Thanks to this database schema, the application will always process *consistent
|
||||
|
||||
> Tip: **A local SQLite database is not a JSON payload loaded from a remote server.**
|
||||
>
|
||||
> The JSON format and content can not be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustable. A relational database such as SQLite guarantees the quality of users data, as long as enough energy is put in the proper definition of the database schema.
|
||||
> The JSON format and content can not be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustable. A relational database such as SQLite guarantees the quality of users' data, as long as enough energy is put in the proper definition of the database schema.
|
||||
|
||||
> Tip: **Plan early for future versions of your application**: use <doc:Migrations>.
|
||||
|
||||
@@ -138,7 +138,7 @@ let books = try dbQueue.read { db in
|
||||
>
|
||||
> There are exceptions to this rule.
|
||||
>
|
||||
> For example, the `id` column is never NULL in the database. And yet, `Author` as an optional `id` property. That is because we want to create instances of `Author` before they could be inserted in the database, and be assigned an auto-incremented id. If the `id` property was not optional, the `Author` type could not profit from auto-incremented ids!
|
||||
> For example, the `id` column is never NULL in the database. And yet, `Author` has an optional `id` property. That is because we want to create instances of `Author` before they could be inserted in the database, and be assigned an auto-incremented id. If the `id` property was not optional, the `Author` type could not profit from auto-incremented ids!
|
||||
>
|
||||
> Another exception to this rule is described in <doc:RecordTimestamps>, where the creation date of a record is never NULL in the database, but optional in the Swift type.
|
||||
|
||||
@@ -220,7 +220,7 @@ let novels = try dbQueue.read { db in
|
||||
|
||||
#### Second Example: GPS Coordinates
|
||||
|
||||
GPS coordinates can be stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
|
||||
GPS coordinates can be stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinates is a single `CLLocationCoordinate2D` struct.
|
||||
|
||||
When this happens, keep column properties private, and provide sensible accessors instead:
|
||||
|
||||
@@ -408,7 +408,7 @@ let names: Set<String> = try Author.all()
|
||||
|
||||
## Associations
|
||||
|
||||
[Associations] help navigating from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books:
|
||||
[Associations] help navigate from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books:
|
||||
|
||||
```swift
|
||||
extension Book {
|
||||
@@ -517,7 +517,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`.
|
||||
|
||||
Those record type 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`).
|
||||
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`).
|
||||
|
||||
For more information about associations, see the [Associations] guide.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Some applications want to record creation and modification dates of database rec
|
||||
|
||||
> Note: Creation and modification dates can be automatically handled by [SQLite triggers](https://www.sqlite.org/lang_createtrigger.html). We'll explore a different technique, though.
|
||||
>
|
||||
> This is not an advice against triggers, and you won't feel hindered in any way if you prefer to use triggers. Still, consider:
|
||||
> This is not advice against triggers, and you won't feel hindered in any way if you prefer to use triggers. Still, consider:
|
||||
>
|
||||
> - A trigger does not suffer any exception, when some applications eventually want to fine-tune timestamps, or to perform migrations without touching timestamps.
|
||||
> - The current time, according to SQLite, is not guaranteed to be constant in a given transaction. This may create undesired timestamp variations. We'll see below how GRDB provides a date that is constant at any point during a transaction.
|
||||
|
||||
@@ -16,7 +16,7 @@ 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 shipping 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 less 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.
|
||||
|
||||
|
||||
@@ -149,7 +149,7 @@ let observation = ValueObservation.tracking { db in
|
||||
|
||||
The solution is to have the record type conform to `Sendable`.
|
||||
|
||||
Since classes are difficult to make `Sendable`, the easiest way to is to replace classes with structs composed of `Sendable` properties:
|
||||
Since classes are difficult to make `Sendable`, the easiest way is to replace classes with structs composed of `Sendable` properties:
|
||||
|
||||
```swift
|
||||
// This struct is Sendable
|
||||
@@ -172,7 +172,7 @@ You do not need to perform this refactoring right away: you can compile your app
|
||||
|
||||
- **Question: I need a hierarchy of record classes because I use inheritance.**
|
||||
|
||||
It should be possible to refactor the class hiearchy with Swift protocols. See <doc:RecordTimestamps> for a practical example. Protocols make it possible to define records as structs.
|
||||
It should be possible to refactor the class hierarchy with Swift protocols. See <doc:RecordTimestamps> for a practical example. Protocols make it possible to define records as structs.
|
||||
|
||||
- **Question: I use the `@Observable` macro for my record types, and this macro requires a class.**
|
||||
|
||||
@@ -212,7 +212,7 @@ Synchronous database accesses are handy. They avoid undesired delays, flashes of
|
||||
|
||||
Performing synchronous accesses from Swift Concurrency tasks is not incorrect.
|
||||
|
||||
Some people recommend to avoid performing long blocking jobs on the cooperative thread pool, so you might want to follow this advice, and prefer to always `await` for the database in Swift tasks. In many occasions, the compiler will help you. For example, in the sample code below, the compiler requires the `await` keyword:
|
||||
Some people recommend avoiding long blocking jobs on the cooperative thread pool, so you might want to follow this advice, and prefer to always `await` for the database in Swift tasks. In many occasions, the compiler will help you. For example, in the sample code below, the compiler requires the `await` keyword:
|
||||
|
||||
```swift
|
||||
func fetchPlayers() async throws -> [Player] {
|
||||
|
||||
@@ -126,7 +126,7 @@ try dbQueue.writeWithoutTransaction { db in
|
||||
}
|
||||
```
|
||||
|
||||
If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the transaction method. If the transaction closure returns `.rollback` instead of `.commit`, the transaction is also rollbacked, but no error is thrown.
|
||||
If an error is thrown from the transaction block, the transaction is rolled back and the error is rethrown by the transaction method. If the transaction closure returns `.rollback` instead of `.commit`, the transaction is also rolled back, but no error is thrown.
|
||||
|
||||
Full manual transaction management is also possible:
|
||||
|
||||
@@ -142,7 +142,7 @@ try dbQueue.writeWithoutTransaction { db
|
||||
}
|
||||
```
|
||||
|
||||
Make sure all transactions opened from a database access are committed or rollbacked 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 opened transaction:
|
||||
|
||||
```swift
|
||||
// fatal error: A transaction has been left
|
||||
@@ -179,7 +179,7 @@ func myCriticalMethod(_ db: Database) throws {
|
||||
|
||||
## Savepoints
|
||||
|
||||
**Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:**
|
||||
**Statements grouped in a savepoint can be rolled back without invalidating a whole transaction:**
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -194,7 +194,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If the savepoint closure returns `.rollback` instead of `.commit`, the savepoint is also rollbacked, but no error is thrown.
|
||||
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:
|
||||
|
||||
@@ -219,9 +219,9 @@ SQLite savepoints are more than nested transactions, though. For advanced uses,
|
||||
|
||||
SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive.
|
||||
|
||||
By default, GRDB opens DEFERRED transaction for reads, and IMMEDIATE transactions for writes.
|
||||
By default, GRDB opens DEFERRED transactions for reads, and IMMEDIATE transactions for writes.
|
||||
|
||||
The transaction kind can be chosen for individual transaction:
|
||||
The transaction kind can be chosen for individual transactions:
|
||||
|
||||
```swift
|
||||
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
|
||||
@@ -29,7 +29,7 @@ This article explains how to solve those errors:
|
||||
> important: GRDB is impacted by some SQLite limitations regarding INSTEAD OF triggers:
|
||||
>
|
||||
> - **Auto-incremented primary keys are not supported.** To be precise, SQLite won't expose the rowid of rows inserted via an INSTEAD OF trigger, so GRDB won't know the id of newly inserted rows. This has various nefarious consequences—see for example the important notice in the ``MutablePersistableRecord/didInsert(_:)`` callback. For more information, check this [SQLite forum thread](https://sqlite.org/forum/forumpost/707e7ed932).
|
||||
> - **INSTEAD OF triggers and the RETURNING clause do not play well together.** Those are SQLite bugs. All GRDB record methods with `andFetch` in their name may return unexpected or wrong results, depending on the SQLite version. For example, the SQLite version that ships with iOS 18 has bugs, and even more in iOS 17. If you intend to use the `RETURNING` clause, it is recommended that you write tests and run them in various target operation systems.
|
||||
> - **INSTEAD OF triggers and the RETURNING clause do not play well together.** Those are SQLite bugs. All GRDB record methods with `andFetch` in their name may return unexpected or wrong results, depending on the SQLite version. For example, the SQLite version that ships with iOS 18 has bugs, and even more in iOS 17. If you intend to use the `RETURNING` clause, it is recommended that you write tests and run them in various target operating systems.
|
||||
|
||||
## Preliminary Setup
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ extension Database {
|
||||
/// - stableOrder: A boolean value that controls the ordering of
|
||||
/// rows fetched from views. If false (the default), rows are
|
||||
/// printed in the order specified by the view (which may be
|
||||
/// undefined). It true, outputted rows are always printed in the
|
||||
/// undefined). If true, outputted rows are always printed in the
|
||||
/// same stable order. The purpose of this stable order is to make
|
||||
/// the output suitable for testing.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
|
||||
@@ -75,7 +75,7 @@ extension DatabaseReader {
|
||||
/// - stableOrder: A boolean value that controls the ordering of
|
||||
/// rows fetched from views. If false (the default), rows are
|
||||
/// printed in the order specified by the view (which may be
|
||||
/// undefined). It true, outputted rows are always printed in the
|
||||
/// undefined). If true, outputted rows are always printed in the
|
||||
/// same stable order. The purpose of this stable order is to make
|
||||
/// the output suitable for testing.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
|
||||
@@ -43,7 +43,7 @@ public struct JSONDumpFormat: Sendable {
|
||||
/// The default `JSONEncoder` for database values.
|
||||
///
|
||||
/// It is configured so that blob values (`Data`) are encoded in the
|
||||
/// base64 format, and Non-conforming floats are encoded as "inf",
|
||||
/// base64 format, and non-conforming floats are encoded as "inf",
|
||||
/// "-inf" and "nan".
|
||||
///
|
||||
/// It uses the output formatting option
|
||||
@@ -72,7 +72,7 @@ public struct JSONDumpFormat: Sendable {
|
||||
/// Creates a `JSONDumpFormat`.
|
||||
///
|
||||
/// - Parameter encoder: The JSONEncoder that formats individual
|
||||
/// database values. If the outputFormatting` options contain
|
||||
/// database values. If the `outputFormatting` options contain
|
||||
/// `.prettyPrinted`, the printed array has one value per line.
|
||||
public init(encoder: JSONEncoder = JSONDumpFormat.defaultEncoder) {
|
||||
self.encoder = encoder
|
||||
@@ -203,7 +203,7 @@ extension DumpFormat where Self == JSONDumpFormat {
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter encoder: The JSONEncoder that formats individual
|
||||
/// database values. If the outputFormatting` options contain
|
||||
/// database values. If the `outputFormatting` options contain
|
||||
/// `.prettyPrinted`, the printed array has one value per line.
|
||||
public static func json(encoder: JSONEncoder = JSONDumpFormat.defaultEncoder) -> Self {
|
||||
JSONDumpFormat(encoder: encoder)
|
||||
|
||||
+1
-1
@@ -139,7 +139,7 @@ extension FTS3: VirtualTableModule {
|
||||
public func database(_ db: Database, didCreate tableName: String, using definition: FTS3TableDefinition) { }
|
||||
}
|
||||
|
||||
/// A `FTS3TableDefinition` lets you define the components of an FTS3
|
||||
/// An `FTS3TableDefinition` lets you define the components of an FTS3
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
|
||||
+2
-2
@@ -155,7 +155,7 @@ extension FTS4: VirtualTableModule {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `FTS4TableDefinition` lets you define the components of an FTS4
|
||||
/// An `FTS4TableDefinition` lets you define the components of an FTS4
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
@@ -275,7 +275,7 @@ public final class FTS4TableDefinition {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - returns: A ``FTS4ColumnDefinition`` that allows you to refine the
|
||||
/// - returns: An ``FTS4ColumnDefinition`` that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func column(_ name: String) -> FTS4ColumnDefinition {
|
||||
|
||||
+2
-2
@@ -283,7 +283,7 @@ extension FTS5: VirtualTableModule {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `FTS5TableDefinition` lets you define the components of an FTS5
|
||||
/// An `FTS5TableDefinition` lets you define the components of an FTS5
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
@@ -426,7 +426,7 @@ public final class FTS5TableDefinition {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - returns: A ``FTS5ColumnDefinition`` that allows you to refine the
|
||||
/// - returns: An ``FTS5ColumnDefinition`` that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func column(_ name: String) -> FTS5ColumnDefinition {
|
||||
|
||||
@@ -147,7 +147,7 @@ extension FTS5Tokenizer {
|
||||
/// - parameter tokenization: The reason why tokenization is requested:
|
||||
/// - .document: Tokenize like a document being inserted into an FTS table.
|
||||
/// - .query: Tokenize like the search pattern of the MATCH operator.
|
||||
/// - parameter tokenizer: A FTS5TokenizerDescriptor such as .ascii()
|
||||
/// - parameter tokenizer: An FTS5TokenizerDescriptor such as .ascii()
|
||||
private func tokenize(_ string: String, for tokenization: FTS5Tokenization)
|
||||
throws -> [(token: String, flags: FTS5TokenFlags)]
|
||||
{
|
||||
|
||||
@@ -65,7 +65,7 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When implementing the accept method, there are a two rules
|
||||
/// When implementing the accept method, there are two rules
|
||||
/// to observe:
|
||||
///
|
||||
/// 1. Errors thrown by the tokenCallback function must not be caught.
|
||||
|
||||
@@ -80,7 +80,7 @@ public struct JSONColumn: ColumnExpression, SQLJSONExpressible, Sendable {
|
||||
|
||||
/// Creates a `JSONColumn` given its name.
|
||||
///
|
||||
/// The name should be unqualified, such as `"score"`. Qualified name such
|
||||
/// The name should be unqualified, such as `"score"`. Qualified names such
|
||||
/// as `"player.score"` are unsupported.
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
|
||||
@@ -183,7 +183,7 @@ extension SQLJSONExpressible {
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
|
||||
/// or an JSON object field label, or an array index.
|
||||
/// or a JSON object field label, or an array index.
|
||||
public subscript(_ path: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.jsonExtractSQL, sqlExpression, path.sqlExpression)
|
||||
}
|
||||
@@ -273,7 +273,7 @@ extension SQLJSONExpressible {
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
|
||||
/// or an JSON object field label, or an array index.
|
||||
/// or a JSON object field label, or an array index.
|
||||
public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.jsonExtractJSON, sqlExpression, path.sqlExpression)
|
||||
}
|
||||
@@ -307,7 +307,7 @@ extension SQLJSONExpressible {
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
|
||||
/// or an JSON object field label, or an array index.
|
||||
/// or a JSON object field label, or an array index.
|
||||
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
|
||||
public subscript(_ path: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.jsonExtractSQL, sqlExpression, path.sqlExpression)
|
||||
@@ -400,7 +400,7 @@ extension SQLJSONExpressible {
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
|
||||
/// or an JSON object field label, or an array index.
|
||||
/// or a JSON object field label, or an array index.
|
||||
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
|
||||
public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.jsonExtractJSON, sqlExpression, path.sqlExpression)
|
||||
|
||||
@@ -46,7 +46,7 @@ import Foundation
|
||||
///
|
||||
/// - ``hasSchemaChanges(_:)``
|
||||
public struct DatabaseMigrator: Sendable {
|
||||
/// Controls how a migration handle foreign keys constraints.
|
||||
/// Controls how a migration handles foreign key constraints.
|
||||
public enum ForeignKeyChecks: Sendable {
|
||||
/// The migration runs with disabled foreign keys.
|
||||
///
|
||||
@@ -153,7 +153,7 @@ public struct DatabaseMigrator: Sendable {
|
||||
/// - warning: Before using this unsafe method, try to register your
|
||||
/// migrations with the `foreignKeyChecks: .immediate` option, _if
|
||||
/// possible_, as in the example above. This will enhance migration
|
||||
/// performances, while preserving the database integrity guarantee.
|
||||
/// performance, while preserving the database integrity guarantee.
|
||||
public func disablingDeferredForeignKeyChecks() -> DatabaseMigrator {
|
||||
with { $0.defersForeignKeyChecks = false }
|
||||
}
|
||||
@@ -178,7 +178,7 @@ public struct DatabaseMigrator: Sendable {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rollbacked, migrations are aborted, and the
|
||||
/// error, the transaction is rolled back, migrations are aborted, and the
|
||||
/// error is thrown by the migrating method.
|
||||
///
|
||||
/// By default, database operations run with disabled foreign keys, and
|
||||
@@ -208,7 +208,7 @@ public struct DatabaseMigrator: Sendable {
|
||||
/// does not perform schema changes described in
|
||||
/// <https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes>
|
||||
/// - migrate: A closure that performs database operations.
|
||||
/// - precondition: No migration with the same identifier as already
|
||||
/// - precondition: No migration with the same identifier has already
|
||||
/// been registered.
|
||||
public mutating func registerMigration(
|
||||
_ identifier: String,
|
||||
@@ -308,7 +308,7 @@ public struct DatabaseMigrator: Sendable {
|
||||
/// first argument is a database connection. The second argument
|
||||
/// is the set of previous migrations that has been applied when
|
||||
/// the merged migration runs.
|
||||
/// - precondition: No migration with the same identifier as already
|
||||
/// - precondition: No migration with the same identifier has already
|
||||
/// been registered.
|
||||
public mutating func registerMigration(
|
||||
_ identifier: String,
|
||||
@@ -672,7 +672,7 @@ extension DatabaseMigrator {
|
||||
/// The database is not accessed until subscription. Value and completion
|
||||
/// are published on `scheduler` (the main dispatch queue by default).
|
||||
///
|
||||
/// - parameter writer: A DatabaseWriter.
|
||||
/// - parameter writer: A DatabaseWriter
|
||||
/// where migrations should apply.
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
public func migratePublisher(
|
||||
|
||||
@@ -669,7 +669,7 @@ public struct AssociationAggregate<RowDecoder> {
|
||||
///
|
||||
/// - We don't know yet if the aggregated expression will be used in the
|
||||
/// SQL selection, or in the HAVING clause.
|
||||
/// - It helps implementing aggregate operators such as `&&`, `+`, etc.
|
||||
/// - It helps implement aggregate operators such as `&&`, `+`, etc.
|
||||
func prepare(_ request: inout some DerivableRequest<RowDecoder>) -> SQLExpression {
|
||||
preparation.prepare(&request)
|
||||
}
|
||||
@@ -811,7 +811,7 @@ private class CombinePreparation<RowDecoder>: AssociationAggregatePreparation<Ro
|
||||
}
|
||||
}
|
||||
|
||||
/// Combines the expression of two aggregates.
|
||||
/// Combines the expressions of two aggregates.
|
||||
private func combine<RowDecoder>(
|
||||
_ lhs: AssociationAggregate<RowDecoder>,
|
||||
_ rhs: AssociationAggregate<RowDecoder>,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// Thes `BelongsToAssociation` sets up a one-to-one connection from a record
|
||||
/// 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
|
||||
/// "belongs to" an instance of the other record.
|
||||
///
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
/// ```
|
||||
///
|
||||
/// 1. The author table has a primary key.
|
||||
/// 2. The `book.authorId` column is used to link a book to the author it
|
||||
/// belongs to. This column is indexed in order to ease the selection of
|
||||
/// an author's books. A foreign key is defined from `book.authorId`
|
||||
/// column to `authors.id`, so that SQLite guarantees that no book refers
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// The `HasOneAssociation` indicates a one-to-one connection between two
|
||||
/// record types, such as each instance of the declaring record "has one"
|
||||
/// instances of the other record.
|
||||
/// instance of the other record.
|
||||
///
|
||||
/// For example, if your application has one database table for countries, and
|
||||
/// another for their demographic profiles, you'd declare the association
|
||||
@@ -49,9 +49,9 @@
|
||||
/// 3. Make the `demographics.countryCode` column not null if you want SQLite to
|
||||
/// guarantee that all profiles are linked to a country.
|
||||
/// 4. Create a unique index on the `demographics.countryCode` column in order
|
||||
/// to guarantee the unicity of any country's demographics.
|
||||
/// to guarantee the uniqueness of any country's demographics.
|
||||
///
|
||||
/// The example above uses a string primary for the country table. But generally
|
||||
/// The example above uses a string primary key for the country table. But generally
|
||||
/// speaking, all primary keys are supported.
|
||||
///
|
||||
/// If the database schema does not define foreign keys between tables, you can
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// The `JoinAssociation` joins common table expression to regular
|
||||
/// The `JoinAssociation` joins common table expressions to regular
|
||||
/// tables or other common table expressions.
|
||||
public struct JoinAssociation<Origin, Destination> {
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//
|
||||
// It wraps an SQLQuery, and has an attached type.
|
||||
//
|
||||
// The attached RowDecoder type helps decoding raw database values:
|
||||
// The attached RowDecoder type helps decode raw database values:
|
||||
//
|
||||
// try dbQueue.read { db in
|
||||
// try playerRequest.fetchAll(db) // [Player]
|
||||
@@ -600,7 +600,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
|
||||
// MARK: - Check Existence
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
/// Returns whether the requests does not match any row in the database.
|
||||
/// Returns whether the request does not match any row in the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -1211,7 +1211,7 @@ extension QueryInterfaceRequest {
|
||||
/// (must not be empty).
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The results of `select` and `assignments` results
|
||||
/// - precondition: The results of `select` and `assignments`
|
||||
/// are not empty.
|
||||
public func updateAndFetchStatement(
|
||||
_ db: Database,
|
||||
@@ -1358,7 +1358,7 @@ extension QueryInterfaceRequest {
|
||||
return try RowDecoder.fetchCursor(statement)
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the array of
|
||||
/// Executes an `UPDATE RETURNING` statement and returns the array of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1397,7 +1397,7 @@ extension QueryInterfaceRequest {
|
||||
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the array of
|
||||
/// Executes an `UPDATE RETURNING` statement and returns the array of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1429,7 +1429,7 @@ extension QueryInterfaceRequest {
|
||||
try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the set of
|
||||
/// Executes an `UPDATE RETURNING` statement and returns the set of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1468,7 +1468,7 @@ extension QueryInterfaceRequest {
|
||||
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the set of
|
||||
/// Executes an `UPDATE RETURNING` statement and returns the set of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1534,7 +1534,7 @@ extension QueryInterfaceRequest {
|
||||
/// (must not be empty).
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The results of `select` and `assignments` results
|
||||
/// - precondition: The results of `select` and `assignments`
|
||||
/// are not empty.
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func updateAndFetchStatement(
|
||||
@@ -1685,7 +1685,7 @@ extension QueryInterfaceRequest {
|
||||
return try RowDecoder.fetchCursor(statement)
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the array of
|
||||
/// Executes an `UPDATE RETURNING` statement and returns the array of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1725,7 +1725,7 @@ extension QueryInterfaceRequest {
|
||||
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the array of
|
||||
/// Executes an `UPDATE RETURNING` statement and returns the array of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1758,7 +1758,7 @@ extension QueryInterfaceRequest {
|
||||
try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the set of
|
||||
/// Executes an `UPDATE RETURNING` statement and returns the set of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1798,7 +1798,7 @@ extension QueryInterfaceRequest {
|
||||
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the set of
|
||||
/// Executes an `UPDATE RETURNING` statement and returns the set of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -2370,7 +2370,7 @@ throws -> DatabaseRegion
|
||||
|
||||
extension [Row] {
|
||||
/// - precondition: Columns all exist in all rows. All rows have the same
|
||||
/// columnns, in the same order.
|
||||
/// columns, in the same order.
|
||||
fileprivate func grouped(byDatabaseValuesOnColumns columns: [String]) -> [[DatabaseValue]: [Row]] {
|
||||
guard let firstRow = first else {
|
||||
return [:]
|
||||
|
||||
@@ -44,7 +44,7 @@ public protocol SelectionRequest {
|
||||
///
|
||||
/// The `selection` parameter is a closure that accepts a database
|
||||
/// connection and returns an array of result columns. It is evaluated when
|
||||
/// the request has an access to the database, and can perform database
|
||||
/// the request has access to the database, and can perform database
|
||||
/// requests in order to build its result.
|
||||
///
|
||||
/// For example:
|
||||
@@ -75,7 +75,7 @@ public protocol SelectionRequest {
|
||||
///
|
||||
/// The `selection` parameter is a closure that accepts a database
|
||||
/// connection and returns an array of result columns. It is evaluated when
|
||||
/// the request has an access to the database, and can perform database
|
||||
/// the request has access to the database, and can perform database
|
||||
/// requests in order to build its result.
|
||||
///
|
||||
/// For example:
|
||||
@@ -362,7 +362,7 @@ public protocol FilteredRequest {
|
||||
///
|
||||
/// The `predicate` parameter is a closure that accepts a database
|
||||
/// connection and returns a boolean SQL expression. It is evaluated when
|
||||
/// the request has an access to the database, and can perform database
|
||||
/// the request has access to the database, and can perform database
|
||||
/// requests in order to build its result.
|
||||
///
|
||||
/// For example:
|
||||
@@ -996,7 +996,7 @@ public protocol AggregatingRequest {
|
||||
///
|
||||
/// The `expressions` parameter is a closure that accepts a database
|
||||
/// connection and returns an array of grouping SQL expressions. It is
|
||||
/// evaluated when the request has an access to the database, and can
|
||||
/// evaluated when the request has access to the database, and can
|
||||
/// perform database requests in order to build its result.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1022,7 +1022,7 @@ public protocol AggregatingRequest {
|
||||
///
|
||||
/// The `predicate` parameter is a closure that accepts a database
|
||||
/// connection and returns a boolean SQL expression. It is evaluated when
|
||||
/// the request has an access to the database, and can perform database
|
||||
/// the request has access to the database, and can perform database
|
||||
/// requests in order to build its result.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1274,7 +1274,7 @@ public protocol OrderedRequest {
|
||||
///
|
||||
/// The `orderings` parameter is a closure that accepts a database
|
||||
/// connection and returns an array of SQL ordering terms. It is evaluated
|
||||
/// when the request has an access to the database, and can perform database
|
||||
/// when the request has access to the database, and can perform database
|
||||
/// requests in order to build its result.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1344,7 +1344,7 @@ public protocol OrderedRequest {
|
||||
|
||||
/// Returns a request with a stable order.
|
||||
///
|
||||
/// The returned request lifts ordering ambiguities and always return
|
||||
/// The returned request lifts ordering ambiguities and always returns
|
||||
/// its results in the same order.
|
||||
///
|
||||
/// The purpose of this method is to make requests testable.
|
||||
|
||||
@@ -131,7 +131,7 @@ public struct Column: Sendable {
|
||||
|
||||
/// Creates a `Column` given its name.
|
||||
///
|
||||
/// The name should be unqualified, such as `"score"`. Qualified name such
|
||||
/// The name should be unqualified, such as `"score"`. Qualified names such
|
||||
/// as `"player.score"` are unsupported.
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
/// let countryRequest = Country.filter(key: "FR")
|
||||
///
|
||||
/// Both need a database connection in order to introspect the database schema,
|
||||
/// find the primary key of both table, and generate the correct SQL:
|
||||
/// find the primary key of both tables, and generate the correct SQL:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // SELECT * FROM player WHERE id = 1
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
/// // JOIN destination ON ...
|
||||
/// Origin.including(required: association)
|
||||
///
|
||||
/// For direct associations such as BelongTo or HasMany, the chain contains a
|
||||
/// For direct associations such as BelongsTo or HasMany, the chain contains a
|
||||
/// single element, the "destination", without intermediate step:
|
||||
///
|
||||
/// // "Origin" belongsTo "destination":
|
||||
@@ -229,7 +229,7 @@ enum SQLAssociationKey: Refinable {
|
||||
/// row.scopes["author"] // singularized "authors" table name
|
||||
case inflected(String)
|
||||
|
||||
/// A key that is inflected in plural contexts, but stricly honors
|
||||
/// A key that is inflected in plural contexts, but strictly honors
|
||||
/// user-provided name in singular contexts.
|
||||
///
|
||||
/// For example:
|
||||
@@ -243,7 +243,7 @@ enum SQLAssociationKey: Refinable {
|
||||
/// row.scopes["demographics"] // not singularized
|
||||
case fixedSingular(String)
|
||||
|
||||
/// A key that is inflected in singular contexts, but stricly honors
|
||||
/// A key that is inflected in singular contexts, but strictly honors
|
||||
/// user-provided name in plural contexts.
|
||||
/// See .inflected and .fixedSingular for some context.
|
||||
case fixedPlural(String)
|
||||
|
||||
@@ -91,7 +91,7 @@ extension SQLCollection {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an expression that check whether the collection contains
|
||||
/// Returns an expression that checks whether the collection contains
|
||||
/// the expression.
|
||||
func contains(_ value: SQLExpression) -> SQLExpression {
|
||||
switch impl {
|
||||
|
||||
@@ -141,7 +141,7 @@ public struct SQLExpression: Sendable {
|
||||
/// <expression> NOT IN <collection>
|
||||
indirect case `in`(SQLExpression, SQLCollection, isNegated: Bool)
|
||||
|
||||
/// An unary operator.
|
||||
/// A unary operator.
|
||||
///
|
||||
/// -<expression>
|
||||
indirect case unary(UnaryOperator, SQLExpression)
|
||||
@@ -343,9 +343,9 @@ public struct SQLExpression: Sendable {
|
||||
|
||||
/// If true, (a • b) • c is strictly equal to a • (b • c).
|
||||
///
|
||||
/// `AND`, `OR`, `||` (concat), `&`, `|` are stricly associative.
|
||||
/// `AND`, `OR`, `||` (concat), `&`, `|` are strictly associative.
|
||||
///
|
||||
/// `+` and `*` are not stricly associative when applied to floating
|
||||
/// `+` and `*` are not strictly associative when applied to floating
|
||||
/// point values.
|
||||
let isStrictlyAssociative: Bool
|
||||
|
||||
@@ -588,7 +588,7 @@ public struct SQLExpression: Sendable {
|
||||
/// The SQL operator
|
||||
let sql: String
|
||||
|
||||
/// Creates an unary operator.
|
||||
/// Creates a unary operator.
|
||||
init(_ sql: String) {
|
||||
self.sql = sql
|
||||
}
|
||||
@@ -820,7 +820,7 @@ extension SQLExpression {
|
||||
self.init(impl: .in(expression, collection, isNegated: isNegated))
|
||||
}
|
||||
|
||||
/// An unary operator.
|
||||
/// A unary operator.
|
||||
///
|
||||
/// -<expression>
|
||||
static func unary(_ op: UnaryOperator, _ expression: SQLExpression) -> Self {
|
||||
@@ -1271,7 +1271,7 @@ extension SQLExpression {
|
||||
/// - parameter context: An SQL generation context which accepts
|
||||
/// statement arguments.
|
||||
/// - parameter wrappedInParenthesis: If true, the returned SQL should be
|
||||
/// wrapped inside parenthesis.
|
||||
/// wrapped inside parentheses.
|
||||
func sql(_ context: SQLGenerationContext, wrappedInParenthesis: Bool = false) throws -> String {
|
||||
switch impl {
|
||||
case let .column(name):
|
||||
@@ -2078,7 +2078,7 @@ extension SQLExpression {
|
||||
///
|
||||
/// A false value does not provide any information.
|
||||
///
|
||||
/// For examples:
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // isJSONValue is true:
|
||||
|
||||
@@ -143,7 +143,7 @@ typealias ForeignKeyMapping = [(origin: String, destination: String)]
|
||||
typealias JoinMapping = [(left: String, right: String)]
|
||||
|
||||
extension ForeignKeyMapping {
|
||||
/// Orient the foreign key mapping for a SQL join.
|
||||
/// Orient the foreign key mapping for an SQL join.
|
||||
///
|
||||
/// - parameter originIsLeft: Whether the table at the origin of a
|
||||
/// foreign key is on the left of a JOIN clause.
|
||||
|
||||
@@ -587,7 +587,7 @@ public func julianDay(_ value: some SQLSpecificExpressible, _ modifiers: SQLDate
|
||||
/// dateTime(Column("date"), .day(1))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation:<https://www.sqlite.org/lang_datefunc.html>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_datefunc.html>
|
||||
public func dateTime(_ value: some SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
|
||||
.function("DATETIME", [value.sqlExpression] + modifiers.map(\.sqlExpression))
|
||||
}
|
||||
@@ -26,7 +26,7 @@ public struct SQLOrdering: Sendable {
|
||||
/// ORDER BY score ASC
|
||||
case asc(SQLExpression)
|
||||
|
||||
/// An descending expression
|
||||
/// A descending expression
|
||||
///
|
||||
/// ORDER BY score DESC
|
||||
case desc(SQLExpression)
|
||||
|
||||
@@ -21,13 +21,13 @@
|
||||
///
|
||||
/// // SELECT * FROM country ORDER BY code
|
||||
/// // ~~~~~~~~~~~~~
|
||||
/// // primary key infered from the database schema
|
||||
/// // primary key inferred from the database schema
|
||||
/// Country.orderByPrimaryKey()
|
||||
///
|
||||
/// ## Children
|
||||
///
|
||||
/// Relations have children. A child is a link to another relation, and
|
||||
/// provide support for joins and prefetched relations.
|
||||
/// provides support for joins and prefetched relations.
|
||||
///
|
||||
/// Relations and their children constitute a tree of relations, which the user
|
||||
/// builds with associations:
|
||||
@@ -184,7 +184,7 @@ struct SQLRelation: Sendable {
|
||||
}
|
||||
|
||||
extension SQLRelation {
|
||||
/// Convenience factory methods which selects all rows from a table.
|
||||
/// Convenience factory methods which select all rows from a table.
|
||||
static func all(
|
||||
fromTable tableName: String,
|
||||
selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] })
|
||||
@@ -793,7 +793,7 @@ extension SQLRelation {
|
||||
/// // ~~~~~~~~~~~~~~~~~~~~~~
|
||||
/// Author.filter(...).including(all: Author.books)
|
||||
///
|
||||
/// Conditions help fetching associated records:
|
||||
/// Conditions help fetch associated records:
|
||||
///
|
||||
/// // SELECT * FROM book WHERE author.id = 1
|
||||
/// // ~~~~~~~~~~~~~
|
||||
@@ -872,7 +872,7 @@ struct SQLForeignKeyCondition: Equatable {
|
||||
/// SELECT ... FROM book JOIN author ON author.id = book.authorId
|
||||
/// ~~~~ ~~~~
|
||||
///
|
||||
/// The origin table `book`is on the right of the JOIN operator for
|
||||
/// The origin table `book` is on the right of the JOIN operator for
|
||||
/// the `HasMany` and `HasOne` associations:
|
||||
///
|
||||
/// -- Author.including(required: Author.books)
|
||||
@@ -991,7 +991,7 @@ extension JoinMapping {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the condition into an SQL expression which involve both left
|
||||
/// Resolves the condition into an SQL expression which involves both left
|
||||
/// and right tables.
|
||||
///
|
||||
/// SELECT * FROM left JOIN right ON (right.a = left.b)
|
||||
|
||||
@@ -311,7 +311,7 @@ extension SQLSelection {
|
||||
extension [SQLSelection] {
|
||||
/// Returns the number of columns in the selection.
|
||||
///
|
||||
/// This method raises a fatal error if the selection contains a literal,
|
||||
/// This method raises a fatal error if the selection contains a literal.
|
||||
///
|
||||
/// See `SQLSelection.columnCount(_:)` for testability.
|
||||
func columnCount(_ context: SQLGenerationContext) throws -> Int {
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
///
|
||||
/// ### Building Query Interface Requests
|
||||
///
|
||||
/// `Table` provide convenience access to most ``DerivableRequest`` and
|
||||
/// `Table` provides convenience access to most ``DerivableRequest`` and
|
||||
/// ``QueryInterfaceRequest`` methods.
|
||||
///
|
||||
/// - ``aliased(_:)-3135k``
|
||||
@@ -1532,7 +1532,7 @@ extension Table {
|
||||
|
||||
extension Table {
|
||||
/// Returns a request with the given association aggregates appended to
|
||||
/// the table colums.
|
||||
/// the table columns.
|
||||
///
|
||||
/// See the ``TableRecord`` method ``TableRecord/annotated(with:)-4xoen``
|
||||
/// for more information.
|
||||
@@ -1541,7 +1541,7 @@ extension Table {
|
||||
}
|
||||
|
||||
/// Returns a request with the given association aggregates appended to
|
||||
/// the table colums.
|
||||
/// the table columns.
|
||||
///
|
||||
/// See the ``TableRecord`` method ``TableRecord/annotated(with:)-8ce7u``
|
||||
/// for more information.
|
||||
@@ -1925,7 +1925,7 @@ extension Table {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignment: A closure that returns an assignments.
|
||||
/// - parameter assignment: A closure that returns an assignment.
|
||||
/// - returns: The number of updated rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/// - It provides a database connection during SQL generation, for any purpose
|
||||
/// such as schema introspection.
|
||||
///
|
||||
/// - It provides unique table aliases in order to disambiguates table names
|
||||
/// - It provides unique table aliases in order to disambiguate table names
|
||||
/// and columns.
|
||||
///
|
||||
/// - It gathers SQL arguments in order to prevent SQL injection.
|
||||
@@ -46,7 +46,7 @@ final class SQLGenerationContext {
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter argumentsSink: An arguments sink.
|
||||
/// - parameter aliases: An array of table aliases to disambiguate.
|
||||
/// - parameter ctes: An dictionary of available CTEs.
|
||||
/// - parameter ctes: A dictionary of available CTEs.
|
||||
init(
|
||||
_ db: Database,
|
||||
argumentsSink: StatementArgumentsSink = StatementArgumentsSink(),
|
||||
@@ -63,7 +63,7 @@ final class SQLGenerationContext {
|
||||
///
|
||||
/// - parameter parent: A parent context.
|
||||
/// - parameter aliases: An array of table aliases to disambiguate.
|
||||
/// - parameter ctes: An dictionary of available CTEs.
|
||||
/// - parameter ctes: A dictionary of available CTEs.
|
||||
private init(
|
||||
parent: SQLGenerationContext,
|
||||
aliases: [TableAliasBase],
|
||||
|
||||
@@ -466,7 +466,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
case none
|
||||
/// Grouped by unique key: SELECT ... FROM player GROUP BY id
|
||||
case unique
|
||||
/// Grouped by some non-unique columnns: SELECT ... FROM player GROUP BY teamId
|
||||
/// Grouped by some non-unique columns: SELECT ... FROM player GROUP BY teamId
|
||||
case nonUnique
|
||||
}
|
||||
|
||||
@@ -518,7 +518,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
/// let book = try Book(row: row)
|
||||
/// }
|
||||
///
|
||||
/// But as soon as the selection includes columns of a included relation,
|
||||
/// But as soon as the selection includes columns of an included relation,
|
||||
/// we need an adapter:
|
||||
///
|
||||
/// // SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorId
|
||||
@@ -659,7 +659,7 @@ private struct SQLQualifiedRelation: Sendable {
|
||||
/// SQLQueryGenerator (as opposed to the joined relations).
|
||||
/// - returns: An optional tuple made of a RowAdapter and the index past the
|
||||
/// rightmost selected column of this relation. Nil is returned if this
|
||||
/// relations does not need any row adapter.
|
||||
/// relation does not need any row adapter.
|
||||
func rowAdapter(
|
||||
_ context: SQLGenerationContext,
|
||||
fromIndex startIndex: Int,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/// Describes a database column.
|
||||
///
|
||||
/// You get instances of `ColumnDefinition` when you create or alter a database
|
||||
/// tables. For example:
|
||||
/// table. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(table: "player") { t in
|
||||
|
||||
@@ -200,7 +200,7 @@ extension Database {
|
||||
/// >
|
||||
/// > The reason for this recommendation is that auto-incremented primary
|
||||
/// > keys forbid the reuse of ids. This prevents your app or
|
||||
/// > <doc:DatabaseObservation> to think that a row was updated, when it was
|
||||
/// > <doc:DatabaseObservation> from thinking that a row was updated, when it was
|
||||
/// > actually deleted and replaced. Depending on your application needs,
|
||||
/// > this may be acceptable. But usually it is not.
|
||||
///
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/// Describes an association in the database schema.
|
||||
///
|
||||
/// You get instances of `ForeignKeyDefinition` when you create a database
|
||||
/// tables. For example:
|
||||
/// table. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(table: "player") { t in
|
||||
|
||||
@@ -41,7 +41,7 @@ public final class TableAlteration {
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - parameter type: the column type.
|
||||
/// - returns: An ColumnDefinition that allows you to refine the
|
||||
/// - returns: A ColumnDefinition that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
|
||||
|
||||
@@ -63,7 +63,7 @@ public struct TableOptions: OptionSet, Sendable {
|
||||
///
|
||||
/// - ``uniqueKey(_:onConflict:)``
|
||||
///
|
||||
/// ### Define Others Constraints
|
||||
/// ### Define Other Constraints
|
||||
///
|
||||
/// - ``check(_:)-6u1za``
|
||||
/// - ``check(_:)-jpcg``
|
||||
|
||||
@@ -35,7 +35,7 @@ extension TableRecord {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The association can also help fetching associated records:
|
||||
/// The association can also help fetch associated records:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
@@ -106,7 +106,7 @@ extension TableRecord {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The association can also help fetching associated records:
|
||||
/// The association can also help fetch associated records:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
@@ -182,7 +182,7 @@ extension TableRecord {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The association can also help fetching associated records:
|
||||
/// The association can also help fetch associated records:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
@@ -425,7 +425,7 @@ extension TableRecord {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The association can also help fetching associated records:
|
||||
/// The association can also help fetch associated records:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
@@ -511,7 +511,7 @@ extension TableRecord {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The association can also help fetching associated records:
|
||||
/// The association can also help fetch associated records:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
|
||||
@@ -84,7 +84,7 @@ public protocol EncodableRecord: GRDBSendableMetatype {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A key that holds a encoder's name
|
||||
/// // A key that holds an encoder's name
|
||||
/// let encoderName = CodingUserInfoKey(rawValue: "encoderName")!
|
||||
///
|
||||
/// struct Player: PersistableRecord, Encodable {
|
||||
@@ -299,7 +299,7 @@ extension EncodableRecord {
|
||||
|
||||
/// Returns a dictionary of values changed from the other record.
|
||||
///
|
||||
/// The keys of the dictionary are the column names for which record do not
|
||||
/// The keys of the dictionary are the column names for which records do not
|
||||
/// share the same value. Values are the database values from the
|
||||
/// `other` record.
|
||||
///
|
||||
@@ -356,7 +356,7 @@ extension EncodableRecord {
|
||||
/// `PersistenceContainer` is the argument of the
|
||||
/// ``EncodableRecord/encode(to:)-k9pf`` method.
|
||||
public struct PersistenceContainer: Sendable {
|
||||
// The ordering of the OrderedDictionary helps generating always the same
|
||||
// The ordering of the OrderedDictionary helps always generate the same
|
||||
// SQL queries, and hit the statement cache.
|
||||
private var storage: OrderedDictionary<CaseInsensitiveIdentifier, DatabaseValue>
|
||||
|
||||
@@ -612,7 +612,7 @@ public enum DatabaseDateEncodingStrategy: @unchecked Sendable {
|
||||
public enum DatabaseUUIDEncodingStrategy: Sendable {
|
||||
/// The strategy that uses formatting from the UUID type.
|
||||
///
|
||||
/// It encodes UUIDs as 16-bytes data blobs.
|
||||
/// It encodes UUIDs as 16-byte data blobs.
|
||||
case deferredToUUID
|
||||
|
||||
/// Encodes UUIDs as uppercased strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
|
||||
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user