mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
198
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3dd3bbf0c5 | ||
|
|
d7cf0f9e59 | ||
|
|
389c3e0d4a | ||
|
|
a212bf9e89 | ||
|
|
65186104cc | ||
|
|
2f108508fa | ||
|
|
5513eab099 | ||
|
|
2ad2d20a89 | ||
|
|
dd90fe6e62 | ||
|
|
691207567a | ||
|
|
c7f1dd7470 | ||
|
|
8e5b9ca9bd | ||
|
|
dc7d47c066 | ||
|
|
14f60ad48f | ||
|
|
e758fde941 | ||
|
|
7477e1cff8 | ||
|
|
2d6fe172c3 | ||
|
|
0526853dde | ||
|
|
a60810f28e | ||
|
|
c35095c6da | ||
|
|
f878d99733 | ||
|
|
48a17ce490 | ||
|
|
361a482b1e | ||
|
|
8cba324d6e | ||
|
|
17e1683b66 | ||
|
|
b1b83abd8b | ||
|
|
d06c9ed6b5 | ||
|
|
9a98ed6292 | ||
|
|
5cc85a98f3 | ||
|
|
edc1d646f0 | ||
|
|
ab09078842 | ||
|
|
267e1ea5a6 | ||
|
|
18497b68fd | ||
|
|
19e33e2e7d | ||
|
|
76e0815907 | ||
|
|
85ad232b0b | ||
|
|
db695cf7dc | ||
|
|
76a7be8404 | ||
|
|
196c33ba63 | ||
|
|
50a74f7b03 | ||
|
|
3f27fb9289 | ||
|
|
62fdd41d75 | ||
|
|
c5d02eac32 | ||
|
|
d1bfce829b | ||
|
|
edd292bcbd | ||
|
|
a0e101e683 | ||
|
|
9ef5e2c8eb | ||
|
|
f5dc68fc6f | ||
|
|
b210ec7428 | ||
|
|
a7e3acf409 | ||
|
|
ca27f75760 | ||
|
|
99ecf76a77 | ||
|
|
f4991273c2 | ||
|
|
1b98a964d7 | ||
|
|
1095d21abd | ||
|
|
eb2378a741 | ||
|
|
37dde39557 | ||
|
|
5786391dc9 | ||
|
|
e1abafaae3 | ||
|
|
93d0baeade | ||
|
|
26ebd7e147 | ||
|
|
75e99861af | ||
|
|
2e433a3cb2 | ||
|
|
9518d74fa6 | ||
|
|
c7bbebc80f | ||
|
|
38f5226e95 | ||
|
|
2b19803644 | ||
|
|
d7d61add23 | ||
|
|
d040588849 | ||
|
|
30313623eb | ||
|
|
aab2664431 | ||
|
|
f3acfecc16 | ||
|
|
aa2cdb7ec3 | ||
|
|
d90ba851fe | ||
|
|
7eea8ccb91 | ||
|
|
6a25b3538e | ||
|
|
7ec88b76e0 | ||
|
|
1a3842e4bc | ||
|
|
32ed290a1b | ||
|
|
f88c7202cd | ||
|
|
79ce0ff5f3 | ||
|
|
f435715f75 | ||
|
|
cf1702630f | ||
|
|
fd7adf7fb3 | ||
|
|
be0f0c6f25 | ||
|
|
cd84db3873 | ||
|
|
4cfa692ddd | ||
|
|
8dfbbb50f6 | ||
|
|
3f69614405 | ||
|
|
b4f3a83755 | ||
|
|
7cd2a4563c | ||
|
|
2698c55654 | ||
|
|
37065fb503 | ||
|
|
3801ab9ac6 | ||
|
|
26abd8ad79 | ||
|
|
827ab62bb6 | ||
|
|
fdeb88a6bd | ||
|
|
8ba1bc9a96 | ||
|
|
c4e39285a0 | ||
|
|
1622b72b62 | ||
|
|
215128390d | ||
|
|
c5283a0bd9 | ||
|
|
fb68849bfb | ||
|
|
c2bddde88a | ||
|
|
b4a21d63b2 | ||
|
|
6ca38eda3b | ||
|
|
d76922fe1a | ||
|
|
a46f3b69e9 | ||
|
|
b572982e34 | ||
|
|
5a8b025ee8 | ||
|
|
9a1914a813 | ||
|
|
4a92263c5e | ||
|
|
f72d0cecb2 | ||
|
|
24e0f5ddeb | ||
|
|
2b1b56ea47 | ||
|
|
ad704c58e5 | ||
|
|
3f928bcf9c | ||
|
|
c91c183354 | ||
|
|
c666393e63 | ||
|
|
d242421862 | ||
|
|
7a1e65b142 | ||
|
|
fb4578a7d6 | ||
|
|
6069e6d683 | ||
|
|
a703da9b27 | ||
|
|
684266b7b8 | ||
|
|
b24fb76610 | ||
|
|
cbbd0cb945 | ||
|
|
dd4227303a | ||
|
|
69b786dc9e | ||
|
|
9dd8b2cef7 | ||
|
|
c5ac6cdaa6 | ||
|
|
e154a652dc | ||
|
|
41d4f23a83 | ||
|
|
27b7400979 | ||
|
|
e6847886db | ||
|
|
c064515247 | ||
|
|
96236a3d44 | ||
|
|
01cd49b4ec | ||
|
|
9db14cb893 | ||
|
|
b26f60eae0 | ||
|
|
79a41dcbbb | ||
|
|
c7d50486ad | ||
|
|
93292d88f4 | ||
|
|
be22e0a2d0 | ||
|
|
d1a2cb0948 | ||
|
|
a5a1be26b4 | ||
|
|
b84d1eaeef | ||
|
|
e7a35dde06 | ||
|
|
c2e6c86934 | ||
|
|
7c2cbfe814 | ||
|
|
034b241e71 | ||
|
|
814146c40d | ||
|
|
fedcdef65e | ||
|
|
2316fb3831 | ||
|
|
98e2812089 | ||
|
|
8f6f1aa264 | ||
|
|
96d04716c2 | ||
|
|
004968517e | ||
|
|
f635aea2f2 | ||
|
|
5c9b772e65 | ||
|
|
d6ff3b14d4 | ||
|
|
fac0c22ecb | ||
|
|
5461caff04 | ||
|
|
6cc3116ff4 | ||
|
|
55edcff97f | ||
|
|
430141344d | ||
|
|
0567f69e66 | ||
|
|
be2fb76d77 | ||
|
|
503fb09270 | ||
|
|
ec6042e9c7 | ||
|
|
190ccda727 | ||
|
|
af1adff71d | ||
|
|
43e103d5f8 | ||
|
|
7b2e9d838a | ||
|
|
6b0faede2a | ||
|
|
ed402d5de6 | ||
|
|
db5c4cc458 | ||
|
|
352f77f225 | ||
|
|
ed98ac30e0 | ||
|
|
35fa28ab90 | ||
|
|
a89bd88340 | ||
|
|
b01f6da3cf | ||
|
|
e7fdd65072 | ||
|
|
ff15f30a3b | ||
|
|
f69ca1a573 | ||
|
|
e8b143e2ee | ||
|
|
5e9b965bee | ||
|
|
ce238b6643 | ||
|
|
787393db18 | ||
|
|
8774497f31 | ||
|
|
94e90e7e6c | ||
|
|
9064717b8a | ||
|
|
00f462292b | ||
|
|
5a0622e5b8 | ||
|
|
596db46407 | ||
|
|
0aaa2a4f37 | ||
|
|
04e73c26c4 | ||
|
|
a71c1d6e80 |
No files matched your search
+30
-30
@@ -1,4 +1,4 @@
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-14-Readme.md
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md
|
||||
|
||||
name: "GRDB CI"
|
||||
|
||||
@@ -40,20 +40,20 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=iPhone 16 Pro"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "OS=18.5,name=iPhone 16 Pro"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=Apple TV"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "OS=18.5,name=Apple TV"
|
||||
name: "tvOS"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
|
||||
SPM:
|
||||
@@ -66,11 +66,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM test_install_SPM
|
||||
SQLCipher3:
|
||||
@@ -83,11 +83,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
SQLCipher4:
|
||||
@@ -100,11 +100,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
CustomSQLite:
|
||||
@@ -117,11 +117,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
XCFramework:
|
||||
@@ -134,11 +134,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_universal_xcframework
|
||||
|
||||
@@ -2,4 +2,4 @@ version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [GRDB]
|
||||
swift_version: 6.0
|
||||
swift_version: 6.1
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"editor.formatOnSave": false,
|
||||
"editor.insertSpaces": true,
|
||||
"editor.tabSize": 4,
|
||||
"editor.detectIndentation": false,
|
||||
"editor.trimAutoWhitespace": false
|
||||
}
|
||||
+55
-1
@@ -7,7 +7,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `7.4.x` Releases - [7.4.0](#740)
|
||||
- `7.8.x` Releases - [7.8.0](#780)
|
||||
- `7.7.x` Releases - [7.7.0](#770) - [7.7.1](#771)
|
||||
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
|
||||
- `7.5.x` Releases - [7.5.0](#750)
|
||||
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
|
||||
- `7.3.x` Releases - [7.3.0](#730)
|
||||
- `7.2.x` Releases - [7.2.0](#720)
|
||||
- `7.1.x` Releases - [7.1.0](#710)
|
||||
@@ -136,6 +140,56 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 7.8.0
|
||||
|
||||
Released October 2, 2025
|
||||
|
||||
- **New**: Merged Migrations by [@groue](https://github.com/groue) in [#1818](https://github.com/groue/GRDB.swift/pull/1818)
|
||||
|
||||
## 7.7.1
|
||||
|
||||
Released September 29, 2025
|
||||
|
||||
- **Fixed**: Fix the save() method for record types with attached triggers by [@groue](https://github.com/groue) in [#1822](https://github.com/groue/GRDB.swift/pull/1822)
|
||||
|
||||
## 7.7.0
|
||||
|
||||
Released September 23, 2025
|
||||
|
||||
- **New**: Update GRDB7MigrationGuide.md reference by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#1807](https://github.com/groue/GRDB.swift/pull/1807)
|
||||
- **New**: Persistable Database Views by [@groue](https://github.com/groue) in [#1810](https://github.com/groue/GRDB.swift/pull/1810)
|
||||
- **New**: Support for Xcode 26 by [@groue](https://github.com/groue) in [#1813](https://github.com/groue/GRDB.swift/pull/1813)
|
||||
- **Fixed**: Fix another race condition regarding Task cancellation, completing [#1797](https://github.com/groue/GRDB.swift/pull/1797)
|
||||
|
||||
## 7.6.1
|
||||
|
||||
Released July 23, 2025
|
||||
|
||||
- **Fixed**: Fix race condition regarding Task cancellation by [@groue](https://github.com/groue) in [#1797](https://github.com/groue/GRDB.swift/pull/1797)
|
||||
|
||||
## 7.6.0
|
||||
|
||||
Released July 20, 2025
|
||||
|
||||
- **New**: All closures that accept DatabaseComponents can throw by [@groue](https://github.com/groue) in [#1768](https://github.com/groue/GRDB.swift/pull/1768)
|
||||
- **New**: Add Sendable conformance to DatabasePreUpdateEvent.Kind, matching DatabaseEvent.Kind by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1773](https://github.com/groue/GRDB.swift/pull/1773)
|
||||
- **New**: Add custom build instruction for hardened runtime by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1776](https://github.com/groue/GRDB.swift/pull/1776)
|
||||
- **New**: Access task locals from asynchronous database accesses by [@groue](https://github.com/groue) in [#1794](https://github.com/groue/GRDB.swift/pull/1794)
|
||||
- **New**: Throwing row accessors by [@groue](https://github.com/groue) in [#1796](https://github.com/groue/GRDB.swift/pull/1796)
|
||||
|
||||
## 7.5.0
|
||||
|
||||
Released May 11, 2025
|
||||
|
||||
- **New**: Make it possible to create a raw FTS5Pattern without any database connection by [@groue](https://github.com/groue) in [#1764](https://github.com/groue/GRDB.swift/pull/1764)
|
||||
- **New**: Build request with closures by [@groue](https://github.com/groue) in [#1759](https://github.com/groue/GRDB.swift/pull/1759)
|
||||
|
||||
## 7.4.1
|
||||
|
||||
Released March 28, 2025
|
||||
|
||||
- Removed a compiler warning
|
||||
|
||||
## 7.4.0
|
||||
|
||||
Released March 22, 2025
|
||||
|
||||
+129
-113
@@ -58,15 +58,26 @@ GRDB Associations
|
||||
Associations streamline common operations in your code, make them safer, and more efficient. For example, consider a library application that has two record types, author and book:
|
||||
|
||||
```swift
|
||||
struct Author {
|
||||
struct Author: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
var id: Int64
|
||||
var name: String
|
||||
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
}
|
||||
}
|
||||
|
||||
struct Book {
|
||||
struct Book: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
var id: Int64
|
||||
var authorId: Int64?
|
||||
var title: String
|
||||
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let authorId = Column(CodingKeys.authorId)
|
||||
static let title = Column(CodingKeys.title)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -75,7 +86,7 @@ Now, suppose we wanted to load all books from an existing author. We'd need to d
|
||||
```swift
|
||||
let author: Author = ...
|
||||
let books = try Book
|
||||
.filter(Column("authorId") == author.id)
|
||||
.filter { $0.authorId == author.id }
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
@@ -121,7 +132,7 @@ let books = try author.books.fetchAll(db)
|
||||
As for loading all pairs of books and authors, it is not only easier, but also *much more efficient*:
|
||||
|
||||
```swift
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
let book: Book
|
||||
let author: Author?
|
||||
}
|
||||
@@ -728,9 +739,15 @@ Your help is needed. You have to instruct GRDB which foreign key to use:
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord {
|
||||
// Table columns
|
||||
enum Columns {
|
||||
static let authorId = Column("authorId")
|
||||
static let translatorId = Column("translatorId")
|
||||
}
|
||||
|
||||
// Define foreign keys
|
||||
static let authorForeignKey = ForeignKey(["authorId"])
|
||||
static let translatorForeignKey = ForeignKey(["translatorId"])
|
||||
static let authorForeignKey = ForeignKey([Columns.authorId])
|
||||
static let translatorForeignKey = ForeignKey([Columns.translatorId])
|
||||
|
||||
// Use foreign keys to define associations:
|
||||
static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
@@ -747,24 +764,11 @@ struct Person: TableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
Foreign keys can also be defined from query interface columns:
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord {
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, title, authorId, translatorId
|
||||
}
|
||||
|
||||
static let authorForeignKey = ForeignKey([Columns.authorId])
|
||||
static let translatorForeignKey = ForeignKey([Columns.translatorId])
|
||||
}
|
||||
```
|
||||
|
||||
When the destination table of a foreign key does not define any primary key, you need to provide the full definition of a foreign key:
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord {
|
||||
static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])
|
||||
static let authorForeignKey = ForeignKey([Columns.authorId], to: [Person.Columns.id])
|
||||
static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
}
|
||||
```
|
||||
@@ -836,8 +840,8 @@ Requests for associated records can be filtered and ordered like all [query inte
|
||||
```swift
|
||||
let novels = try author
|
||||
.books
|
||||
.filter(Column("kind") == BookKind.novel)
|
||||
.order(Column("publishDate").desc)
|
||||
.filter { $0.kind == BookKind.novel }
|
||||
.order(\.publishDate.desc)
|
||||
.fetchAll(db) // [Book]
|
||||
```
|
||||
|
||||
@@ -921,7 +925,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var author: PartialAuthor
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author.select(Column("name"), Column("country")))
|
||||
.including(required: Book.author.select { [$0.name, $0.country] })
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -935,7 +939,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(Column("country")))
|
||||
.annotated(withRequired: Book.author.select(\.country)
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -982,7 +986,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var author: PartialAuthor?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author.select(Column("name"), Column("country")))
|
||||
.including(optional: Book.author.select { [$0.name, $0.country] })
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -996,7 +1000,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(Column("country")))
|
||||
.annotated(withOptional: Book.author.select(\.country))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1064,7 +1068,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var books: [PartialBook]
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books.select(Column("title"), Column("year")))
|
||||
.including(all: Author.books.select { [$0.title, $0.year] })
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1079,7 +1083,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books
|
||||
.select(Column("title"))
|
||||
.select(\.title)
|
||||
.forKey("bookTitles"))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
@@ -1093,7 +1097,7 @@ For example, fetch books along with the name and country of their author:
|
||||
// SELECT book.*, author.name, author.country
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId
|
||||
let request = Book.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
|
||||
let request = Book.annotated(withRequired: Book.author.select { [$0.name, $0.country] })
|
||||
```
|
||||
|
||||
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, records are not present in the fetched results: the associated record is "required".
|
||||
@@ -1108,7 +1112,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String // A column of the required associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
|
||||
.annotated(withRequired: Book.author.select { [$0.name, $0.country] })
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1122,7 +1126,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var authorName: String
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(Column("name").forKey("authorName")))
|
||||
.annotated(withRequired: Book.author.select { $0.name.forKey("authorName") })
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1135,7 +1139,7 @@ For example, fetch books along with the name and country of their eventual autho
|
||||
// SELECT book.*, author.name, author.country
|
||||
// FROM book
|
||||
// LEFT JOIN author ON author.id = book.authorId
|
||||
let request = Book.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
|
||||
let request = Book.annotated(withOptional: Book.author.select { [$0.name, $0.country] })
|
||||
```
|
||||
|
||||
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, the columns of the associated record are NULL: the associated record is "optional".
|
||||
@@ -1150,7 +1154,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String? // A column of the optional associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
|
||||
.annotated(withOptional: Book.author.select { [$0.name, $0.country] })
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1164,7 +1168,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var authorName: String?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(Column("name").forKey("authorName")))
|
||||
.annotated(withOptional: Book.author.select { $0.name.forKey("authorName") })
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1178,7 +1182,7 @@ For example, fetch books by French authors:
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId
|
||||
// AND author.country = 'France'
|
||||
let request = Book.joining(required: Book.author.filter(Column("country") == "France"))
|
||||
let request = Book.joining(required: Book.author.filter { $0.country == "France" })
|
||||
```
|
||||
|
||||
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. When the associated record does not exist, the base record is not present in the fetched results: the associated record is "required".
|
||||
@@ -1188,7 +1192,7 @@ To fetch results from such a request, you do not need to define a dedicated reco
|
||||
```swift
|
||||
// Fetch all books by French authors
|
||||
let books = try Book
|
||||
.joining(required: Book.author.filter(Column("country") == "France"))
|
||||
.joining(required: Book.author.filter { $0.country == "France" })
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
@@ -1239,7 +1243,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author.select(Column("name"), Column("country")))
|
||||
.including(required: Book.author.select { [$0.name, $0.country] })
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1254,9 +1258,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(
|
||||
Column("name").forKey("authorName"),
|
||||
Column("country")))
|
||||
.annotated(withRequired: Book.author.select {
|
||||
[$0.name.forKey("authorName"), $0.country]
|
||||
})
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1286,7 +1290,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author.select(Column("name"), Column("country")))
|
||||
.including(optional: Book.author.select { [$0.name, $0.country] })
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1301,9 +1305,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(
|
||||
Column("name").forKey("authorName"),
|
||||
Column("country")))
|
||||
.annotated(withOptional: Book.author.select {
|
||||
[$0.name.forKey("authorName"), $0.country]
|
||||
})
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1333,7 +1337,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books.select(Column("title"), Column("year")))
|
||||
.including(all: Author.books.select { [$0.title, $0.year] })
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1346,7 +1350,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books
|
||||
.select(Column("title"))
|
||||
.select(\.title)
|
||||
.forKey("bookTitles"))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
@@ -1460,7 +1464,7 @@ The `filter(_:)`, `filter(id:)`, `filter(ids:)`, `filter(key:)` and `filter(keys
|
||||
// FROM book
|
||||
// JOIN person ON person.id = book.authorId
|
||||
// AND person.countryCode = 'FR'
|
||||
let frenchAuthor = Book.author.filter(Column("countryCode") == "FR")
|
||||
let frenchAuthor = Book.author.filter { $0.countryCode == "FR" }
|
||||
let request = Book.joining(required: frenchAuthor)
|
||||
|
||||
// This request feeds the Book record:
|
||||
@@ -1474,10 +1478,10 @@ The one below fetches all authors along with their novels and poems:
|
||||
```swift
|
||||
let request = Author
|
||||
.including(all: Author.book
|
||||
.filter(Column("kind") == "novel")
|
||||
.filter { $0.kind == "novel" }
|
||||
.forKey("novels"))
|
||||
.including(all: Author.book
|
||||
.filter(Column("kind") == "poems")
|
||||
.filter { $0.kind == "poems" }
|
||||
.forKey("poems"))
|
||||
|
||||
// This request can feed the following record:
|
||||
@@ -1508,7 +1512,7 @@ The `order()` method, that you already know for [sorting simple requests](../REA
|
||||
// FROM book
|
||||
// JOIN person ON person.id = book.authorId
|
||||
// ORDER BY person.name
|
||||
let sortedAuthor = Book.author.order(Column("name"))
|
||||
let sortedAuthor = Book.author.order(\.name)
|
||||
let request = Book.including(required: sortedAuthor)
|
||||
```
|
||||
|
||||
@@ -1519,10 +1523,10 @@ When you sort both the base record and the associated record, the request is sor
|
||||
// FROM book
|
||||
// JOIN person ON person.id = book.authorId
|
||||
// ORDER BY book.publishDate DESC, person.name
|
||||
let sortedAuthor = Book.author.order(Column("name"))
|
||||
let sortedAuthor = Book.author.order(\.name)
|
||||
let request = Book
|
||||
.including(required: sortedAuthor)
|
||||
.order(Column("publishDate").desc)
|
||||
.order(\.publishDate.desc)
|
||||
```
|
||||
|
||||
**There are more sorting options:**
|
||||
@@ -1559,7 +1563,7 @@ The `Team.players` association is ordered by position, so that all team players
|
||||
|
||||
```swift
|
||||
extension Team {
|
||||
static let players = hasMany(Player.self).order(Column("position"))
|
||||
static let players = hasMany(Player.self).order(\.position)
|
||||
|
||||
var players: QueryInterfaceRequest<Player> {
|
||||
request(for: Team.players)
|
||||
@@ -1591,7 +1595,7 @@ Again, the `Team.players` association is ordered by position, so that all team p
|
||||
|
||||
```swift
|
||||
extension Team {
|
||||
static let playerRoles = hasMany(PlayerRole.self).order(Column("position"))
|
||||
static let playerRoles = hasMany(PlayerRole.self).order(\.position)
|
||||
|
||||
static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player)
|
||||
|
||||
@@ -1623,9 +1627,9 @@ let teamInfos = try Team
|
||||
|
||||
// Custom ordering
|
||||
let team: Team = ...
|
||||
let players = try team.players.order(Column("name")).fetchAll(db)
|
||||
let players = try team.players.order(\.name).fetchAll(db)
|
||||
let teamInfos = try Team
|
||||
.including(all: Team.players.order(Column("name")))
|
||||
.including(all: Team.players.order(\.name))
|
||||
.asRequest(of: TeamInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1651,7 +1655,7 @@ To specify the selection in a specific request, use the `select` method:
|
||||
// SELECT book.*, author.id, author.name
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId
|
||||
let restrictedAuthor = Book.author.select(Column("id"), Column("name"))
|
||||
let restrictedAuthor = Book.author.select { [$0.id, $0.name] }
|
||||
let request = Book.including(required: restrictedAuthor)
|
||||
```
|
||||
|
||||
@@ -1673,7 +1677,7 @@ Associations support more refinements:
|
||||
}
|
||||
|
||||
let distinctBookKinds = Author.books
|
||||
.select(Column("kind"))
|
||||
.select(\.kind)
|
||||
.distinct()
|
||||
.forKey("bookKinds")
|
||||
|
||||
@@ -1699,10 +1703,8 @@ Associations support more refinements:
|
||||
}
|
||||
|
||||
let bookKindInfos = Author.books
|
||||
.select(
|
||||
Column("kind"),
|
||||
max(Column("year")).forKey("maxYear"))
|
||||
.group(Column("kind"))
|
||||
.select { [$0.kind, max($0.year).forKey("maxYear")] }
|
||||
.group(\.kind)
|
||||
.forKey("bookKindInfos")
|
||||
|
||||
let authorInfos: [AuthorInfo] = try Author
|
||||
@@ -1772,7 +1774,7 @@ Let's first see a wrong way to do it:
|
||||
// WHERE book.publishDate >= book.deathDate
|
||||
let request = Book
|
||||
.joining(required: Book.author)
|
||||
.filter(Column("publishDate") >= Column("deathDate"))
|
||||
.filter { $0.publishDate >= $0.deathDate }
|
||||
```
|
||||
|
||||
When executed, we'll get a DatabaseError of code 1, "no such column: book.deathDate".
|
||||
@@ -1782,21 +1784,35 @@ That is because the "deathDate" column has been used for filtering books, when i
|
||||
To fix this error, we need a **table alias**:
|
||||
|
||||
```swift
|
||||
let authorAlias = TableAlias()
|
||||
let authorAlias = TableAlias<Author>()
|
||||
```
|
||||
|
||||
We modify the `Book.author` association so that it uses this table alias, and we use the table alias to qualify author columns where needed:
|
||||
|
||||
```swift
|
||||
// SELECT book.*
|
||||
// FROM book
|
||||
// JOIN person ON person.id = book.authorId
|
||||
// WHERE book.publishDate >= person.deathDate
|
||||
// Swift 6.1
|
||||
//
|
||||
// > SELECT book.*
|
||||
// > FROM book
|
||||
// > JOIN person ON person.id = book.authorId
|
||||
// > WHERE book.publishDate >= person.deathDate
|
||||
let request = Book
|
||||
.joining(required: Book.author.aliased(authorAlias))
|
||||
.filter(Column("publishDate") >= authorAlias[Column("deathDate")])
|
||||
.filter { $0.publishDate >= authorAlias.deathDate }
|
||||
|
||||
// Swift 6.0
|
||||
//
|
||||
// > SELECT book.*
|
||||
// > FROM book
|
||||
// > JOIN person ON person.id = book.authorId
|
||||
// > WHERE book.publishDate >= person.deathDate
|
||||
let request = Book
|
||||
.joining(required: Book.author.aliased(authorAlias))
|
||||
.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.
|
||||
|
||||
**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:
|
||||
|
||||
```swift
|
||||
@@ -1806,7 +1822,7 @@ let request = Book
|
||||
// ORDER BY person.name, book.publishDate
|
||||
let request = Book
|
||||
.joining(required: Book.author.aliased(authorAlias))
|
||||
.order(authorAlias[Column("name")], Column("publishDate"))
|
||||
.order { [authorAlias.name, $0.publishDate] }
|
||||
```
|
||||
|
||||
**Table aliases** can be given a name. This name is guaranteed to be used as the table alias in the SQL query. This guarantee lets you write SQL snippets when you need it:
|
||||
@@ -1817,8 +1833,8 @@ let request = Book
|
||||
// JOIN person a ON a.id = b.authorId
|
||||
// AND a.countryCode = 'FR'
|
||||
// WHERE b.publishDate >= a.deathDate
|
||||
let bookAlias = TableAlias(name: "b")
|
||||
let authorAlias = TableAlias(name: "a")
|
||||
let bookAlias = TableAlias<Book>(name: "b")
|
||||
let authorAlias = TableAlias<Person>(name: "a")
|
||||
let request = Book.aliased(bookAlias)
|
||||
.joining(required: Book.author.aliased(authorAlias)
|
||||
.filter(sql: "a.countryCode = ?", arguments: ["FR"]))
|
||||
@@ -1838,11 +1854,11 @@ let request = Book.aliased(bookAlias)
|
||||
>
|
||||
> ```swift
|
||||
> // NOT IMPLEMENTED: loading all authors along with their posthumous books
|
||||
> let authorAlias = TableAlias()
|
||||
> let authorAlias = TableAlias<Author>()
|
||||
> let request = Author
|
||||
> .aliased(authorAlias)
|
||||
> .including(all: Author.books
|
||||
> .filter(Column("publishDate") >= authorAlias[Column("deathDate")]))
|
||||
> .filter { $0.publishDate >= authorAlias.deathDate })
|
||||
> ```
|
||||
|
||||
|
||||
@@ -1904,7 +1920,7 @@ For example, we can start by defining base requests as extensions to the [Deriva
|
||||
extension DerivableRequest<Author> {
|
||||
/// Filters authors by country
|
||||
func filter(country: String) -> Self {
|
||||
filter(Column("country") == country)
|
||||
filter { $0.country == country }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1917,12 +1933,13 @@ extension DerivableRequest<Book> {
|
||||
|
||||
/// Order books by author name and then book title
|
||||
func orderedByAuthorNameAndYear() -> Self {
|
||||
let authorAlias = TableAlias()
|
||||
let authorAlias = TableAlias<Author>()
|
||||
return self
|
||||
.joining(optional: Book.author.aliased(authorAlias))
|
||||
.order(
|
||||
authorAlias[Column("name")].collating(.localizedCaseInsensitiveCompare),
|
||||
Column("year"))
|
||||
.order { [
|
||||
authorAlias.name.collating(.localizedCaseInsensitiveCompare),
|
||||
$0.year,
|
||||
] }
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -2063,7 +2080,7 @@ Keys can also be customized with the `forKey` method:
|
||||
```swift
|
||||
extension Author {
|
||||
static let novels = books
|
||||
.filter(Column("kind") == "novel")
|
||||
.filter { $0.kind == "novel" }
|
||||
.forKey("novels")
|
||||
}
|
||||
Author.including(all: Author.novels) // association key "novels"
|
||||
@@ -2169,26 +2186,25 @@ struct BookInfo: FetchableRecord {
|
||||
|
||||
init(row: Row) throws {
|
||||
book = try Book(row: row)
|
||||
author = row["author"]
|
||||
country = row["country"]
|
||||
coverImage = row["coverImage"]
|
||||
author = try row.decode(forKey: "author")
|
||||
country = try row.decodeIfPresent(forKey: "country")
|
||||
coverImage = try row.decodeIfPresent(forKey: "coverImage")
|
||||
}
|
||||
}
|
||||
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
You are already familiar with row subscripts to decode [database values](../README.md#column-values):
|
||||
When you extract a record from a row, GRDB looks up the tree of **association keys**:
|
||||
|
||||
```swift
|
||||
let name: String = row["name"]
|
||||
let author = try row.decode(Author.self, forKey: "author")
|
||||
```
|
||||
|
||||
When you extract a record instead of a value from a row, GRDB looks up the tree of **association keys**. If the key is not found, or only associated with columns that all contain NULL values, an optional record is decoded as nil:
|
||||
If the key is not found, or only associated with columns that are all NULL, an optional record is decoded as nil:
|
||||
|
||||
```swift
|
||||
let author: Author = row["author"]
|
||||
let country: Country? = row["country"]
|
||||
let country = try row.decodeIfPresent(Country.self, forKey: "country")
|
||||
```
|
||||
|
||||
You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information.
|
||||
@@ -2204,7 +2220,7 @@ struct AuthorInfo: FetchableRecord {
|
||||
|
||||
init(row: Row) throws {
|
||||
author = try Author(row: row)
|
||||
books = row["books"]
|
||||
books = try row.decode(forKey: "books")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2288,7 +2304,7 @@ let author: Author = ...
|
||||
let bookCount = try author.books.fetchCount(db) // Int
|
||||
|
||||
// The year of the most recent book by this author
|
||||
let request = author.books.select(max(yearColumn))
|
||||
let request = author.books.select { max($0.year) }
|
||||
let maxBookYear = try Int.fetchOne(db, request) // Int?
|
||||
```
|
||||
|
||||
@@ -2359,7 +2375,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
// GROUP BY author.id
|
||||
let request = Author.annotated(with:
|
||||
Author.books.count,
|
||||
Author.books.max(Column("year")))
|
||||
Author.books.max(\.year))
|
||||
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
|
||||
@@ -2376,13 +2392,13 @@ The default name is built from the aggregating method, the **[association key](#
|
||||
|
||||
| Method | Association Key | Aggregated Column | Aggregate name |
|
||||
| ------ | --------------- | ----------------- | -------------- |
|
||||
| `Author.books.isEmpty`. | `books` | - | `hasNoBook` |
|
||||
| `Author.books.count`. | `books` | - | `bookCount` |
|
||||
| `Author.books.min(Column("year"))` | `books` | `year` | `minBookYear` |
|
||||
| `Author.books.max(Column("year"))` | `books` | `year` | `maxBookYear` |
|
||||
| `Author.books.average(Column("price"))` | `books` | `price` | `averageBookPrice` |
|
||||
| `Author.books.sum(Column("awards"))` | `books` | `awards` | `bookAwardsSum` |
|
||||
| `Author.books.total(Column("awards"))` | `books` | `awards` | `bookAwardsSum` ¹ |
|
||||
| `Author.books.isEmpty`. | `books` | - | `hasNoBook` |
|
||||
| `Author.books.count`. | `books` | - | `bookCount` |
|
||||
| `Author.books.min(\.year)` | `books` | `year` | `minBookYear` |
|
||||
| `Author.books.max(\.year)` | `books` | `year` | `maxBookYear` |
|
||||
| `Author.books.average(\.price)` | `books` | `price` | `averageBookPrice` |
|
||||
| `Author.books.sum(\.awards)` | `books` | `awards` | `bookAwardsSum` |
|
||||
| `Author.books.total((\.awards))` | `books` | `awards` | `bookAwardsSum` ¹ |
|
||||
|
||||
¹ The default name of the `total` aggregate has a `Sum` suffix, just like the `sum` aggregate. Both compute sums, one with the `SUM` SQL function, the other with `TOTAL`. See [SQLite documentation](https://www.sqlite.org/lang_aggfunc.html#sumunc) for the difference between these aggregate functions.
|
||||
|
||||
@@ -2511,7 +2527,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Author.having(Author.books.max(Column("year")) >= 2010)
|
||||
let request = Author.having(Author.books.max(\.year) >= 2010)
|
||||
```
|
||||
|
||||
- Authors who wrote at least one book of kind "novel":
|
||||
@@ -2530,7 +2546,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let novels = Author.books.filter(Column("kind") == "novel")
|
||||
let novels = Author.books.filter { $0.kind == "novel" }
|
||||
let request = Author.having(novels.isEmpty == false)
|
||||
```
|
||||
|
||||
@@ -2616,7 +2632,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Author.having(Author.books.max(Column("year")) >= 2010)
|
||||
let request = Author.having(Author.books.max(\.year) >= 2010)
|
||||
```
|
||||
|
||||
- Arithmetic operators `+`, `-`, `*`, `/`
|
||||
@@ -2656,7 +2672,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
|
||||
let request = Team.annotated(with: Team.players.min(\.score) ?? 0)
|
||||
```
|
||||
|
||||
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
|
||||
@@ -2674,7 +2690,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Team.annotated(with: abs(Team.players.max(Column("score"))))
|
||||
let request = Team.annotated(with: abs(Team.players.max(\.score)))
|
||||
```
|
||||
|
||||
### Isolation of Multiple Aggregates
|
||||
@@ -2711,8 +2727,8 @@ In the example below, we use compute two aggregates from the same association `A
|
||||
}
|
||||
|
||||
let request = Author.annotated(with:
|
||||
Author.books.min(Column("year")), // association key "books"
|
||||
Author.books.max(Column("year"))) // association key "books"
|
||||
Author.books.min(\.year), // association key "books"
|
||||
Author.books.max(\.year)) // association key "books"
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
@@ -2782,11 +2798,11 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
}
|
||||
|
||||
let novelCount = Author.books
|
||||
.filter(Column("kind") == "novel")
|
||||
.filter { $0.kind == "novel" }
|
||||
.forKey("novels") // association key "novels"
|
||||
.count
|
||||
let theatrePlayCount = Author.books
|
||||
.filter(Column("kind") == "theatrePlay")
|
||||
.filter { $0.kind == "theatrePlay" }
|
||||
.forKey("theatrePlays") // association key "theatrePlays"
|
||||
.count
|
||||
let request = Author.annotated(with: novelCount, theatrePlayCount)
|
||||
@@ -2813,11 +2829,11 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
```swift
|
||||
// WRONG: not counting distinct sets of associated books
|
||||
let novelCount = Author.books // association key "books"
|
||||
.filter(Column("kind") == "novel")
|
||||
.filter { $0.kind == "novel" }
|
||||
.count
|
||||
.forKey("novelCount")
|
||||
let theatrePlayCount = Author.books // association key "books"
|
||||
.filter(Column("kind") == "theatrePlay")
|
||||
.filter { $0.kind == "theatrePlay" }
|
||||
.count
|
||||
.forKey("theatrePlayCount")
|
||||
let request = Author.annotated(with: novelCount, theatrePlayCount)
|
||||
@@ -2847,11 +2863,11 @@ Those methods are defined on extensions to the `DerivableRequest` protocol:
|
||||
```swift
|
||||
extension DerivableRequest<Author> {
|
||||
func filter(country: String) -> Self {
|
||||
filter(Column("country") == country)
|
||||
filter { $0.country == country }
|
||||
}
|
||||
|
||||
func orderedByName() -> Self {
|
||||
order(Column("name").collating(.localizedCaseInsensitiveCompare))
|
||||
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2882,11 +2898,11 @@ See [Recommended Practices for Designing Record Types] for more information.
|
||||
|
||||
```swift
|
||||
// NOT IMPLEMENTED: loading all authors along with their posthumous books
|
||||
let authorAlias = TableAlias()
|
||||
let authorAlias = TableAlias<Author>()
|
||||
let request = Author
|
||||
.aliased(authorAlias)
|
||||
.including(all: Author.books
|
||||
.filter(Column("publishDate") >= authorAlias[Column("deathDate")]))
|
||||
.filter { $0.publishDate >= authorAlias.deathDate })
|
||||
```
|
||||
|
||||
- **You can't use the `including(all:)` method with a [HasMany] and a [HasManyThrough] associations that share the same base association in the same request**:
|
||||
|
||||
@@ -332,7 +332,7 @@ let hallOfFamePublisher = ValueObservation
|
||||
|
||||
// 2nd request
|
||||
let bestPlayers = try Player
|
||||
.order(Column("score").desc)
|
||||
.order(\.score.desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
@@ -358,7 +358,7 @@ let totalPlayerCountPublisher = ValueObservation
|
||||
// OK
|
||||
let bestPlayerPublisher = ValueObservation
|
||||
.tracking(Player
|
||||
.order(Column("score").desc)
|
||||
.order(\.score.desc)
|
||||
.limit(10)
|
||||
.fetchAll)
|
||||
.publisher(in: dbQueue)
|
||||
|
||||
@@ -31,7 +31,7 @@ The CTE request can be provided as a [query interface request]:
|
||||
// WITH playerName AS (SELECT name FROM player) ...
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
request: Player.select(Column("name")))
|
||||
request: Player.select(\.name))
|
||||
```
|
||||
|
||||
You can feed a CTE with raw SQL as well (second and third examples use [SQL Interpolation]):
|
||||
@@ -123,7 +123,7 @@ And we can then filter the `player` table with a subquery:
|
||||
// WHERE name = (SELECT * FROM playerName)
|
||||
let request = Player
|
||||
.with(playerNameCTE)
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
.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.
|
||||
@@ -167,13 +167,13 @@ Common table expressions can also be used as subqueries, when you update or dele
|
||||
// UPDATE player SET name = (SELECT * FROM playerName)
|
||||
try Player
|
||||
.with(playerNameCTE)
|
||||
.updateAll(db, Column("name").set(to: playerNameCTE.all()))
|
||||
.updateAll(db) { $0.name.set(to: playerNameCTE.all()) }
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// DELETE FROM player WHERE name = (SELECT * FROM playerName)
|
||||
try Player
|
||||
.with(playerNameCTE)
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
.filter { $0.name == playerNameCTE.all() }
|
||||
.deleteAll(db)
|
||||
```
|
||||
|
||||
@@ -281,9 +281,15 @@ struct Chat: Codable, FetchableRecord, PersistableRecord {
|
||||
}
|
||||
|
||||
struct Message: Codable, FetchableRecord, PersistableRecord {
|
||||
var chatID: Int64
|
||||
var chatId: Int64
|
||||
var date: Date
|
||||
...
|
||||
|
||||
enum Columns {
|
||||
static let chatId = Column("chatId")
|
||||
static let date = Column("date")
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -315,8 +321,8 @@ We start by defining the CTE request, which loads the latest messages of all cha
|
||||
```swift
|
||||
// SELECT *, MAX(date) FROM message GROUP BY chatID
|
||||
let latestMessageRequest = Message
|
||||
.annotated(with: max(Column("date")))
|
||||
.group(Column("chatID"))
|
||||
.annotated { max($0.date) }
|
||||
.group(\.chatId)
|
||||
```
|
||||
|
||||
We can now define the CTE for the latest messages:
|
||||
@@ -324,7 +330,7 @@ We can now define the CTE for the latest messages:
|
||||
```swift
|
||||
// WITH latestMessage AS
|
||||
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
|
||||
let latestMessageCTE = CommonTableExpression(
|
||||
let latestMessageCTE = CommonTableExpression<Message>(
|
||||
named: "latestMessage",
|
||||
request: latestMessageRequest)
|
||||
```
|
||||
@@ -337,9 +343,9 @@ The association from a chat to its latest message follows:
|
||||
let latestMessage = Chat.association(
|
||||
to: latestMessageCTE,
|
||||
on: { chat, latestMessage in
|
||||
chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
chat.id == latestMessage.chatId
|
||||
})
|
||||
.order(Column("date").desc)
|
||||
.order(\.date.desc)
|
||||
```
|
||||
|
||||
The final request can now be defined:
|
||||
|
||||
@@ -9,18 +9,20 @@ 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).
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version:
|
||||
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout [latest tag]
|
||||
git submodule update --init SQLiteCustom/src
|
||||
```
|
||||
|
||||
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
|
||||
|
||||
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
|
||||
@@ -28,31 +30,31 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
4. Create four files in the `GRDBCustomSQLite` folder:
|
||||
|
||||
- `SQLiteLib-USER.xcconfig`: this file sets the extra SQLite compilation flags.
|
||||
|
||||
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is no space between -D and the option name.
|
||||
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
|
||||
```
|
||||
|
||||
|
||||
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
|
||||
|
||||
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is one space between -D and the option name.
|
||||
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
|
||||
```
|
||||
|
||||
|
||||
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
|
||||
|
||||
|
||||
```c
|
||||
// As many #define as there are custom SQLite compilation options
|
||||
#define SQLITE_ENABLE_SNAPSHOT
|
||||
#define SQLITE_ENABLE_FTS5
|
||||
```
|
||||
|
||||
|
||||
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
|
||||
|
||||
|
||||
```sh
|
||||
# License: MIT License
|
||||
# https://github.com/swiftlyfalling/SQLiteLib/blob/master/LICENSE
|
||||
@@ -61,52 +63,52 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
# PROJECT PATHS
|
||||
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
|
||||
#######################################################
|
||||
|
||||
|
||||
# The path to the folder containing GRDBCustom.xcodeproj:
|
||||
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
|
||||
|
||||
|
||||
# The path to your custom "SQLiteLib-USER.xcconfig":
|
||||
SQLITELIB_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/SQLiteLib-USER.xcconfig"
|
||||
|
||||
|
||||
# The path to your custom "GRDBCustomSQLite-USER.xcconfig":
|
||||
CUSTOMSQLITE_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig"
|
||||
|
||||
|
||||
# The path to your custom "GRDBCustomSQLite-USER.h":
|
||||
CUSTOMSQLITE_H_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.h"
|
||||
|
||||
|
||||
#######################################################
|
||||
#
|
||||
#######################################################
|
||||
|
||||
|
||||
|
||||
|
||||
if [ ! -d "$GRDB_SOURCE_PATH" ];
|
||||
then
|
||||
echo "error: Path to GRDB source (GRDB_SOURCE_PATH) missing/incorrect: $GRDB_SOURCE_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
SyncFileChanges () {
|
||||
SOURCE=$1
|
||||
DESTINATIONPATH=$2
|
||||
DESTINATIONFILENAME=$3
|
||||
DESTINATION="${DESTINATIONPATH}/${DESTINATIONFILENAME}"
|
||||
|
||||
|
||||
if [ ! -f "$SOURCE" ];
|
||||
then
|
||||
echo "error: Source file missing: $SOURCE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
rsync -a "$SOURCE" "$DESTINATION"
|
||||
}
|
||||
|
||||
|
||||
SyncFileChanges $SQLITELIB_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom/src" "SQLiteLib-USER.xcconfig"
|
||||
SyncFileChanges $CUSTOMSQLITE_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.xcconfig"
|
||||
SyncFileChanges $CUSTOMSQLITE_H_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.h"
|
||||
|
||||
|
||||
echo "Finished syncing"
|
||||
```
|
||||
|
||||
|
||||
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
|
||||
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
|
||||
@@ -116,17 +118,21 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
7. Add the `GRDBCustom.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
|
||||
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
|
||||
|
||||
|
||||
```sh
|
||||
source "${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh"
|
||||
```
|
||||
|
||||
|
||||
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
|
||||
|
||||
|
||||
Select your application target in the "Provide build settings from" menu.
|
||||
|
||||
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
|
||||
|
||||
10. If you have enabled "Hardened Runtime" for your target (**Build Settings**/**Signing**) then you may need to check **Disable Library Validation** under the **Hardened Runtime** section of the **Signing & Capabilities** tab.
|
||||
|
||||
(The build error without this exception is "Library not loaded ... different Team IDs")
|
||||
|
||||
Now you can use GRDB with your custom SQLite build:
|
||||
|
||||
```swift
|
||||
|
||||
@@ -158,7 +158,7 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
LastUpgradeCheck = 2600;
|
||||
TargetAttributes = {
|
||||
56CFC6432C9F1DC9000B5023 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
@@ -293,6 +293,7 @@
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@@ -350,6 +351,7 @@
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
@@ -380,7 +382,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -409,7 +411,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
@@ -425,7 +427,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
@@ -442,7 +444,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1600"
|
||||
LastUpgradeVersion = "2600"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -12,7 +12,7 @@ import os.log
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
final class AppDatabase: Sendable {
|
||||
struct AppDatabase: Sendable {
|
||||
/// Access to the database.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
|
||||
@@ -130,7 +130,7 @@ extension AppDatabase {
|
||||
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() async throws {
|
||||
try await dbWriter.write { [self] db in
|
||||
try await dbWriter.write { db in
|
||||
if try Player.all().isEmpty(db) {
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
|
||||
@@ -64,45 +64,3 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience access to player columns in this file
|
||||
private typealias Columns = Player.Columns
|
||||
|
||||
// MARK: - Player Database Requests
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
// Sort by name in a localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// A request of players ordered by score.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchAll(db)
|
||||
/// }
|
||||
/// let bestPlayer: Player? = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchOne(db)
|
||||
/// }
|
||||
func orderedByScore() -> Self {
|
||||
// Sort by descending score, and then by name, in a
|
||||
// localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(
|
||||
Columns.score.desc,
|
||||
Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
@@ -41,15 +41,22 @@ import GRDB
|
||||
let observation = ValueObservation.tracking { [ordering] db in
|
||||
switch ordering {
|
||||
case .byName:
|
||||
try Player.all().orderedByName().fetchAll(db)
|
||||
try Player
|
||||
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
.fetchAll(db)
|
||||
case .byScore:
|
||||
try Player.all().orderedByScore().fetchAll(db)
|
||||
try Player
|
||||
.order { [
|
||||
$0.score.desc,
|
||||
$0.name.collating(.localizedCaseInsensitiveCompare),
|
||||
] }
|
||||
.fetchAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Start observing the database.
|
||||
// Previous observation, if any, is cancelled.
|
||||
cancellable = observation.start(in: appDatabase.reader) { error in
|
||||
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in
|
||||
// Handle error
|
||||
} onChange: { [unowned self] players in
|
||||
self.players = players
|
||||
|
||||
@@ -316,7 +316,7 @@ Use them in the [query interface](../README.md#the-query-interface):
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
|
||||
// Search in a specific column:
|
||||
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
|
||||
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -565,7 +565,7 @@ Use them in the [query interface](../README.md#the-query-interface):
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
|
||||
// Search in a specific column:
|
||||
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
|
||||
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -32,14 +32,14 @@ try dbQueue.inDatabase { db in
|
||||
CREATE TABLE place (
|
||||
id INTEGER PRIMARY KEY,
|
||||
title TEXT,
|
||||
favorite BOOLEAN NOT NULL,
|
||||
isFavorite BOOLEAN NOT NULL,
|
||||
latitude DOUBLE NOT NULL,
|
||||
longitude DOUBLE NOT NULL
|
||||
)
|
||||
""")
|
||||
|
||||
try db.execute(sql: """
|
||||
INSERT INTO place (title, favorite, latitude, longitude)
|
||||
INSERT INTO place (title, isFavorite, latitude, longitude)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""", arguments: ["Paris", true, 48.85341, 2.3488])
|
||||
let parisId = db.lastInsertedRowID
|
||||
@@ -52,11 +52,11 @@ try! dbQueue.inDatabase { db in
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place")
|
||||
while let row = try rows.next() {
|
||||
let title: String = row["title"]
|
||||
let favorite: Bool = row["favorite"]
|
||||
let isFavorite: Bool = row["isFavorite"]
|
||||
let coordinate = CLLocationCoordinate2D(
|
||||
latitude: row["latitude"],
|
||||
longitude: row["longitude"])
|
||||
print("Fetched", title, favorite, coordinate)
|
||||
print("Fetched", title, isFavorite, coordinate)
|
||||
}
|
||||
|
||||
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
|
||||
@@ -69,35 +69,43 @@ try! dbQueue.inDatabase { db in
|
||||
struct Place {
|
||||
var id: Int64?
|
||||
var title: String?
|
||||
var favorite: Bool
|
||||
var isFavorite: Bool
|
||||
var coordinate: CLLocationCoordinate2D
|
||||
}
|
||||
|
||||
// Adopt FetchableRecord
|
||||
extension Place : FetchableRecord {
|
||||
init(row: Row) {
|
||||
id = row["id"]
|
||||
title = row["title"]
|
||||
favorite = row["favorite"]
|
||||
id = row[Columns.id]
|
||||
title = row[Columns.title]
|
||||
isFavorite = row[Columns.isFavorite]
|
||||
coordinate = CLLocationCoordinate2DMake(
|
||||
row["latitude"],
|
||||
row["longitude"])
|
||||
row[Columns.latitude],
|
||||
row[Columns.longitude])
|
||||
}
|
||||
}
|
||||
|
||||
// Adopt TableRecord
|
||||
extension Place : TableRecord {
|
||||
static let databaseTableName = "place"
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let title = Column("title")
|
||||
static let isFavorite = Column("isFavorite")
|
||||
static let latitude = Column("latitude")
|
||||
static let longitude = Column("longitude")
|
||||
}
|
||||
}
|
||||
|
||||
// Adopt MutablePersistableRecord
|
||||
extension Place : MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) throws {
|
||||
container["id"] = id
|
||||
container["title"] = title
|
||||
container["favorite"] = favorite
|
||||
container["latitude"] = coordinate.latitude
|
||||
container["longitude"] = coordinate.longitude
|
||||
container[Columns.id] = id
|
||||
container[Columns.title] = title
|
||||
container[Columns.isFavorite] = isFavorite
|
||||
container[Columns.latitude] = coordinate.latitude
|
||||
container[Columns.longitude] = coordinate.longitude
|
||||
}
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
@@ -109,13 +117,13 @@ try dbQueue.inDatabase { db in
|
||||
var berlin = Place(
|
||||
id: nil,
|
||||
title: "Berlin",
|
||||
favorite: false,
|
||||
isFavorite: false,
|
||||
coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053))
|
||||
|
||||
try berlin.insert(db)
|
||||
berlin.id // some value
|
||||
|
||||
berlin.favorite = true
|
||||
berlin.isFavorite = true
|
||||
try berlin.update(db)
|
||||
|
||||
// Fetch from SQL
|
||||
@@ -124,13 +132,10 @@ try dbQueue.inDatabase { db in
|
||||
|
||||
//: Avoid SQL with the query interface:
|
||||
|
||||
let title = Column("title")
|
||||
let favorite = Column("favorite")
|
||||
|
||||
berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place
|
||||
berlin = try Place.filter { $0.title == "Berlin" }.fetchOne(db)! // Place
|
||||
let paris = try Place.fetchOne(db, key: 1) // Place?
|
||||
let favoritePlaces = try Place // [Place]
|
||||
.filter(favorite == true)
|
||||
.order(title)
|
||||
.filter { $0.isFavorite == true }
|
||||
.order { $0.title }
|
||||
.fetchAll(db)
|
||||
}
|
||||
@@ -93,7 +93,7 @@ Columns are special expressions that allow some optimizations and niceties:
|
||||
ValueObservation.tracking { db in
|
||||
try Player.fetchOne(db, id: 1)
|
||||
// or
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
try Player.filter { $0.id == 1 }.fetchOne(db)
|
||||
}
|
||||
|
||||
// Non-optimized observations
|
||||
@@ -110,7 +110,7 @@ Columns are special expressions that allow some optimizations and niceties:
|
||||
// Nicer SQL
|
||||
// SELECT * FROM player WHERE id = 1
|
||||
try Player.fetchOne(db, id: 1)
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
try Player.filter { $0.id == 1 }.fetchOne(db)
|
||||
|
||||
// Less nice SQL
|
||||
// SELECT * FROM player WHERE id = 1 LIMIT 1
|
||||
@@ -261,7 +261,7 @@ The basic value types conform to [DatabaseValueConvertible] so that they can fee
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
// ~~~~~~~~~~
|
||||
Player.filter(Column("name") == "O'Brien")
|
||||
Player.filter { $0.name == "O'Brien" }
|
||||
```
|
||||
|
||||
### QueryInterfaceRequest
|
||||
@@ -346,8 +346,9 @@ Functions and methods that build an SQL expression should return an SQLExpressio
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE LENGTH(name) > 0
|
||||
let expression = length(Column("name")) > 0 // SQLExpression
|
||||
Player.filter(expression)
|
||||
Player.filter {
|
||||
length($0.name) > 0 // SQLExpression
|
||||
}
|
||||
```
|
||||
|
||||
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
|
||||
@@ -358,7 +359,7 @@ func date(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
|
||||
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
```
|
||||
|
||||
This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table:
|
||||
@@ -368,7 +369,7 @@ This technique, based on [SQL Interpolation], is composable and works well even
|
||||
// JOIN team ON team.id = player.teamId
|
||||
// WHERE DATE(player.createdAt) = '2020-01-23'
|
||||
let request = Player
|
||||
.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
.filter { date($0.createdAt) == "2020-01-23" }
|
||||
.including(required: Player.team)
|
||||
```
|
||||
|
||||
@@ -583,7 +584,7 @@ SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpres
|
||||
// SELECT * FROM player
|
||||
// WHERE score >= (SELECT AVG(score) FROM player)
|
||||
let averageScore = Player.select(average(Column("score")))
|
||||
Player.filter(Column("score") >= averageScore)
|
||||
Player.filter { $0.score >= averageScore }
|
||||
```
|
||||
|
||||
SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions.
|
||||
|
||||
@@ -175,7 +175,7 @@ func date(_ expression: SQLExpressible) -> SQLExpression {
|
||||
SQL("DATE(\(expression))").sqlExpression
|
||||
}
|
||||
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -207,13 +207,13 @@ try player.updateChanges {
|
||||
|
||||
// SELECT * FROM player ORDER BY score DESC LIMIT 10
|
||||
let bestPlayers: [Player] = try Player
|
||||
.order(scoreColumn.desc)
|
||||
.order(\.score.desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
// SELECT MAX(score) FROM player
|
||||
let maximumScore: Int? = try Player
|
||||
.select(max(scoreColumn))
|
||||
.select { max($0.score) }
|
||||
.asRequestOf(Int.self)
|
||||
.fetchOne(db)
|
||||
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.4.0'
|
||||
s.version = '7.8.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
@@ -9,7 +9,7 @@ Pod::Spec.new do |s|
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.swift_versions = ['6']
|
||||
s.swift_versions = ['6.1']
|
||||
s.ios.deployment_target = '13.0'
|
||||
s.osx.deployment_target = '10.15'
|
||||
s.watchos.deployment_target = '7.0'
|
||||
@@ -21,7 +21,7 @@ Pod::Spec.new do |s|
|
||||
ss.framework = 'Foundation'
|
||||
ss.library = 'sqlite3'
|
||||
ss.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5',
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5 -D GRDBFRAMEWORK',
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@
|
||||
562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; };
|
||||
562206081E420EA4005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; };
|
||||
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
|
||||
56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231A432DCF3A19007676E4 /* TableAlias.swift */; };
|
||||
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; };
|
||||
562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; };
|
||||
5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; };
|
||||
@@ -80,6 +81,7 @@
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */; };
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
|
||||
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
@@ -222,6 +224,7 @@
|
||||
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
|
||||
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
|
||||
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; };
|
||||
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
@@ -272,6 +275,7 @@
|
||||
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
|
||||
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
|
||||
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
|
||||
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */; };
|
||||
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
|
||||
56AE6424222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */; };
|
||||
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
|
||||
@@ -286,6 +290,7 @@
|
||||
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
|
||||
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */; };
|
||||
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
|
||||
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */; };
|
||||
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
|
||||
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
|
||||
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
|
||||
@@ -487,6 +492,7 @@
|
||||
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
|
||||
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
56231A432DCF3A19007676E4 /* TableAlias.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlias.swift; sourceTree = "<group>"; };
|
||||
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
|
||||
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -500,6 +506,7 @@
|
||||
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = "<group>"; };
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
@@ -671,6 +678,7 @@
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
|
||||
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
|
||||
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
|
||||
@@ -767,6 +775,7 @@
|
||||
56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = "<group>"; };
|
||||
56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = "<group>"; };
|
||||
56AACAA722ACED7100A40F2A /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = "<group>"; };
|
||||
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DispatchQueueActor.swift; sourceTree = "<group>"; };
|
||||
56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HasOneThroughAssociation.swift; sourceTree = "<group>"; };
|
||||
56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
|
||||
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = "<group>"; };
|
||||
@@ -788,6 +797,7 @@
|
||||
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
|
||||
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
|
||||
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
|
||||
56BF2281241781C5003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
|
||||
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
|
||||
@@ -993,6 +1003,7 @@
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
|
||||
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
|
||||
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
|
||||
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */,
|
||||
);
|
||||
name = PersistableRecord;
|
||||
sourceTree = "<group>";
|
||||
@@ -1284,6 +1295,7 @@
|
||||
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
|
||||
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */,
|
||||
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */,
|
||||
56231A432DCF3A19007676E4 /* TableAlias.swift */,
|
||||
);
|
||||
path = SQLGeneration;
|
||||
sourceTree = "<group>";
|
||||
@@ -1481,6 +1493,7 @@
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */,
|
||||
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
|
||||
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
|
||||
@@ -1587,18 +1600,19 @@
|
||||
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */,
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
|
||||
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */,
|
||||
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
|
||||
56A238761B9C75030082EB20 /* Row.swift */,
|
||||
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
|
||||
56E9FAD7221053DC00C703A8 /* SQL.swift */,
|
||||
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */,
|
||||
@@ -1608,6 +1622,7 @@
|
||||
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */,
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
@@ -1836,8 +1851,9 @@
|
||||
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 0730;
|
||||
LastUpgradeCheck = 1400;
|
||||
LastUpgradeCheck = 2600;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
56E5D7F81B4D422D00430942 = {
|
||||
@@ -2003,6 +2019,7 @@
|
||||
56677C15241D14450050755D /* FailureTestCase.swift in Sources */,
|
||||
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
|
||||
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
|
||||
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
|
||||
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
|
||||
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
|
||||
@@ -2107,6 +2124,7 @@
|
||||
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
|
||||
5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
|
||||
56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */,
|
||||
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
|
||||
56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */,
|
||||
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
|
||||
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
|
||||
@@ -2168,6 +2186,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */,
|
||||
56158780288D875E00A67323 /* Optional.swift in Sources */,
|
||||
@@ -2176,6 +2195,7 @@
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
|
||||
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */,
|
||||
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */,
|
||||
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
@@ -2199,6 +2219,7 @@
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */,
|
||||
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
|
||||
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
@@ -2531,6 +2552,7 @@
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_MODULE_VERIFIER = YES;
|
||||
INFOPLIST_FILE = Support/Info.plist;
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
@@ -2538,6 +2560,7 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
|
||||
SKIP_INSTALL = YES;
|
||||
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
|
||||
SUPPORTS_MACCATALYST = YES;
|
||||
@@ -2562,6 +2585,7 @@
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_MODULE_VERIFIER = YES;
|
||||
INFOPLIST_FILE = Support/Info.plist;
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
@@ -2569,6 +2593,7 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
|
||||
SKIP_INSTALL = YES;
|
||||
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
|
||||
SUPPORTS_MACCATALYST = YES;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1400"
|
||||
LastUpgradeVersion = "2600"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
#if !canImport(Darwin)
|
||||
@@ -87,7 +90,7 @@ public struct Configuration: Sendable {
|
||||
/// with the number of snapshots.
|
||||
///
|
||||
/// The default configuration label is nil.
|
||||
public var label: String? = nil
|
||||
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
|
||||
@@ -144,7 +147,7 @@ public struct Configuration: Sendable {
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
|
||||
/// } catch {
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when an error occurs:
|
||||
@@ -173,7 +176,7 @@ public struct Configuration: Sendable {
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
|
||||
/// } catch {
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(error)
|
||||
@@ -329,7 +332,7 @@ public struct Configuration: Sendable {
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
var readonlyBusyMode: Database.BusyMode?
|
||||
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
@@ -387,7 +390,7 @@ public struct Configuration: Sendable {
|
||||
/// ``qos`` property.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
public var targetQueue: DispatchQueue?
|
||||
|
||||
/// The target dispatch queue for write database accesses.
|
||||
///
|
||||
@@ -395,7 +398,7 @@ public struct Configuration: Sendable {
|
||||
/// by ``targetQueue``.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
public var writeTargetQueue: DispatchQueue?
|
||||
|
||||
#if os(iOS)
|
||||
/// A boolean value indicating whether the database connection releases
|
||||
@@ -421,6 +424,22 @@ public struct Configuration: Sendable {
|
||||
/// reveals that a lot of time is spent opening new SQLite connections.
|
||||
public var persistentReadOnlyConnections = false
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// A custom schema source.
|
||||
///
|
||||
/// The use case for a custom schema source is enabling GRDB features that
|
||||
/// would not work with the built-in schema introspection that is provided
|
||||
/// by SQLite. For example, a custom schema source can help record types
|
||||
/// that read or write in a database view.
|
||||
///
|
||||
/// The schema source is automatically disabled during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration.
|
||||
|
||||
+401
-229
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -387,7 +390,7 @@ extension SQLStatementCursor: Cursor {
|
||||
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
|
||||
|
||||
// Compile next statement
|
||||
var statementEnd: UnsafePointer<CChar>? = nil
|
||||
var statementEnd: UnsafePointer<CChar>?
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
|
||||
+92
-26
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -113,6 +116,11 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``resumeNotification``
|
||||
/// - ``suspendNotification``
|
||||
///
|
||||
/// ### The Schema Source
|
||||
///
|
||||
/// - ``schemaSource``
|
||||
/// - ``withSchemaSource(_:execute:)``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``add(tokenizer:)``
|
||||
@@ -169,7 +177,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// connection has been opened is an SQLite misuse, and has no effect.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? {
|
||||
didSet {
|
||||
if logError != nil {
|
||||
_registerErrorLogCallback { (_, code, message) in
|
||||
@@ -187,6 +195,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// The database configuration.
|
||||
public let configuration: Configuration
|
||||
|
||||
/// The current schema source.
|
||||
///
|
||||
/// By default, it is the ``Configuration/schemaSource``
|
||||
/// of ``configuration``. To modify the schema source,
|
||||
/// use ``withSchemaSource(_:execute:)``.
|
||||
///
|
||||
/// The schema source is automatically disabled (nil) during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public internal(set) var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
/// A description of this database connection.
|
||||
///
|
||||
/// The returned string is based on the ``Configuration/label``
|
||||
@@ -442,6 +463,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.schemaSource = configuration.schemaSource
|
||||
self.path = path
|
||||
|
||||
// We do not report read-only transactions to transaction observers, so
|
||||
@@ -459,7 +481,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
|
||||
// See <https://www.sqlite.org/c3ref/open.html>
|
||||
var sqliteConnection: SQLiteConnection? = nil
|
||||
var sqliteConnection: SQLiteConnection?
|
||||
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// https://www.sqlite.org/c3ref/open.html
|
||||
@@ -806,7 +828,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
collationPointer,
|
||||
{ (collationPointer, length1, buffer1, length2, buffer2) in
|
||||
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
|
||||
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
|
||||
return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
|
||||
}, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
@@ -1149,7 +1171,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// See <https://www.sqlite.org/c3ref/interrupt.html>
|
||||
func interrupt() {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
if let sqliteConnection {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Suspension
|
||||
@@ -1223,22 +1247,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancels the current database access. All statements but ROLLBACK
|
||||
/// will throw `CancellationError`, until `uncancel()` is called.
|
||||
///
|
||||
/// This method can be called from any thread.
|
||||
func cancel() {
|
||||
let needsInterrupt = suspensionMutex.withLock { suspension in
|
||||
if suspension.isCancelled {
|
||||
return false
|
||||
/// Returns a closure that cancels the current database access.
|
||||
/// Most statements will throw `CancellationError`, until `uncancel()`
|
||||
/// is called.
|
||||
var cancel: @Sendable () -> Void {
|
||||
// Workaround the fact that SQLiteConnection is not Sendable.
|
||||
struct Connection: @unchecked Sendable {
|
||||
var sqliteConnection: SQLiteConnection?
|
||||
}
|
||||
let connection = Connection(sqliteConnection: sqliteConnection)
|
||||
|
||||
return { [suspensionMutex, connection] in
|
||||
let needsInterrupt = suspensionMutex.withLock { suspension in
|
||||
if suspension.isCancelled {
|
||||
return false
|
||||
}
|
||||
|
||||
suspension.isCancelled = true
|
||||
return suspension.interruptsWhenCancelled
|
||||
}
|
||||
|
||||
suspension.isCancelled = true
|
||||
return suspension.interruptsWhenCancelled
|
||||
}
|
||||
|
||||
if needsInterrupt {
|
||||
interrupt()
|
||||
if needsInterrupt {
|
||||
if let sqliteConnection = connection.sqliteConnection {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1275,7 +1308,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
|
||||
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
|
||||
var statement: SQLiteStatement? = nil
|
||||
var statement: SQLiteStatement?
|
||||
let sql = "PRAGMA journal_mode"
|
||||
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
|
||||
defer { sqlite3_finalize(statement) }
|
||||
@@ -1318,6 +1351,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return
|
||||
}
|
||||
|
||||
// Commits when read-only are just like rollbacks above.
|
||||
if statement.transactionEffect == .commitTransaction && isReadOnly {
|
||||
return
|
||||
}
|
||||
|
||||
// Suspension should not prevent adjusting the read-only mode.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1715>.
|
||||
if statement.isQueryOnlyPragma {
|
||||
@@ -1467,7 +1505,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that transaction has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error? = nil
|
||||
var firstError: Error?
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1610,7 +1648,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that savepoint has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error? = nil
|
||||
var firstError: Error?
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1728,7 +1766,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
if isInsideTransaction {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
|
||||
/// Commits a database transaction.
|
||||
@@ -1983,6 +2021,34 @@ extension Database {
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
/// Returns the count of changes executed by one statement execution.
|
||||
func countChanges<T>(_ count: inout Int, forTable tableName: String, updates: () throws -> T) throws -> T {
|
||||
// Database.changesCount calls sqlite3_changes(), whose documentation says:
|
||||
//
|
||||
// > https://sqlite.org/c3ref/changes.html
|
||||
// > Changes to a view that are intercepted by INSTEAD OF triggers are not counted.
|
||||
//
|
||||
// We want to support INSTEAD OF triggers, so we prefer to use
|
||||
// sqlite3_total_changes() for views.
|
||||
//
|
||||
// At the same time, FTS5 has sqlite3_total_changes() report changes
|
||||
// even when database is not changed (https://github.com/groue/GRDB.swift/issues/1820)
|
||||
//
|
||||
// Well, let's do our best:
|
||||
if try viewExists(tableName) {
|
||||
let prevCount = totalChangesCount
|
||||
let result = try updates()
|
||||
count = totalChangesCount - prevCount
|
||||
return result
|
||||
} else {
|
||||
let result = try updates()
|
||||
count = changesCount
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database-Related Types
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -53,12 +56,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
|
||||
/// <https://www.sqlite.org/c3ref/create_collation.html>
|
||||
typealias XCompare = @Sendable (
|
||||
_ length1: CInt,
|
||||
_ buffer1: UnsafeRawPointer,
|
||||
_ length2: CInt,
|
||||
_ buffer2: UnsafeRawPointer
|
||||
) -> CInt
|
||||
|
||||
/// The identifier of the collation.
|
||||
public var id: ID { ID(name: name) }
|
||||
|
||||
/// The name of the collation.
|
||||
public let name: String
|
||||
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
|
||||
let xCompare: XCompare
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
@@ -75,21 +87,16 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
/// - parameters:
|
||||
/// - name: The collation name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
|
||||
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
|
||||
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
|
||||
return CInt(function(string1, string2).rawValue)
|
||||
})
|
||||
}
|
||||
|
||||
init(_ name: String, xCompare: @escaping XCompare) {
|
||||
self.name = name
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
|
||||
length: Int(length1),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
let string2 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
|
||||
length: Int(length2),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
self.xCompare = xCompare
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A custom SQL function or aggregate.
|
||||
@@ -82,20 +85,43 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
|
||||
/// have exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public init(
|
||||
public convenience init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv[index]!)
|
||||
}
|
||||
let result = try function(arguments)
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(context)
|
||||
case .int64(let int64):
|
||||
sqlite3_result_int64(context, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(context, double)
|
||||
case .string(let string):
|
||||
sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
xFunc: @escaping XFunc)
|
||||
{
|
||||
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.isPure = pure
|
||||
self.kind = .function { (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
return try function(arguments)
|
||||
}
|
||||
self.kind = .function(xFunc)
|
||||
}
|
||||
|
||||
/// Creates an SQL aggregate function.
|
||||
@@ -173,13 +199,20 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// }
|
||||
/// return int * int
|
||||
/// }
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.read { db in
|
||||
/// db.add(function: square)
|
||||
///
|
||||
/// // SELECT square(score) FROM player
|
||||
/// let squaredScores = let Player
|
||||
/// .select(square(Column("score")), as: Int.self)
|
||||
/// .select({ square($0.score) }, as: Int.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
@@ -249,11 +282,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class FunctionDefinition {
|
||||
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
|
||||
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
|
||||
throws -> (any DatabaseValueConvertible)?)
|
||||
let xFunc: XFunc
|
||||
init(xFunc: @escaping XFunc)
|
||||
{
|
||||
self.compute = compute
|
||||
self.xFunc = xFunc
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,11 +308,19 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
typealias XFunc = @Sendable (
|
||||
_ argc: CInt,
|
||||
_ argv: UnsafeMutablePointer<OpaquePointer?>,
|
||||
_ context: OpaquePointer?
|
||||
) throws -> Void
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private enum Kind: Sendable {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
|
||||
case function(XFunc)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(@Sendable () -> any DatabaseAggregate)
|
||||
@@ -289,8 +329,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let compute):
|
||||
return FunctionDefinition(compute: compute)
|
||||
case .function(let xFunc):
|
||||
return FunctionDefinition(xFunc: xFunc)
|
||||
case .aggregate(let makeAggregate):
|
||||
return AggregateDefinition(makeAggregate: makeAggregate)
|
||||
}
|
||||
@@ -305,9 +345,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: definition.compute(argc, argv),
|
||||
in: sqliteContext)
|
||||
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
@@ -457,7 +495,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
/// ```
|
||||
public protocol DatabaseAggregate {
|
||||
public protocol DatabaseAggregate: GRDBSendableMetatype {
|
||||
/// Creates an aggregate.
|
||||
///
|
||||
/// A new instance is created for each aggregation.
|
||||
|
||||
@@ -352,40 +352,29 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -403,7 +392,14 @@ extension DatabasePool: DatabaseReader {
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
@@ -436,35 +432,16 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -584,7 +561,14 @@ extension DatabasePool: DatabaseReader {
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
@@ -700,7 +684,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
|
||||
guard let readerPool else {
|
||||
@@ -802,7 +786,7 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
@@ -818,22 +802,32 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
asyncBarrierWriteWithoutTransaction { dbResult in
|
||||
do {
|
||||
try dbAccess.checkCancellation()
|
||||
let db = try dbResult.get()
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try updates(db)
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
// Pool.barrier does not support async calls (yet?).
|
||||
// So we perform cancellation checks just as in
|
||||
// the async version of SerializedDatabase.execute().
|
||||
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
|
||||
return try await withTaskCancellationHandler {
|
||||
try Task.checkCancellation()
|
||||
return try await readerPool.barrier {
|
||||
try Task.checkCancellation()
|
||||
return try writer.sync { db in
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try updates(db)
|
||||
}
|
||||
}
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -956,7 +950,7 @@ extension DatabasePool {
|
||||
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// Creates a database snapshot that allows concurrent accesses to an
|
||||
/// unchanging database content, as it exists at the moment the snapshot
|
||||
/// is created.
|
||||
|
||||
@@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
@@ -248,8 +248,14 @@ extension DatabaseQueue: DatabaseReader {
|
||||
) {
|
||||
writer.async { db in
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
@@ -272,7 +278,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(value)
|
||||
}
|
||||
@@ -296,8 +302,14 @@ extension DatabaseQueue: DatabaseReader {
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
@@ -385,7 +397,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
@@ -396,7 +408,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
|
||||
@@ -22,14 +22,14 @@ import Dispatch
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
/// - ``read(_:)-3806d``
|
||||
/// - ``read(_:)-4d1da``
|
||||
/// - ``read(_:)-5mfwu``
|
||||
/// - ``readPublisher(receiveOn:value:)``
|
||||
/// - ``asyncRead(_:)``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeRead(_:)-5i7tf``
|
||||
/// - ``unsafeRead(_:)-5gsav``
|
||||
/// - ``unsafeRead(_:)-90w0p``
|
||||
/// - ``unsafeReentrantRead(_:)``
|
||||
/// - ``asyncUnsafeRead(_:)``
|
||||
///
|
||||
@@ -215,7 +215,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// database access, or the error thrown by `value`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules read-only database operations for execution, and
|
||||
@@ -319,7 +319,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// database access, or the error thrown by `value`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
@@ -652,7 +652,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.read(value)
|
||||
}
|
||||
@@ -669,7 +669,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.unsafeRead(value)
|
||||
}
|
||||
|
||||
@@ -256,8 +256,8 @@ extension DatabaseRegion {
|
||||
}
|
||||
} else {
|
||||
// full database
|
||||
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
|
||||
let schema = try db.schema(schemaIdentifier)
|
||||
return try db.fetchSchemaIdentifiers().flatMap { schemaID in
|
||||
let schema = try db.schema(schemaID)
|
||||
return try schema.objects
|
||||
.filter { $0.type == .table }
|
||||
.flatMap { table in
|
||||
|
||||
@@ -201,7 +201,11 @@ extension DatabasePublishers {
|
||||
self.observation = observation
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
public func receive<S>(subscriber: S)
|
||||
where S: Subscriber & GRDBSendableMetatype,
|
||||
Failure == S.Failure,
|
||||
Output == S.Input
|
||||
{
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
observation: observation,
|
||||
@@ -212,7 +216,7 @@ extension DatabasePublishers {
|
||||
|
||||
private class DatabaseRegionSubscription<Downstream>:
|
||||
Subscription, @unchecked Sendable
|
||||
where Downstream: Subscriber,
|
||||
where Downstream: Subscriber & GRDBSendableMetatype,
|
||||
Downstream.Failure == Error,
|
||||
Downstream.Input == Database
|
||||
{
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
/// A type that provides information about the database schema.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// The use case for a custom schema source is to enable GRDB features that
|
||||
/// would not work with the built-in schema introspection provided
|
||||
/// by SQLite.
|
||||
///
|
||||
/// For example, if your database schema contains a view and you wish to use
|
||||
/// GRDB features that need a primary key, such as the
|
||||
/// ``FetchableRecord/find(_:id:)`` record method, or the persistence
|
||||
/// methods of the ``PersistableRecord`` protocol, then use a schema source
|
||||
/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. See
|
||||
/// <doc:ViewRecords> for a detailed guide about such views.
|
||||
///
|
||||
/// ## Enabling a Schema Source
|
||||
///
|
||||
/// To enable a schema source in a database connection, configure its
|
||||
/// ``Configuration/schemaSource``:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct MySchemaSource: DatabaseSchemaSource { ... }
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = MySchemaSource()
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// ## Schema Sources and Migrations
|
||||
///
|
||||
/// By default, schema sources are disabled during <doc:Migrations>. In
|
||||
/// migrations that need a schema source, you can use
|
||||
/// ``Database/withSchemaSource(_:execute:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// migrator.registerMigration("My migration") { db in
|
||||
/// // No schema source is enabled at this point.
|
||||
/// try db.withSchemaSource(MySchemaSource()) {
|
||||
/// // Here the provided schema source is in effect.
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Take care that **a good migration is a migration that is never
|
||||
/// modified once it has shipped**: check
|
||||
/// <doc:Migrations#Good-Practices-for-Defining-Migrations>.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Customizing the Database Schema
|
||||
///
|
||||
/// - ``columnsForPrimaryKey(_:inView:)``
|
||||
///
|
||||
/// ### Chaining Schema Sources
|
||||
///
|
||||
/// - ``then(_:)``
|
||||
public protocol DatabaseSchemaSource: Sendable {
|
||||
/// Returns the names of the columns for the primary key in the
|
||||
/// provided database view.
|
||||
///
|
||||
/// Return `nil` if no customization should happen. Return an empty
|
||||
/// array to specify that the view has no primary key. The default
|
||||
/// implementation returns `nil`.
|
||||
///
|
||||
/// In your implementation, make sure that the returned columns define
|
||||
/// a genuine **primary key**:
|
||||
///
|
||||
/// - All columns exist in the provided view.
|
||||
/// - The set of columns reliably identifies and distinguishes between
|
||||
/// each individual row in the view.
|
||||
/// - No column contains NULL values.
|
||||
///
|
||||
/// It is a programmer error with undefined consequences to miss
|
||||
/// those requirements.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A schema source that specifies that all views are identified by
|
||||
/// // their "id" column:
|
||||
/// struct MySchemaSource: DatabaseSchemaSource {
|
||||
/// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) {
|
||||
/// ["id"]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // A database connection configured with the schema source.
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = MySchemaSource()
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
|
||||
///
|
||||
/// // A record type that feeds from a view.
|
||||
/// struct Player: Decodable, Identifiable, FetchableRecord {
|
||||
/// static let databaseTableName = "playerView"
|
||||
/// var id: String
|
||||
/// var name: String
|
||||
/// }
|
||||
///
|
||||
/// // Thanks to the schema source, we can fetch players by id:
|
||||
/// let player = try dbQueue.read { db in
|
||||
/// try Player.find(db, id: "alice")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Schema Sources in Libraries
|
||||
///
|
||||
/// When you are developing a schema source for a library, some extra
|
||||
/// care is necessary whenever the database file is owned by the users
|
||||
/// of your library. Your users may define views for their own purposes,
|
||||
/// and your library knows nothing about the eventual primary key of
|
||||
/// those views.
|
||||
///
|
||||
/// In this case, make your schema source `public`, and have this method
|
||||
/// return `nil` for those unknown views. If needed, use the `db`
|
||||
/// argument and query the database schema with
|
||||
/// <doc:DatabaseSchemaIntrospection> methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A well-behaved schema source defined by a library is public
|
||||
/// // and returns nil for unknown views.
|
||||
/// public struct MyLibrarySchemaSource: DatabaseSchemaSource {
|
||||
/// public func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) {
|
||||
/// if view.name == "playerView" {
|
||||
/// // This is a view managed by my library:
|
||||
/// return ["id"]
|
||||
/// } else if try db.tableExists(view.name + "MyLibrary") {
|
||||
/// // This is a view managed by my library:
|
||||
/// return ["uuid"]
|
||||
/// } else {
|
||||
/// // Not a view managed by my library:
|
||||
/// // don't mess with user's schema
|
||||
/// return nil
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// With such a setup, your user will be able to deal with their
|
||||
/// own views, by chaining your schema source with other ones
|
||||
/// (see ``DatabaseSchemaSource/then(_:)``):
|
||||
///
|
||||
/// ```swift
|
||||
/// // Application code
|
||||
/// import MyLibrary
|
||||
/// import GRDB
|
||||
///
|
||||
/// let myLibrarySchemaSource = MyLibrarySchemaSource()
|
||||
/// let customSchemaSource = TheirCustomSchemaSource()
|
||||
/// let schemaSource = myLibrarySchemaSource.then(customSchemaSource)
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = schemaSource
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - db: A database connection.
|
||||
/// - view: The identifier of a database view.
|
||||
func columnsForPrimaryKey(
|
||||
_ db: Database,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]?
|
||||
}
|
||||
|
||||
extension DatabaseSchemaSource {
|
||||
public func columnsForPrimaryKey(
|
||||
_ db: Database,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]? {
|
||||
nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Combined2SchemaSource
|
||||
|
||||
extension DatabaseSchemaSource {
|
||||
/// Returns a schema source that queries `other` when this source does
|
||||
/// not perform a customization.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let schemaSource1 = SomeSchemaSource()
|
||||
/// let schemaSource2 = AnotherSchemaSource()
|
||||
/// let schemaSource = schemaSource1.then(schemaSource2)
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = schemaSource
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource {
|
||||
Chained2SchemaSource(first: self, second: other)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move to parameter packs eventually. Parameter packs in generic types
|
||||
// are only available in macOS 14.0.0 or newer.
|
||||
// This schema source is designed to tame bad citizens that customize tables
|
||||
// and views they do not own (such as insufficienly robust schema sources
|
||||
// exposed by external libraries). We should NEVER MERGE the results of the
|
||||
// schema sources.
|
||||
struct Chained2SchemaSource<Source1, Source2>: DatabaseSchemaSource
|
||||
where Source1: DatabaseSchemaSource,
|
||||
Source2: DatabaseSchemaSource
|
||||
{
|
||||
var first: Source1
|
||||
var second: Source2
|
||||
|
||||
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
|
||||
if let result = try first.columnsForPrimaryKey(db, inView: view) { return result }
|
||||
if let result = try second.columnsForPrimaryKey(db, inView: view) { return result }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -113,7 +113,14 @@ public final class DatabaseSnapshot {
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
reader.reentrantSync { db in
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +159,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await reader.execute(value)
|
||||
}
|
||||
@@ -173,7 +180,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A database connection that allows concurrent accesses to an unchanging
|
||||
@@ -294,36 +297,25 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader(self.poolCompletion(db))
|
||||
}
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try value(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
let (reader, releaseReader) = try await readerPool.get()
|
||||
var readerCompletion: PoolCompletion?
|
||||
defer {
|
||||
// readerCompletion might be null in cancelled database accesses
|
||||
releaseReader(readerCompletion ?? .reuse)
|
||||
}
|
||||
let (result, completion) = try await reader.execute { db in
|
||||
let result = Result { try value(db) }
|
||||
let completion = poolCompletion(db)
|
||||
return (result, completion)
|
||||
}
|
||||
readerCompletion = completion
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
public func asyncRead(
|
||||
@@ -353,7 +345,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -541,13 +541,20 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -584,13 +591,20 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -623,13 +637,20 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -657,13 +678,20 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -696,13 +724,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -736,13 +771,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -772,13 +814,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -808,8 +857,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
|
||||
@@ -22,18 +22,18 @@ import Dispatch
|
||||
/// ### Writing into the Database
|
||||
///
|
||||
/// - ``write(_:)-76inz``
|
||||
/// - ``write(_:)-3db50``
|
||||
/// - ``write(_:)-4gnqx``
|
||||
/// - ``writePublisher(receiveOn:updates:)``
|
||||
/// - ``writePublisher(receiveOn:updates:thenRead:)``
|
||||
/// - ``writeWithoutTransaction(_:)-4qh1w``
|
||||
/// - ``writeWithoutTransaction(_:)-67mri``
|
||||
/// - ``writeWithoutTransaction(_:)-18zhj``
|
||||
/// - ``asyncWrite(_:completion:)``
|
||||
/// - ``asyncWriteWithoutTransaction(_:)``
|
||||
///
|
||||
/// ### Exclusive Access to the Database
|
||||
///
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-48d63``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-11q6c``
|
||||
/// - ``asyncBarrierWriteWithoutTransaction(_:)``
|
||||
///
|
||||
/// ### Reading from the Latest Committed Database State
|
||||
@@ -130,7 +130,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
@@ -552,7 +552,7 @@ extension DatabaseWriter {
|
||||
// This method is declared on DatabaseWriter instead of DatabaseReader,
|
||||
// so that it is not available on DatabaseSnaphot. VACUUM INTO is not
|
||||
// available inside the transaction that is kept open by DatabaseSnaphot.
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
@@ -640,7 +640,7 @@ extension DatabaseWriter {
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
public func write<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writeWithoutTransaction { db in
|
||||
var result: T?
|
||||
@@ -665,7 +665,7 @@ extension DatabaseWriter {
|
||||
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
@@ -885,7 +885,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.read(value)
|
||||
}
|
||||
@@ -902,7 +902,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.unsafeRead(value)
|
||||
}
|
||||
@@ -936,7 +936,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.writeWithoutTransaction(updates)
|
||||
}
|
||||
@@ -947,7 +947,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
#if os(Linux)
|
||||
@preconcurrency import Dispatch
|
||||
#else
|
||||
import Dispatch
|
||||
#endif
|
||||
|
||||
/// An actor that runs in a DispatchQueue.
|
||||
///
|
||||
/// Inspired by <https://forums.swift.org/t/using-dispatchqueue-as-actors-serial-executor-under-linux/75260/3>
|
||||
actor DispatchQueueActor {
|
||||
private let executor: DispatchQueueExecutor
|
||||
|
||||
/// - precondition: the queue is serial, or flags contains `.barrier`.
|
||||
init(queue: DispatchQueue, flags: DispatchWorkItemFlags = []) {
|
||||
self.executor = DispatchQueueExecutor(queue: queue, flags: flags)
|
||||
}
|
||||
|
||||
nonisolated var unownedExecutor: UnownedSerialExecutor {
|
||||
executor.asUnownedSerialExecutor()
|
||||
}
|
||||
|
||||
func execute<T>(_ work: () throws -> T) rethrows -> T {
|
||||
try work()
|
||||
}
|
||||
}
|
||||
|
||||
private final class DispatchQueueExecutor: SerialExecutor {
|
||||
private let queue: DispatchQueue
|
||||
private let flags: DispatchWorkItemFlags
|
||||
|
||||
init(queue: DispatchQueue, flags: DispatchWorkItemFlags) {
|
||||
self.queue = queue
|
||||
self.flags = flags
|
||||
}
|
||||
|
||||
func enqueue(_ job: UnownedJob) {
|
||||
queue.async(flags: flags) {
|
||||
job.runSynchronously(on: self.asUnownedSerialExecutor())
|
||||
}
|
||||
}
|
||||
|
||||
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
|
||||
UnownedSerialExecutor(ordinary: self)
|
||||
}
|
||||
|
||||
func checkIsolated() {
|
||||
dispatchPrecondition(condition: .onQueue(queue))
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
extension DispatchQueueExecutor: @unchecked Sendable {}
|
||||
#endif
|
||||
+393
-121
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -52,6 +55,8 @@ import Foundation
|
||||
/// - ``subscript(_:)-9c1fw``
|
||||
/// - ``subscript(_:)-3jhwm``
|
||||
/// - ``subscript(_:)-7krrg``
|
||||
/// - ``decode(_:atIndex:)-33ykh``
|
||||
/// - ``decode(_:atIndex:)-3btwn``
|
||||
/// - ``withUnsafeData(atIndex:_:)``
|
||||
/// - ``dataNoCopy(atIndex:)``
|
||||
///
|
||||
@@ -61,7 +66,8 @@ import Foundation
|
||||
/// - ``subscript(_:)-4k8od``
|
||||
/// - ``subscript(_:)-9rbo7``
|
||||
/// - ``coalesce(_:)-359k7``
|
||||
/// - ``coalesce(_:)-6nbah``
|
||||
/// - ``decode(_:forColumn:)-4i1o4``
|
||||
/// - ``decode(_:forColumn:)-4rhs4``
|
||||
/// - ``withUnsafeData(named:_:)``
|
||||
/// - ``dataNoCopy(named:)``
|
||||
///
|
||||
@@ -70,6 +76,9 @@ import Foundation
|
||||
/// - ``subscript(_:)-9txgm``
|
||||
/// - ``subscript(_:)-2esg7``
|
||||
/// - ``subscript(_:)-wl9a``
|
||||
/// - ``coalesce(_:)-6nbah``
|
||||
/// - ``decode(_:forColumn:)-1ljuo``
|
||||
/// - ``decode(_:forColumn:)-47qeg``
|
||||
/// - ``withUnsafeData(at:_:)``
|
||||
/// - ``dataNoCopy(_:)``
|
||||
///
|
||||
@@ -84,6 +93,10 @@ import Foundation
|
||||
/// - ``subscript(_:)-8god3``
|
||||
/// - ``subscript(_:)-jwnx``
|
||||
/// - ``subscript(_:)-6ge6t``
|
||||
/// - ``decode(_:forKey:)-9bbd3``
|
||||
/// - ``decode(_:forKey:)-2w6lc``
|
||||
/// - ``decode(_:forKey:)-2soc2``
|
||||
/// - ``decodeIfPresent(_:forKey:)``
|
||||
/// - ``PrefetchedRowsView``
|
||||
/// - ``ScopesTreeView``
|
||||
/// - ``ScopesView``
|
||||
@@ -119,6 +132,10 @@ import Foundation
|
||||
///
|
||||
/// - ``RowAdapter``
|
||||
///
|
||||
/// ### Errors
|
||||
///
|
||||
/// - ``RowDecodingError``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``RowCursor``
|
||||
@@ -452,7 +469,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
try! decode(Value.self, forColumn: columnName)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -489,7 +506,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
try! decode(Value.self, forColumn: columnName)
|
||||
}
|
||||
|
||||
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
|
||||
@@ -533,7 +550,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
try! decode(Value.self, forColumn: column)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -573,7 +590,7 @@ extension Row {
|
||||
-> Value
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
try! decode(Value.self, forColumn: column)
|
||||
}
|
||||
|
||||
/// Calls the given closure with the `Data` at given index.
|
||||
@@ -739,12 +756,13 @@ extension Row {
|
||||
|
||||
// MARK: - Extracting Records
|
||||
|
||||
/// The record associated to the given scope.
|
||||
/// Returns the record associated to the given key.
|
||||
///
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
/// The ``JoinableRequest/including(required:)`` and
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
@@ -769,26 +787,28 @@ extension Row {
|
||||
/// let request = Book
|
||||
/// .including(required: Book.author
|
||||
/// .including(required: Author.country))
|
||||
/// let bookRow = try Row.fetchOne(db, request)!
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let book = try Book(row: bookRow)
|
||||
/// let author: Author = bookRow["author"]
|
||||
/// let country: Country = bookRow["country"]
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author = row["author"]
|
||||
/// let country: Country = row["country"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``scopesTree``
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
///
|
||||
/// - parameter scope: A scope identifier.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
|
||||
try! decode(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// The eventual record associated to the given scope.
|
||||
/// Returns the eventual record associated to the given key.
|
||||
///
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
/// The ``JoinableRequest/including(required:)`` and
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
@@ -809,25 +829,26 @@ extension Row {
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// // Fetch a book, with its author, and the country of its author.
|
||||
/// // Fetch a book, with its eventual author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(optional: Book.author
|
||||
/// .including(optional: Author.country))
|
||||
/// let bookRow = try Row.fetchOne(db, request)!
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let book = try Book(row: bookRow)
|
||||
/// let author: Author? = bookRow["author"]
|
||||
/// let country: Country? = bookRow["country"]
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author? = row["author"]
|
||||
/// let country: Country? = row["country"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``scopesTree``
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
///
|
||||
/// - parameter scope: A scope identifier.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
|
||||
try! decodeIfPresent(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// A collection of prefetched records associated to the given
|
||||
/// Returns a collection of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
@@ -843,10 +864,10 @@ extension Row {
|
||||
/// struct Book: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let authorRow = try Row.fetchOne(db, request)!
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: authorRow)
|
||||
/// let books: [Book] = author["books"]
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: [Book] = row["books"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
@@ -861,7 +882,8 @@ extension Row {
|
||||
try! decode(Records.self, forKey: key)
|
||||
}
|
||||
|
||||
/// A set prefetched records associated to the given association key.
|
||||
/// Returns the set of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
@@ -876,10 +898,10 @@ extension Row {
|
||||
/// struct Book: TableRecord, FetchableRecord, Hashable { }
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let authorRow = try Row.fetchOne(db, request)!
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: authorRow)
|
||||
/// let books: Set<Book> = author["books"]
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: Set<Book> = row["books"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
@@ -935,7 +957,8 @@ extension Row {
|
||||
/// // Prints [code:"US" name:"United States of America"]
|
||||
/// ```
|
||||
///
|
||||
/// See also ``scopesTree``.
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
public var scopes: ScopesView {
|
||||
impl.scopes(prefetchedRows: prefetchedRows)
|
||||
}
|
||||
@@ -1065,10 +1088,28 @@ extension Row {
|
||||
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
|
||||
/// let score = try row.decode(Int.self, atIndex: 0) // 42
|
||||
/// let score: Int = try row.decode(atIndex: 0) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
|
||||
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
|
||||
/// let name: String = try row.decode(atIndex: 0) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
|
||||
/// let name: String? = try row.decode(atIndex: 0) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
@@ -1082,13 +1123,37 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain the column, or if the SQLite value is NULL,
|
||||
/// or if the SQLite value can not be converted to `Value`, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: "score") // 42
|
||||
/// let score: Int = try row.decode(forColumn: "score") // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: "name") // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "name") // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "missing") // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
forColumn columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
@@ -1100,6 +1165,47 @@ extension Row {
|
||||
}
|
||||
return try Value.decode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
|
||||
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn column: some ColumnExpression)
|
||||
throws -> Value
|
||||
{
|
||||
try decode(type, forColumn: column.name)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods
|
||||
@@ -1114,11 +1220,29 @@ extension Row {
|
||||
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
|
||||
/// let score = try row.decode(Int.self, atIndex: 0) // 42
|
||||
/// let score: Int = try row.decode(atIndex: 0) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
|
||||
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
|
||||
/// let name: String = try row.decode(atIndex: 0) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
|
||||
/// let name: String? = try row.decode(atIndex: 0) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
@@ -1136,13 +1260,37 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain the column, or if the SQLite value is NULL,
|
||||
/// or if the SQLite value can not be converted to `Value`, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: "score") // 42
|
||||
/// let score: Int = try row.decode(forColumn: "score") // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: "name") // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "name") // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "missing") // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
forColumn columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
@@ -1155,6 +1303,51 @@ extension Row {
|
||||
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
|
||||
/// conversions](https://www.sqlite.org/datatype3.html).
|
||||
///
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
|
||||
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn column: some ColumnExpression)
|
||||
throws -> Value
|
||||
{
|
||||
try decode(type, forColumn: column.name)
|
||||
}
|
||||
|
||||
// Support for fast decoding in scoped rows
|
||||
@usableFromInline
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
@@ -1187,37 +1380,51 @@ extension Row {
|
||||
// MARK: - Throwing Record Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the eventual record associated with the given scope.
|
||||
/// Returns the eventual record associated to the given key.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
///
|
||||
/// The result is nil if the scope is not available, or contains only
|
||||
/// `NULL` values.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Book.including(optional: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let country = belongsTo(Country.self)
|
||||
/// }
|
||||
///
|
||||
/// let author: Author? = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
/// // Fetch a book, with its eventual author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(optional: Book.author
|
||||
/// .including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author? = try row.decode(forKey: "author")
|
||||
/// let country: Country? = try row.decode(forKey: "country")
|
||||
/// ```
|
||||
///
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
///
|
||||
/// let country: Country? = row["country"]
|
||||
/// print(country.name)
|
||||
/// // Prints "United States"
|
||||
///
|
||||
/// Nil is returned if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decodeIfPresent<Record: FetchableRecord>(
|
||||
/// - parameter type: The decoded type.
|
||||
/// - parameter scope: A scope identifier.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decodeIfPresent<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record?
|
||||
@@ -1228,37 +1435,48 @@ extension Row {
|
||||
return try Record(row: scopedRow)
|
||||
}
|
||||
|
||||
/// Returns the record associated with the given scope.
|
||||
/// Returns the record associated to the given key.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Book.including(required: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let country = belongsTo(Country.self)
|
||||
/// }
|
||||
///
|
||||
/// let author: Author = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
/// // Fetch a book, with its author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(required: Book.author
|
||||
/// .including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let request = Book.including(required: Book.author.including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author = try row.decode(forKey: "author")
|
||||
/// let country: Country = try row.decode(forKey: "country")
|
||||
/// ```
|
||||
///
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
///
|
||||
/// let country: Country = row["country"]
|
||||
/// print(country.name)
|
||||
/// // Prints "United States"
|
||||
///
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decode<Record: FetchableRecord>(
|
||||
/// - parameter type: The decoded type.
|
||||
/// - parameter scope: A scope identifier.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record
|
||||
@@ -1300,20 +1518,34 @@ extension Row {
|
||||
// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the records encoded in the given prefetched rows.
|
||||
/// Returns a collection of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// }
|
||||
///
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
/// struct Book: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// let books: [Book] = row["books"]
|
||||
/// print(books[0].title)
|
||||
/// // Prints "Moby-Dick"
|
||||
func decode<Collection>(
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: [Book] = try row.decode(forKey: "books")
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
///
|
||||
/// - parameter type: The type of the decoded collection.
|
||||
/// - parameter key: An association key.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Collection>(
|
||||
_ type: Collection.Type = Collection.self,
|
||||
forKey key: String)
|
||||
throws -> Collection
|
||||
@@ -1321,6 +1553,7 @@ extension Row {
|
||||
Collection: RangeReplaceableCollection,
|
||||
Collection.Element: FetchableRecord
|
||||
{
|
||||
// TODO: test independently
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
let availableKeys = prefetchedRows.keys
|
||||
if availableKeys.isEmpty {
|
||||
@@ -1351,24 +1584,39 @@ extension Row {
|
||||
return collection
|
||||
}
|
||||
|
||||
/// Returns the set of records encoded in the given prefetched rows.
|
||||
/// Returns the set of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// }
|
||||
///
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
/// struct Book: TableRecord, FetchableRecord, Hashable { }
|
||||
///
|
||||
/// let books: Set<Book> = row["books"]
|
||||
/// print(books.first!.title)
|
||||
/// // Prints "Moby-Dick"
|
||||
func decode<Record: FetchableRecord & Hashable>(
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: Set<Book> = try row.decode(forKey: "books")
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
///
|
||||
/// - parameter type: The type of the decoded set.
|
||||
/// - parameter key: An association key.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Record: FetchableRecord & Hashable>(
|
||||
_ type: Set<Record>.Type = Set<Record>.self,
|
||||
forKey key: String)
|
||||
throws -> Set<Record>
|
||||
{
|
||||
// TODO: test independently
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
let availableKeys = prefetchedRows.keys
|
||||
if availableKeys.isEmpty {
|
||||
@@ -1735,11 +1983,17 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -1784,11 +2038,17 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -1816,11 +2076,17 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -1852,11 +2118,17 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A key that is used to decode a value in a row
|
||||
@@ -23,9 +26,21 @@ enum RowKey: Hashable, Sendable {
|
||||
case prefetchKey(String)
|
||||
}
|
||||
|
||||
/// A decoding error
|
||||
@usableFromInline
|
||||
enum RowDecodingError: Error {
|
||||
/// A decoding error thrown when decoding a database row.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// // RowDecodingError: could not decode String from database value NULL.
|
||||
/// let name = try row.decode(String.self, forColumn: "name")
|
||||
/// ```
|
||||
public struct RowDecodingError: Error {
|
||||
enum Impl {
|
||||
case keyNotFound(RowKey, Context)
|
||||
case valueMismatch(Any.Type, Context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct Context: CustomDebugStringConvertible, Sendable {
|
||||
/// A description of what went wrong, for debugging purposes.
|
||||
@@ -55,17 +70,19 @@ enum RowDecodingError: Error {
|
||||
}
|
||||
}
|
||||
|
||||
case keyNotFound(RowKey, Context)
|
||||
case valueMismatch(Any.Type, Context)
|
||||
|
||||
var impl: Impl
|
||||
var context: Context {
|
||||
switch self {
|
||||
switch impl {
|
||||
case .keyNotFound(_, let context),
|
||||
.valueMismatch(_, let context):
|
||||
return context
|
||||
}
|
||||
}
|
||||
|
||||
static func valueMismatch(_ type: Any.Type, _ context: Context) -> Self {
|
||||
self.init(impl: .valueMismatch(type, context))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
/// `could not decode <Type> from database value <value>` error message.
|
||||
static func valueMismatch(
|
||||
@@ -74,11 +91,10 @@ enum RowDecodingError: Error {
|
||||
databaseValue: DatabaseValue)
|
||||
-> Self
|
||||
{
|
||||
valueMismatch(
|
||||
type,
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
"""))
|
||||
let context = RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
""")
|
||||
return self.init(impl: .valueMismatch(type, context))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
@@ -115,11 +131,15 @@ enum RowDecodingError: Error {
|
||||
/// error message.
|
||||
@usableFromInline
|
||||
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
|
||||
keyNotFound(
|
||||
self.init(impl: .keyNotFound(
|
||||
.columnName(columnName),
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
column not found: \(String(reflecting: columnName))
|
||||
"""))
|
||||
""")))
|
||||
}
|
||||
|
||||
static func keyNotFound(_ rowKey: RowKey, _ context: Context) -> Self {
|
||||
self.init(impl: .keyNotFound(rowKey, context))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,8 +187,7 @@ struct RowDecodingContext {
|
||||
}
|
||||
|
||||
extension RowDecodingError: CustomStringConvertible {
|
||||
@usableFromInline
|
||||
var description: String {
|
||||
public var description: String {
|
||||
let context = self.context
|
||||
let row = context.row
|
||||
var chunks: [String] = []
|
||||
|
||||
+2
-2
@@ -118,7 +118,7 @@ public struct SQL: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
fileprivate func qualified(with alias: TableAliasBase) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
// A raw SQL string can't be qualified with a table alias,
|
||||
@@ -192,7 +192,7 @@ public struct SQL: Sendable {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> SQL {
|
||||
func qualified(with alias: TableAliasBase) -> SQL {
|
||||
SQL(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ final class SerializedDatabase {
|
||||
/// The database connection
|
||||
private let db: Database
|
||||
|
||||
/// The actor that performs asynchronous accesses
|
||||
private let actor: DispatchQueueActor
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration { db.configuration }
|
||||
|
||||
@@ -55,6 +58,8 @@ final class SerializedDatabase {
|
||||
} else {
|
||||
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
|
||||
}
|
||||
self.actor = DispatchQueueActor(queue: queue)
|
||||
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
do {
|
||||
@@ -245,20 +250,22 @@ final class SerializedDatabase {
|
||||
|
||||
/// Asynchrously executes the block.
|
||||
func execute<T: Sendable>(
|
||||
_ block: @escaping @Sendable (Database) throws -> T
|
||||
_ block: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
self.async { db in
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try block(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await actor.execute {
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
preconditionNoUnsafeTransactionLeft(db)
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try block(db)
|
||||
}
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,108 +312,3 @@ final class SerializedDatabase {
|
||||
// It happens the job of SerializedDatabase is precisely to provide thread-safe
|
||||
// access to `Database`.
|
||||
extension SerializedDatabase: @unchecked Sendable { }
|
||||
|
||||
// MARK: - Task Cancellation Support
|
||||
|
||||
enum DatabaseAccessCancellationState: @unchecked Sendable {
|
||||
// @unchecked Sendable because database is only accessed from its
|
||||
// dispatch queue.
|
||||
case notConnected
|
||||
case connected(Database)
|
||||
case cancelled
|
||||
case expired
|
||||
}
|
||||
|
||||
typealias CancellableDatabaseAccess = Mutex<DatabaseAccessCancellationState>
|
||||
|
||||
/// Supports Task cancellation in async database accesses.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbAccess = CancellableDatabaseAccess()
|
||||
/// return try dbAccess.withCancellableContinuation { continuation in
|
||||
/// asyncDatabaseAccess { db in
|
||||
/// do {
|
||||
/// let result = try dbAccess.inDatabase(db) {
|
||||
/// // Perform database operations
|
||||
/// }
|
||||
/// continuation.resume(returning: result)
|
||||
/// } catch {
|
||||
/// continuation.resume(throwing: error)
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
extension CancellableDatabaseAccess: DatabaseCancellable {
|
||||
convenience init() {
|
||||
self.init(.notConnected)
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
withLock { state in
|
||||
switch state {
|
||||
case let .connected(db):
|
||||
db.cancel()
|
||||
state = .cancelled
|
||||
case .notConnected:
|
||||
state = .cancelled
|
||||
case .cancelled, .expired:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func withCancellableContinuation<Value>(
|
||||
_ fn: (UnsafeContinuation<Value, any Error>) -> Void
|
||||
) async throws -> Value {
|
||||
try await withTaskCancellationHandler {
|
||||
try checkCancellation()
|
||||
return try await withUnsafeThrowingContinuation { continuation in
|
||||
fn(continuation)
|
||||
}
|
||||
} onCancel: {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func checkCancellation() throws {
|
||||
try withLock { state in
|
||||
if case .cancelled = state {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a full database access with cancellation support. When this
|
||||
/// method returns, the database is NOT cancelled.
|
||||
func inDatabase<Value>(_ db: Database, execute work: () throws -> Value) throws -> Value {
|
||||
try withLock { state in
|
||||
switch state {
|
||||
case .connected, .expired:
|
||||
fatalError("Can't use a CancellableDatabaseAccess twice")
|
||||
case .notConnected:
|
||||
state = .connected(db)
|
||||
case .cancelled:
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
|
||||
return try throwingFirstError {
|
||||
try work()
|
||||
} finally: {
|
||||
let cancelled = withLock { state in
|
||||
if case .cancelled = state {
|
||||
db.uncancel()
|
||||
return true
|
||||
} else {
|
||||
state = .expired
|
||||
return false
|
||||
}
|
||||
}
|
||||
if cancelled {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -141,7 +144,7 @@ public final class Statement {
|
||||
let authorizer = database.authorizer
|
||||
authorizer.reset()
|
||||
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
var sqliteStatement: SQLiteStatement?
|
||||
let code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
#if canImport(string_h)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A type that can decode itself from the low-level C interface to
|
||||
@@ -563,13 +566,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -608,13 +618,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -647,13 +664,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -681,13 +705,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -720,13 +751,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -760,13 +798,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -796,13 +841,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -827,13 +879,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#if canImport(CoreGraphics)
|
||||
import CoreGraphics
|
||||
#elseif !canImport(Darwin)
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
@@ -15,4 +18,3 @@ extension CGFloat: DatabaseValueConvertible {
|
||||
return CGFloat(double)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
@@ -38,7 +40,6 @@ extension NSDate: DatabaseValueConvertible {
|
||||
return cast(date)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
#if !os(Linux)
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -65,4 +67,3 @@ extension Decimal: StatementColumnConvertible {
|
||||
|
||||
@usableFromInline
|
||||
let _posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
@@ -24,4 +23,3 @@ extension NSData: DatabaseValueConvertible {
|
||||
return cast(data)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,4 +1,4 @@
|
||||
#if !os(Linux) && !os(Windows)
|
||||
#if !os(Windows)
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
@@ -81,10 +81,18 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: int64)
|
||||
return number as? Self
|
||||
case .int64(let int64):
|
||||
return self.init(value: int64)
|
||||
let number = NSNumber(value: int64)
|
||||
return number as? Self
|
||||
case .double(let double) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: double)
|
||||
return number as? Self
|
||||
case .double(let double):
|
||||
return self.init(value: double)
|
||||
let number = NSNumber(value: double)
|
||||
return number as? Self
|
||||
case let .string(string):
|
||||
// Must match Decimal.fromDatabaseValue(_:)
|
||||
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
@@ -24,4 +23,3 @@ extension NSString: DatabaseValueConvertible {
|
||||
return self.init(string: string)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,12 +1,16 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows)
|
||||
#if !os(Windows)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value containing the absolute URL.
|
||||
public var databaseValue: DatabaseValue {
|
||||
absoluteString?.databaseValue ?? .null
|
||||
#if !canImport(Darwin)
|
||||
absoluteString.databaseValue
|
||||
#else
|
||||
absoluteString?.databaseValue ?? .null
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows)
|
||||
#if !os(Windows)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
@@ -33,10 +36,17 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data) where data.count == 16:
|
||||
return data.withUnsafeBytes {
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
#if canImport(Darwin)
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
#else
|
||||
guard let uuidBytes = $0.bindMemory(to: UInt8.self).baseAddress else {
|
||||
return nil as Self?
|
||||
}
|
||||
return NSUUID(uuidBytes: uuidBytes) as? Self
|
||||
#endif
|
||||
}
|
||||
case .string(let string):
|
||||
return self.init(uuidString: string)
|
||||
return NSUUID(uuidString: string) as? Self
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
@@ -88,8 +98,8 @@ extension UUID: StatementColumnConvertible {
|
||||
self.init(uuid: uuid.uuid)
|
||||
case SQLITE_BLOB:
|
||||
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index) else
|
||||
{
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
extension Optional: StatementBinding where Wrapped: StatementBinding {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
// MARK: - Value Types
|
||||
@@ -650,8 +653,7 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/capitalized``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let request = Player.select { $0.name.capitalized }
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let capitalize =
|
||||
@@ -672,8 +674,7 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/lowercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.lowercased)
|
||||
/// let request = Player.select { $0.name.lowercased }
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let lowercase =
|
||||
@@ -694,8 +695,7 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/uppercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.uppercased)
|
||||
/// let request = Player.select { $0.name.uppercased }
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let uppercase =
|
||||
@@ -716,8 +716,7 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/localizedCapitalized``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let request = Player.select { $0.name.localizedCapitalized }
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedCapitalize =
|
||||
@@ -739,8 +738,7 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/localizedLowercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedLowercase)
|
||||
/// let request = Player.select { $0.name.localizedLowercase }
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedLowercase =
|
||||
@@ -761,8 +759,7 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/localizedUppercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedUppercase)
|
||||
/// let request = Player.select { $0.name.localizedUppercase }
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedUppercase =
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
@@ -613,7 +616,6 @@ class DatabaseObservationBroker {
|
||||
|
||||
// Called from statementDidExecute or statementDidFail
|
||||
private func databaseDidRollback(notifyTransactionObservers: Bool) {
|
||||
#warning("TODO")
|
||||
savepointStack.clear()
|
||||
|
||||
if notifyTransactionObservers {
|
||||
@@ -1253,16 +1255,16 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
|
||||
|
||||
public struct DatabasePreUpdateEvent {
|
||||
|
||||
/// An event kind
|
||||
public enum Kind: CInt {
|
||||
/// SQLITE_INSERT
|
||||
case insert = 18
|
||||
/// An event kind.
|
||||
public enum Kind: CInt, Sendable {
|
||||
/// An insertion event
|
||||
case insert = 18 // SQLITE_INSERT
|
||||
|
||||
/// SQLITE_DELETE
|
||||
case delete = 9
|
||||
/// A deletion event
|
||||
case delete = 9 // SQLITE_DELETE
|
||||
|
||||
/// SQLITE_UPDATE
|
||||
case update = 23
|
||||
/// An update event
|
||||
case update = 23 // SQLITE_UPDATE
|
||||
}
|
||||
|
||||
/// The event kind
|
||||
@@ -1495,7 +1497,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
|
||||
-> DatabaseValue?
|
||||
{
|
||||
var value: SQLiteValue? = nil
|
||||
var value: SQLiteValue?
|
||||
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
|
||||
if let value {
|
||||
return DatabaseValue(sqliteValue: value)
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// An instance of WALSnapshot records the state of a WAL mode database for some
|
||||
@@ -16,18 +19,6 @@ import SQLite3
|
||||
/// actual observation. This class has no other purpose, and is not intended to
|
||||
/// become public.
|
||||
///
|
||||
/// It does not work with SQLCipher, because SQLCipher does not support
|
||||
/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors.
|
||||
/// See <https://github.com/ericsink/SQLitePCL.raw/issues/452>.
|
||||
///
|
||||
/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT`
|
||||
/// is defined.
|
||||
///
|
||||
/// With system SQLite, it works because the SDK exposes the C apis and
|
||||
/// since XCode 14.
|
||||
///
|
||||
/// Yes, this is an awfully complex logic.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot: @unchecked Sendable {
|
||||
// @unchecked because sqlite3_snapshot has no threading requirements.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// A long-live read-only WAL transaction.
|
||||
///
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
@@ -15,7 +15,13 @@ final class WALSnapshotTransaction: @unchecked Sendable {
|
||||
// WALSnapshotTransaction may be deinitialized in the dispatch
|
||||
// queue of its reader: allow reentrancy.
|
||||
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
|
||||
try? db.commit()
|
||||
// Commit or rollback, but try hard to leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
return db.isInsideTransaction
|
||||
}
|
||||
release(isInsideTransaction)
|
||||
|
||||
@@ -97,7 +97,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
See ``DatabaseReader/read(_:)-4d1da`` and ``DatabaseWriter/write(_:)-3db50``.
|
||||
See ``DatabaseReader/read(_:)-5mfwu`` and ``DatabaseWriter/write(_:)-4gnqx``.
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
|
||||
@@ -29,6 +29,8 @@ Get information about schema objects such as tables, columns, indexes, foreign k
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseSchemaID``
|
||||
- ``DatabaseObjectID``
|
||||
- ``ColumnInfo``
|
||||
- ``ForeignKeyInfo``
|
||||
- ``IndexInfo``
|
||||
|
||||
@@ -262,11 +262,11 @@ try dbQueue.write { db in
|
||||
|
||||
// Use instead:
|
||||
let player = try Player
|
||||
.filter(Column("teamId") == 42 && Column("position") == 1)
|
||||
.filter { $0.teamId == 42 && $0.position == 1 }
|
||||
.fetchOne(db)
|
||||
|
||||
try Player
|
||||
.filter(Column("name") == "Arthur")
|
||||
.filter { $0.name == "Arthur" }
|
||||
.deleteAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -96,6 +96,7 @@ do {
|
||||
- ``persistentReadOnlyConnections``
|
||||
- ``prepareDatabase(_:)``
|
||||
- ``publicStatementArguments``
|
||||
- ``schemaSource``
|
||||
- ``transactionClock``
|
||||
- ``TransactionClock``
|
||||
|
||||
@@ -106,3 +107,7 @@ do {
|
||||
- ``writeQoS``
|
||||
- ``targetQueue``
|
||||
- ``writeTargetQueue``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseSchemaSource``
|
||||
@@ -59,7 +59,7 @@ You can feed `DatabaseRegionObservation` with any type that conforms to the ``Da
|
||||
```swift
|
||||
// Observe the score column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: Player.select(Column("score")))
|
||||
tracking: Player.select(\.score))
|
||||
|
||||
// Observe the 'score' column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
|
||||
@@ -214,7 +214,7 @@ Consider a scenario where you'd like to get a specific Player's row, but only wh
|
||||
let observation = ValueObservation.tracking(
|
||||
// Define the tracked database region
|
||||
// (the score column of the player with id 1)
|
||||
region: Player.select(Column("score")).filter(id: 1),
|
||||
region: Player.select(\.score).filter(id: 1),
|
||||
// Define what to fetch upon such change to the tracked region
|
||||
// (the player with id 1)
|
||||
fetch: { db in try Player.fetchOne(db, id: 1) }
|
||||
@@ -263,6 +263,10 @@ You can filter out undesired duplicate notifications with the ``removeDuplicates
|
||||
|
||||
When needed, you can help GRDB optimize observations and reduce database contention:
|
||||
|
||||
> Important: **Keep your number of observations bounded.**
|
||||
>
|
||||
> In particular, do not observe independently all elements in a list. Instead, observe the whole list in a single observation.
|
||||
|
||||
> Tip: Stop observations when possible.
|
||||
>
|
||||
> For example, if a `UIViewController` needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`.
|
||||
|
||||
@@ -94,6 +94,7 @@ let players: [Player] = try dbQueue.read { db in
|
||||
- <doc:RecordRecommendedPractices>
|
||||
- <doc:RecordTimestamps>
|
||||
- <doc:SingleRowTables>
|
||||
- <doc:ViewRecords>
|
||||
|
||||
### Application Tools
|
||||
|
||||
|
||||
@@ -36,10 +36,16 @@ try db.create(table: "player") { t in
|
||||
> JSONColumn("address")["country"],
|
||||
> ])
|
||||
>
|
||||
> struct Player: FetchableRecord, TableRecord {
|
||||
> enum Columns {
|
||||
> static let address = JSONColumn("address")
|
||||
> }
|
||||
> }
|
||||
>
|
||||
> // SELECT * FROM player
|
||||
> // WHERE address ->> 'country' = 'DE'
|
||||
> let germanPlayers = try Player
|
||||
> .filter(JSONColumn("address")["country"] == "DE")
|
||||
> .filter { $0.address["country"] == "DE" }
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
|
||||
@@ -104,10 +110,16 @@ extension Team: FetchableRecord, PersistableRecord {
|
||||
> struct Address: Codable { ... }
|
||||
> extension Address: DatabaseValueConvertible {}
|
||||
>
|
||||
> struct Player: FetchableRecord, TableRecord {
|
||||
> enum Columns {
|
||||
> static let address = JSONColumn("address")
|
||||
> }
|
||||
> }
|
||||
>
|
||||
> // SELECT * FROM player
|
||||
> // WHERE address = '{"street": "...", "city": "...", "country": "..."}'
|
||||
> let players = try Player
|
||||
> .filter(JSONColumn("address") == Address(...))
|
||||
> .filter { $0.address == Address(...) }
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
>
|
||||
|
||||
@@ -214,7 +214,7 @@ extension Book.Kind: DatabaseValueConvertible { }
|
||||
|
||||
// Fetch all novels
|
||||
let novels = try dbQueue.read { db in
|
||||
try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db)
|
||||
try Book.filter { $0.kind == Book.Kind.novel }.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -297,7 +297,7 @@ Once we have record types that are able to read and write in the database, we'd
|
||||
|
||||
### Columns
|
||||
|
||||
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
|
||||
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration, with the name `Columns`, nested inside the record type. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
|
||||
|
||||
```swift
|
||||
// HOW TO define columns for a Codable record
|
||||
@@ -310,13 +310,15 @@ extension Author {
|
||||
}
|
||||
```
|
||||
|
||||
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
|
||||
For non-Codable record types, declare columns with their names:
|
||||
|
||||
```swift
|
||||
// HOW TO define columns for a non-Codable record
|
||||
extension Author {
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, countryCode
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let countryCode = Column("countryCode")
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -328,12 +330,12 @@ try dbQueue.read { db in
|
||||
// Fetch all authors, ordered by name,
|
||||
// in a localized case-insensitive fashion
|
||||
let sortedAuthors: [Author] = try Author.all()
|
||||
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
.fetchAll(db)
|
||||
|
||||
// Count French authors
|
||||
let frenchAuthorCount: Int = try Author.all()
|
||||
.filter(Author.Columns.countryCode == "FR")
|
||||
.filter { $0.countryCode == "FR" }
|
||||
.fetchCount(db)
|
||||
}
|
||||
```
|
||||
@@ -349,13 +351,12 @@ Define those methods in extensions of the ``DerivableRequest`` protocol, as belo
|
||||
extension DerivableRequest<Author> {
|
||||
/// Order authors by name, in a localized case-insensitive fashion
|
||||
func orderByName() -> Self {
|
||||
let name = Author.Columns.name
|
||||
return order(name.collating(.localizedCaseInsensitiveCompare))
|
||||
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
}
|
||||
|
||||
/// Filters authors from a country
|
||||
func filter(countryCode: String) -> Self {
|
||||
filter(Author.Columns.countryCode == countryCode)
|
||||
filter { $0.countryCode == countryCode }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,13 +364,12 @@ extension DerivableRequest<Author> {
|
||||
extension DerivableRequest<Book> {
|
||||
/// Order books by title, in a localized case-insensitive fashion
|
||||
func orderByTitle() -> Self {
|
||||
let title = Book.Columns.title
|
||||
return order(title.collating(.localizedCaseInsensitiveCompare))
|
||||
order { $0.title.collating(.localizedCaseInsensitiveCompare) }
|
||||
}
|
||||
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter(Book.Columns.kind == kind)
|
||||
filter { $0.kind == kind }
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -395,7 +395,7 @@ Extensions to the `DerivableRequest` protocol can not change the type of request
|
||||
extension QueryInterfaceRequest<Author> {
|
||||
// Selects authors' name
|
||||
func selectName() -> QueryInterfaceRequest<String> {
|
||||
select(Author.Columns.name)
|
||||
select(\.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -91,8 +91,14 @@ extension Player: FetchableRecord, PersistableRecord {
|
||||
// because non-'Sendable' type '[any SQLSelectable]'
|
||||
// may have shared mutable state
|
||||
static let databaseSelection: [any SQLSelectable] = [
|
||||
Column("id"), Column("name"), Column("score")
|
||||
Columns.id, Columns.name, Columns.score
|
||||
]
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let score = Column("score")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -101,7 +107,7 @@ extension Player: FetchableRecord, PersistableRecord {
|
||||
```swift
|
||||
extension Player: FetchableRecord, PersistableRecord {
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[Column("id"), Column("name"), Column("score")]
|
||||
[Columns.id, Columns.name, Columns.score]
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -223,5 +229,11 @@ Task {
|
||||
}
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``GRDBSendableMetatype``
|
||||
|
||||
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
|
||||
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/
|
||||
@@ -0,0 +1,383 @@
|
||||
# View Records
|
||||
|
||||
Define record types that target database views.
|
||||
|
||||
## Overview
|
||||
|
||||
A record type targets a [database view] as soon as its ``TableRecord/databaseTableName-3tcw2`` is the name of a view.
|
||||
|
||||
With such a record, some GRDB features will work out of the box, and some will throw errors without extra configuration:
|
||||
|
||||
```swift
|
||||
// OK: Works out of the box
|
||||
let captains = try Captain.fetchAll(db)
|
||||
let captainCount = try Captain.fetchCount(db)
|
||||
|
||||
// KO: Requires extra configuration
|
||||
// SQLite error 1: database view captain has no primary key
|
||||
var bob = try Captain.find(db, id: "bob")
|
||||
bob.name = "Bobby"
|
||||
// SQLite error 1: cannot modify captain because it is a view
|
||||
try bob.update(db)
|
||||
```
|
||||
|
||||
This article explains how to solve those errors:
|
||||
|
||||
- How to provide a primary key to a view.
|
||||
- How to define INSTEAD OF triggers that insert, update, and delete through a database view.
|
||||
|
||||
> 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.
|
||||
|
||||
## Preliminary Setup
|
||||
|
||||
To support this documentation, we need a database that contains a view. The sample code below uses <doc:Migrations> and <doc:DatabaseSchemaModifications> methods.
|
||||
|
||||
The database schema contains teams and players. Some players are the captain of their team. We enforce in the database schema that a given team can't have multiple captains:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("Teams and players") { db in
|
||||
try db.create(table: "team") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
t.belongsTo("team", onDelete: .setNull)
|
||||
t.column("isCaptain", .boolean).notNull()
|
||||
}
|
||||
|
||||
// One unique captain per team
|
||||
try db.create(
|
||||
indexOn: "player", columns: ["teamId"],
|
||||
options: .unique,
|
||||
condition: Column("isCaptain"))
|
||||
}
|
||||
```
|
||||
|
||||
We define record types for the `team` and `player` tables, as described in <doc:RecordRecommendedPractices>:
|
||||
|
||||
```swift
|
||||
struct Team: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
}
|
||||
|
||||
struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
var teamId: String?
|
||||
var isCaptain: Bool
|
||||
}
|
||||
```
|
||||
|
||||
Let's define a view and a record type for captains. At this point, both the view and the record are read-only:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Read-only captains") { db in
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW captain AS
|
||||
SELECT id, name, teamId
|
||||
FROM player
|
||||
WHERE isCaptain AND teamId IS NOT NULL;
|
||||
""")
|
||||
}
|
||||
|
||||
struct Captain: Decodable, Identifiable, FetchableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
var teamId: String
|
||||
}
|
||||
```
|
||||
|
||||
✅ From now on, we can use the `Captain` record:
|
||||
|
||||
```swift
|
||||
let dbQueue = try DatabaseQueue()
|
||||
try migrator.migrate(dbQueue)
|
||||
try dbQueue.write { db in
|
||||
try Team(id: "red", name: "Red").insert(db)
|
||||
try Team(id: "blue", name: "Blue").insert(db)
|
||||
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
|
||||
try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db)
|
||||
try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db)
|
||||
|
||||
let captains = try Captain.fetchAll(db)
|
||||
// Prints:
|
||||
// Captain(id: "alice", name: "Alice", teamId: "red")
|
||||
// Captain(id: "bob", name: "Bob", teamId: "blue")
|
||||
print(captains)
|
||||
}
|
||||
```
|
||||
|
||||
## Specifying the primary key of a view
|
||||
|
||||
SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the eventual primary key.
|
||||
|
||||
To instruct GRDB about the primary key, define a **schema source**, a type that conforms to ``DatabaseSchemaSource``. In this sample code, the schema only contains the "captain" view, so our schema source does not need to be very complicated. Check the documentation of the protocol for more detailed instructions:
|
||||
|
||||
```swift
|
||||
struct GameSchemaSource: DatabaseSchemaSource {
|
||||
/// Returns the names of the columns for the primary key in the
|
||||
/// provided database view.
|
||||
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
|
||||
["id"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
We configure the database connection with this schema source:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.schemaSource = GameSchemaSource()
|
||||
let dbQueue = try DatabaseQueue(configuration: config)
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
✅ We can now use the primary key of captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// [Insert some teams and players...]
|
||||
let captains = try Captain.orderByPrimaryKey().fetchAll(db)
|
||||
let alice = try Captain.find(db, id: "alice")
|
||||
}
|
||||
```
|
||||
|
||||
## Associations between views
|
||||
|
||||
To define [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) between record types that target database views, the foreign key must be explicitly provided. We define the foreign key from `captain` to `team` with a column declared as recommended in <doc:RecordRecommendedPractices>:
|
||||
|
||||
```swift
|
||||
extension Captain {
|
||||
// Time to define some columns
|
||||
enum Columns {
|
||||
static let teamId = Column(CodingKeys.teamId)
|
||||
}
|
||||
|
||||
// The captain view has a foreign key to teams,
|
||||
// from the teamId column to the team primary key.
|
||||
// SQLite does not know about it, so we declare it explicitly:
|
||||
static let teamForeignKey = ForeignKey([Columns.teamId])
|
||||
|
||||
// A captain belongs to a team.
|
||||
static let team = belongsTo(Team.self, using: teamForeignKey)
|
||||
}
|
||||
|
||||
extension Team {
|
||||
// A team has a captain.
|
||||
static let captain = hasOne(Captain.self, using: Captain.teamForeignKey)
|
||||
}
|
||||
```
|
||||
|
||||
✅ We can now use those associations:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// All teams with a captain
|
||||
let teamsWithCaptain: [Team] = try Team
|
||||
.joining(required: Team.captain)
|
||||
.fetchAll(db)
|
||||
|
||||
// All (captain, team) pairs
|
||||
struct CaptainWithTeam: Decodable, FetchableRecord {
|
||||
var captain: Captain
|
||||
var team: Team
|
||||
}
|
||||
let captainsWithTeam: [CaptainWithTeam] = try Captain
|
||||
.including(required: Captain.team)
|
||||
.asRequest(of: CaptainWithTeam.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
## Inserting rows into a view
|
||||
|
||||
SQLite views are read-only unless we define an [INSTEAD OF trigger] that specifies which statements to run when we insert a row into a view.
|
||||
|
||||
INSTEAD OF triggers are very versatile, and applications can define the behavior that best fits their needs. In our sample code, inserting a captain will insert a player with the `isCaptain` flag set, and we'll also remove the `isCaptain` flag of the previous captain, if any:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Captain insert") { db in
|
||||
try db.execute(sql: """
|
||||
-- Insert trigger
|
||||
CREATE TRIGGER captain_insert
|
||||
INSTEAD OF INSERT ON captain
|
||||
BEGIN
|
||||
-- Remove previous captain
|
||||
UPDATE player SET isCaptain = 0
|
||||
WHERE teamId = NEW.teamId AND isCaptain;
|
||||
|
||||
-- Insert new captain
|
||||
INSERT INTO player(id, name, teamId, isCaptain)
|
||||
VALUES (NEW.id, NEW.name, NEW.teamId, 1);
|
||||
END;
|
||||
""")
|
||||
}
|
||||
|
||||
// Apply the new migration
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
Let's also give an `insert()` method to the Captain record, with the ``PersistableRecord`` protocol:
|
||||
|
||||
```swift
|
||||
extension Captain: Encodable, PersistableRecord { }
|
||||
```
|
||||
|
||||
- note: Remember that auto-incremented primary keys are not supported, as described at the beginning of this article. Our captain view is backed by the player table which has a string primary key, so we're fine.
|
||||
|
||||
✅ We can directly insert captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.write {
|
||||
try Team(id: "green", name: "Green").insert(db)
|
||||
// Diane is the captain
|
||||
try Captain(id: "diane", name: "Diane", teamId: "green").insert(db)
|
||||
// Well, no: Eugene is the captain
|
||||
try Captain(id: "eugene", name: "Eugene", teamId: "green").insert(db)
|
||||
|
||||
// Prints:
|
||||
// team player captain
|
||||
// green|Green diane|Diane|green|0 eugene|Eugene|green
|
||||
// eugene|Eugene|green|1
|
||||
try db.dumpTables(["team", "player", "captain"])
|
||||
}
|
||||
```
|
||||
|
||||
## Updating rows in a view
|
||||
|
||||
Just like for inserts, an INSTEAD OF trigger can specify how to update rows in a view.
|
||||
|
||||
In our sample code, updating a captain will update the player with the same id, and remove the `isCaptain` flag from the previous captain of the team, if any:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Captain update") { db in
|
||||
try db.execute(sql: """
|
||||
-- Update trigger
|
||||
CREATE TRIGGER captain_update
|
||||
INSTEAD OF UPDATE ON captain
|
||||
BEGIN
|
||||
-- Remove previous captain
|
||||
UPDATE player SET isCaptain = 0
|
||||
WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id;
|
||||
|
||||
-- Update captain
|
||||
UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
""")
|
||||
}
|
||||
|
||||
// Apply the new migration
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
✅ Let's update captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.write {
|
||||
try Team(id: "red", name: "Red").insert(db)
|
||||
try Team(id: "blue", name: "Blue").insert(db)
|
||||
try Captain(id: "alice", name: "Alice", teamId: "red").insert(db)
|
||||
|
||||
// Bob is the Blue captain.
|
||||
var bob = Captain(id: "bob", name: "Bob", teamId: "blue")
|
||||
try bob.insert(db)
|
||||
|
||||
// Bob is now Bobby, the Red captain.
|
||||
// Alice is no longer the Red captain.
|
||||
try bob.updateChanges(db) {
|
||||
$0.name = "Bobby"
|
||||
$0.teamId = "red"
|
||||
}
|
||||
|
||||
// Prints:
|
||||
// team player captain
|
||||
// blue|Blue alice|Alice|red|0 bob|Bobby|red
|
||||
// red|Red bob|Bobby|red|1
|
||||
try db.dumpTables(["team", "player", "captain"])
|
||||
}
|
||||
```
|
||||
|
||||
## Deleting rows from a view
|
||||
|
||||
The last missing INSTEAD OF trigger deals with deletes:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Captain delete") { db in
|
||||
try db.execute(sql: """
|
||||
-- Delete trigger
|
||||
CREATE TRIGGER captain_delete
|
||||
INSTEAD OF DELETE ON captain
|
||||
BEGIN
|
||||
DELETE FROM player WHERE id = OLD.id;
|
||||
END;
|
||||
""")
|
||||
}
|
||||
|
||||
// Apply the new migration
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
✅ Let's delete some captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.write {
|
||||
// Delete Alice
|
||||
try Captain.deleteOne(db, id: "alice")
|
||||
|
||||
// Delete Bob
|
||||
let bob = try Captain.find(db, id: "bob")
|
||||
try bob.delete(db)
|
||||
|
||||
// Delete all captains
|
||||
try Captain.deleteAll()
|
||||
}
|
||||
```
|
||||
|
||||
## Going further
|
||||
|
||||
To exercise the techniques described here, try to define record types for these other views:
|
||||
|
||||
- The `enrolledPlayer` view that only contains players that belong to a team:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW enrolledPlayer AS
|
||||
SELECT id, name, teamId, isCaptain
|
||||
FROM player
|
||||
WHERE teamId IS NOT NULL;
|
||||
""")
|
||||
```
|
||||
|
||||
- The `teamWithCaptainId` view that contains a `captainId` column:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW teamWithCaptainId AS
|
||||
SELECT team.id, team.name, player.id AS captainId
|
||||
FROM team
|
||||
JOIN player ON player.teamId = team.id AND player.isCaptain;
|
||||
""")
|
||||
```
|
||||
|
||||
- A refactored `captain` view whose primary key is the team id—this is valid, since the schema enforces that there's a single captain for each team:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW captain AS
|
||||
SELECT teamId, name
|
||||
FROM player
|
||||
WHERE isCaptain AND teamId IS NOT NULL;
|
||||
""")
|
||||
```
|
||||
|
||||
[database view]: https://www.sqlite.org/lang_createview.html
|
||||
[INSTEAD OF trigger]: https://sqlite.org/lang_createtrigger.html#instead_of_triggers
|
||||
@@ -324,7 +324,7 @@ extension Database {
|
||||
}
|
||||
|
||||
private func isShadowTable(_ tableName: String) throws -> Bool {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
// Maybe SQLCipher is too old: check actual version
|
||||
if Database.sqliteLibVersionNumber >= 3037000 {
|
||||
guard let table = try table(tableName) else {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A format that prints one line per database row, formatting values
|
||||
|
||||
+2
-2
@@ -40,11 +40,11 @@ public struct FTS3 {
|
||||
/// the `remove_diacritics=1` tokenizer argument.
|
||||
case removeLegacy
|
||||
|
||||
#if GRDBCUSTOMSQLITE
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Remove diacritics from Latin script characters. This option matches
|
||||
/// the `remove_diacritics=2` tokenizer argument.
|
||||
case remove
|
||||
#elseif !GRDBCIPHER
|
||||
#else
|
||||
/// Remove diacritics from Latin script characters. This option matches
|
||||
/// the `remove_diacritics=2` tokenizer argument.
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+
|
||||
|
||||
@@ -95,10 +95,10 @@ public struct FTS3TokenizerDescriptor: Sendable {
|
||||
break
|
||||
case .keep:
|
||||
arguments.append("remove_diacritics=0")
|
||||
#if GRDBCUSTOMSQLITE
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
case .remove:
|
||||
arguments.append("remove_diacritics=2")
|
||||
#elseif !GRDBCIPHER
|
||||
#else
|
||||
case .remove:
|
||||
arguments.append("remove_diacritics=2")
|
||||
#endif
|
||||
|
||||
+11
-8
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -60,12 +63,12 @@ public struct FTS5 {
|
||||
/// Remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=1" tokenizer argument.
|
||||
case removeLegacy
|
||||
#if GRDBCUSTOMSQLITE
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=2" tokenizer argument,
|
||||
/// available from SQLite 3.27.0
|
||||
case remove
|
||||
#elseif !GRDBCIPHER
|
||||
#else
|
||||
/// Remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=2" tokenizer argument,
|
||||
/// available from SQLite 3.27.0
|
||||
@@ -117,8 +120,8 @@ public struct FTS5 {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#extending_fts5>
|
||||
public static func api(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
var statement: SQLiteStatement? = nil
|
||||
var api: UnsafePointer<fts5_api>? = nil
|
||||
var statement: SQLiteStatement?
|
||||
var api: UnsafePointer<fts5_api>?
|
||||
let type: StaticString = "fts5_api_ptr"
|
||||
|
||||
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine.
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
///
|
||||
/// ### Creating Raw FTS5 Patterns
|
||||
///
|
||||
/// - ``init(rawPattern:allowedColumns:)``
|
||||
/// - ``Database/makeFTS5Pattern(rawPattern:forTable:)``
|
||||
///
|
||||
///
|
||||
/// ### Creating FTS5 Patterns from User Input
|
||||
///
|
||||
/// - ``init(matchingAllPrefixesIn:)``
|
||||
@@ -123,7 +124,25 @@ public struct FTS5Pattern: Sendable {
|
||||
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
|
||||
init(rawPattern: String, allowedColumns: [String] = []) throws {
|
||||
/// Creates a pattern from a raw pattern string.
|
||||
///
|
||||
/// The pattern syntax is documented at <https://www.sqlite.org/fts5.html#full_text_query_syntax>
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// let pattern = try FTS5Pattern(rawPattern: "and")
|
||||
///
|
||||
/// // Throws an error: malformed MATCH expression: [AND]
|
||||
/// let pattern = try FTS5Pattern(rawPattern: "AND")
|
||||
/// ```
|
||||
///
|
||||
/// If the pattern tests for specific columns, you must pass those
|
||||
/// columns in the `allowedColumns` parameter.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` if the pattern has an invalid syntax.
|
||||
public init(rawPattern: String, allowedColumns: [String] = []) throws {
|
||||
// Correctness above all: use SQLite to validate the pattern.
|
||||
//
|
||||
// Invalid patterns have SQLite return an error on the first
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -208,7 +211,7 @@ extension Database {
|
||||
|
||||
self.xTokenizer = xTokenizer
|
||||
|
||||
var tokenizerPointer: OpaquePointer? = nil
|
||||
var tokenizerPointer: OpaquePointer?
|
||||
let code: CInt
|
||||
if arguments.isEmpty {
|
||||
code = xCreate(contextPointer, nil, 0, &tokenizerPointer)
|
||||
|
||||
@@ -182,10 +182,10 @@ public struct FTS5TokenizerDescriptor: Sendable {
|
||||
break
|
||||
case .keep:
|
||||
components.append(contentsOf: ["remove_diacritics", "0"])
|
||||
#if GRDBCUSTOMSQLITE
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
case .remove:
|
||||
components.append(contentsOf: ["remove_diacritics", "2"])
|
||||
#elseif !GRDBCIPHER
|
||||
#else
|
||||
case .remove:
|
||||
components.append(contentsOf: ["remove_diacritics", "2"])
|
||||
#endif
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let address = JSONColumn(CodingKeys.address) // JSONColumn!
|
||||
/// static let address = JSONColumn(CodingKeys.address) // JSONColumn
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
@@ -43,7 +43,7 @@
|
||||
/// // Fetch all country codes
|
||||
/// // SELECT DISTINCT address ->> 'countryCode' FROM player
|
||||
/// let countryCodes: [String] = try Player
|
||||
/// .select(Player.Columns.address["countryCode"], as: String.self)
|
||||
/// .select({ $0.address["countryCode"] }, as: String.self)
|
||||
/// .distinct()
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
@@ -59,8 +59,10 @@
|
||||
/// > extension Player: FetchableRecord, PersistableRecord {
|
||||
/// > // That's another valid way to define columns.
|
||||
/// > // But we don't have any JSONColumn this time.
|
||||
/// > enum Columns: String, ColumnExpression {
|
||||
/// > case id, name, address
|
||||
/// > enum Columns {
|
||||
/// > static let id = Column("id")
|
||||
/// > static let name = Column("name")
|
||||
/// > static let address = Column("address")
|
||||
/// > }
|
||||
/// > }
|
||||
/// >
|
||||
@@ -68,7 +70,7 @@
|
||||
/// > // Fetch all country codes
|
||||
/// > // SELECT DISTINCT address ->> 'countryCode' FROM player
|
||||
/// > let countryCodes: [String] = try Player
|
||||
/// > .select(Player.Columns.address.asJSON["countryCode"], as: String.self)
|
||||
/// > .select({ $0.address.asJSON["countryCode"] }, as: String.self)
|
||||
/// > .distinct()
|
||||
/// > .fetchAll(db)
|
||||
/// > }
|
||||
|
||||
@@ -135,12 +135,16 @@ extension SQLSpecificExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = Column("info").asJSON
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = Column("info")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .select({ $0.info.asJSON["firstName"] }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -150,25 +154,29 @@ extension SQLSpecificExpressible {
|
||||
}
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
extension SQLJSONExpressible {
|
||||
/// The `->>` SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .select({ $0.info["firstName"] }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info ->> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select(info["address"], as: String.self)
|
||||
/// .select({ $0.info["address"] }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -185,18 +193,22 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
|
||||
/// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
|
||||
/// .select({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -212,12 +224,16 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
|
||||
/// // → '["Arthur","Miller"]'
|
||||
/// let nameComponents = try Player
|
||||
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
|
||||
/// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -235,18 +251,22 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT info -> 'firstName' FROM player
|
||||
/// // → '"Arthur"'
|
||||
/// let name = try Player
|
||||
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
|
||||
/// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info -> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let name = try Player
|
||||
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
|
||||
/// .select({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -265,18 +285,22 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .select({ $0.info["firstName"] }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info ->> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select(info["address"], as: String.self)
|
||||
/// .select({ $0.info["address"] }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -294,18 +318,22 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
|
||||
/// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
|
||||
/// .select({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -322,12 +350,16 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
|
||||
/// // → '["Arthur","Miller"]'
|
||||
/// let nameComponents = try Player
|
||||
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
|
||||
/// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -346,18 +378,22 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT info -> 'firstName' FROM player
|
||||
/// // → '"Arthur"'
|
||||
/// let name = try Player
|
||||
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
|
||||
/// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info -> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let name = try Player
|
||||
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
|
||||
/// .select({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
// MARK: - JSON
|
||||
|
||||
extension Database {
|
||||
@@ -378,14 +378,21 @@ extension Database {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name")))
|
||||
/// Player.select { Database.jsonGroupArray($0.name) }
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
/// Player.select { Database.jsonGroupArray($0.name, filter: $0.score > 0) }
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name ORDER BY name) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), orderBy: Column("name")))
|
||||
/// Player.select { Database.jsonGroupArray($0.name, orderBy: $0.name) }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -407,16 +414,27 @@ extension Database {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
/// Player.select {
|
||||
/// Database.jsonGroupObject(
|
||||
/// key: $0.name,
|
||||
/// value: $0.score)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// Player.select {
|
||||
/// Database.jsonGroupObject(
|
||||
/// key: $0.name,
|
||||
/// value: $0.score,
|
||||
/// filter: $0.score > 0)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -698,14 +716,21 @@ extension Database {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_ARRAY(name) FROM player
|
||||
/// Player.select(Database.jsonbGroupArray(Column("name")))
|
||||
/// Player.select { Database.jsonbGroupArray($0.name) }
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonbGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
/// Player.select { Database.jsonbGroupArray($0.name, filter: $0.score > 0) }
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_ARRAY(name ORDER BY name) FROM player
|
||||
/// Player.select(Database.jsonbGroupArray(Column("name"), orderBy: Column("name")))
|
||||
/// Player.select { Database.jsonbGroupArray($0.name, orderBy: $0.name) }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -727,16 +752,27 @@ extension Database {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_OBJECT(name, score) FROM player
|
||||
/// Player.select(Database.jsonbGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
/// Player.select {
|
||||
/// Database.jsonbGroupObject(
|
||||
/// key: $0.name,
|
||||
/// value: $0.score)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonbGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// Player.select {
|
||||
/// Database.jsonbGroupObject(
|
||||
/// key: $0.name,
|
||||
/// value: $0.score,
|
||||
/// filter: $0.score > 0)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -1125,11 +1161,18 @@ extension Database {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name")))
|
||||
/// Player.select { Database.jsonGroupArray($0.name) }
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
/// Player.select { Database.jsonGroupArray($0.name, filter: $0.score > 0) }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -1150,16 +1193,27 @@ extension Database {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
/// Player.select {
|
||||
/// Database.jsonGroupObject(
|
||||
/// key: $0.name,
|
||||
/// value: $0.score)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// Player.select {
|
||||
/// Database.jsonGroupObject(
|
||||
/// key: $0.name,
|
||||
/// value: $0.score,
|
||||
/// filter: $0.score > 0)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
|
||||
@@ -18,6 +18,7 @@ import Foundation
|
||||
/// ### Registering Migrations
|
||||
///
|
||||
/// - ``registerMigration(_:foreignKeyChecks:migrate:)``
|
||||
/// - ``registerMigration(_:foreignKeyChecks:merging:migrate:)``
|
||||
/// - ``ForeignKeyChecks``
|
||||
///
|
||||
/// ### Configuring a DatabaseMigrator
|
||||
@@ -161,9 +162,8 @@ public struct DatabaseMigrator: Sendable {
|
||||
|
||||
/// Registers a migration.
|
||||
///
|
||||
/// The registered migration is appended to the list of migrations to run:
|
||||
/// it will execute after previously registered migrations, and before
|
||||
/// migrations that are registered later.
|
||||
/// The registered migration is appended to the list of migrations. It
|
||||
/// will execute after previously registered migrations.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -214,6 +214,107 @@ public struct DatabaseMigrator: Sendable {
|
||||
_ identifier: String,
|
||||
foreignKeyChecks: ForeignKeyChecks = .deferred,
|
||||
migrate: @escaping @Sendable (Database) throws -> Void)
|
||||
{
|
||||
registerMigration(identifier, foreignKeyChecks: foreignKeyChecks, merging: []) { db, ids in
|
||||
precondition(ids.isEmpty)
|
||||
try migrate(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers a merged migration.
|
||||
///
|
||||
/// Like migrations registered with ``registerMigration(_:foreignKeyChecks:migrate:)``,
|
||||
/// the merged migration is appended to the list of migrations. It
|
||||
/// will execute after previously registered migrations.
|
||||
///
|
||||
/// A merged migration merges and replaces a set of migrations defined
|
||||
/// in a previous version of the application. For example, to merge the
|
||||
/// migrations "v1", "v2" and "v3", redefine the "v3" migration so that
|
||||
/// it merges "v1" and "v2", as in the example below.
|
||||
///
|
||||
/// The second argument of the `migrate` closure is the subset of merged
|
||||
/// migrations that have already been applied when the merged
|
||||
/// migration runs.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Old code
|
||||
/// migrator.registerMigration("v1") { db in
|
||||
/// // Apply schema version 1
|
||||
/// }
|
||||
/// migrator.registerMigration("v2") { db in
|
||||
/// // Apply schema version 2
|
||||
/// }
|
||||
/// migrator.registerMigration("v3") { db in
|
||||
/// // Apply schema version 3
|
||||
/// }
|
||||
///
|
||||
/// // New code:
|
||||
/// // - Migrations v1 and v2 are deleted.
|
||||
/// // - Migration v3 is redefined and merges v1 and v2:
|
||||
/// migrator.registerMigration("v3", merging: ["v1", "v2"]) { db, appliedIDs in
|
||||
/// if !appliedIDs.contains("v1") {
|
||||
/// // Apply schema version 1
|
||||
/// }
|
||||
/// if !appliedIDs.contains("v2") {
|
||||
/// // Apply schema version 2
|
||||
/// }
|
||||
/// // Apply schema version 3
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// In the above sample code, the merged migration is named like the
|
||||
/// last one of the merged set. You can also give it a brand new name,
|
||||
/// as in the alternative below. Notice the different logic in the
|
||||
/// migration code.
|
||||
///
|
||||
/// **In all cases avoid naming the merged migration like the first
|
||||
/// elements in the merged set** (`v1` or `v2` in our example).
|
||||
///
|
||||
/// ```swift
|
||||
/// // Alternative new code:
|
||||
/// // - Migrations v1, v2 and v3 are deleted.
|
||||
/// // - The new migration v3-new merges v1, v2 and v3:
|
||||
/// migrator.registerMigration("v3-new", merging: ["v1", "v2", "v3"]) { db, appliedIDs in
|
||||
/// if !appliedIDs.contains("v1") {
|
||||
/// // Apply schema version 1
|
||||
/// }
|
||||
/// if !appliedIDs.contains("v2") {
|
||||
/// // Apply schema version 2
|
||||
/// }
|
||||
/// if !appliedIDs.contains("v3") {
|
||||
/// // Apply schema version 3
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - identifier: The migration identifier.
|
||||
/// - mergedIdentifiers: A set of previous migration identifiers
|
||||
/// that are merged in this migration.
|
||||
/// - foreignKeyChecks: This parameter is ignored if the database
|
||||
/// ``Configuration`` has disabled foreign keys.
|
||||
///
|
||||
/// The default `.deferred` checks have the migration run with
|
||||
/// disabled foreign keys, until foreign keys are checked right before
|
||||
/// changes are committed on disk. These deferred checks are not
|
||||
/// executed if the migrator is the result of
|
||||
/// ``disablingDeferredForeignKeyChecks()``.
|
||||
///
|
||||
/// The `.immediate` checks have the migration run with foreign
|
||||
/// keys enabled. Make sure you only use `.immediate` if the migration
|
||||
/// 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. The
|
||||
/// 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
|
||||
/// been registered.
|
||||
public mutating func registerMigration(
|
||||
_ identifier: String,
|
||||
foreignKeyChecks: ForeignKeyChecks = .deferred,
|
||||
merging mergedIdentifiers: Set<String> = [],
|
||||
migrate: @escaping @Sendable (_ db: Database, _ appliedIdentifiers: Set<String>) throws -> Void)
|
||||
{
|
||||
let migrationChecks: Migration.ForeignKeyChecks
|
||||
switch foreignKeyChecks {
|
||||
@@ -226,7 +327,18 @@ public struct DatabaseMigrator: Sendable {
|
||||
case .immediate:
|
||||
migrationChecks = .immediate
|
||||
}
|
||||
registerMigration(Migration(identifier: identifier, foreignKeyChecks: migrationChecks, migrate: migrate))
|
||||
|
||||
// Remove the migration identifier from the list of merged identifiers.
|
||||
// Arguably, the semantics are ambiguous. And raising a fatal error
|
||||
// is a high price when we can just fix the input.
|
||||
var mergedIdentifiers = mergedIdentifiers
|
||||
mergedIdentifiers.remove(identifier)
|
||||
|
||||
registerMigration(Migration(
|
||||
identifier: identifier,
|
||||
mergedIdentifiers: mergedIdentifiers,
|
||||
foreignKeyChecks: migrationChecks,
|
||||
migrate: migrate))
|
||||
}
|
||||
|
||||
// MARK: - Applying Migrations
|
||||
@@ -450,6 +562,16 @@ public struct DatabaseMigrator: Sendable {
|
||||
|
||||
// MARK: - Non public
|
||||
|
||||
private struct Execution {
|
||||
enum Mode {
|
||||
case run(mergedIdentifiers: Set<String>)
|
||||
case deleteMergedIdentifiers
|
||||
}
|
||||
|
||||
var migration: Migration
|
||||
var mode: Mode
|
||||
}
|
||||
|
||||
private mutating func registerMigration(_ migration: Migration) {
|
||||
GRDBPrecondition(
|
||||
!_migrations.map({ $0.identifier }).contains(migration.identifier),
|
||||
@@ -457,8 +579,8 @@ public struct DatabaseMigrator: Sendable {
|
||||
_migrations.append(migration)
|
||||
}
|
||||
|
||||
/// Returns unapplied migration identifier,
|
||||
private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: [String]) -> [Migration] {
|
||||
/// Returns unapplied migration executions
|
||||
private func unappliedExecutions(upTo targetIdentifier: String, appliedIdentifiers: Set<String>) -> [Execution] {
|
||||
var expectedMigrations: [Migration] = []
|
||||
for migration in _migrations {
|
||||
expectedMigrations.append(migration)
|
||||
@@ -472,32 +594,52 @@ public struct DatabaseMigrator: Sendable {
|
||||
expectedMigrations.last?.identifier == targetIdentifier,
|
||||
"undefined migration: \(String(reflecting: targetIdentifier))")
|
||||
|
||||
return expectedMigrations.filter { !appliedIdentifiers.contains($0.identifier) }
|
||||
return expectedMigrations.compactMap { migration in
|
||||
if appliedIdentifiers.contains(migration.identifier) {
|
||||
if migration.mergedIdentifiers.isDisjoint(with: appliedIdentifiers) {
|
||||
// Nothing to do
|
||||
return nil
|
||||
} else {
|
||||
// Migration is applied, but we have some merged identifiers to delete
|
||||
return Execution(migration: migration, mode: .deleteMergedIdentifiers)
|
||||
}
|
||||
} else {
|
||||
// Migration is not applied yet.
|
||||
let appliedMergedIdentifiers = migration.mergedIdentifiers.intersection(appliedIdentifiers)
|
||||
return Execution(migration: migration, mode: .run(mergedIdentifiers: appliedMergedIdentifiers))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
|
||||
try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
|
||||
let appliedIdentifiers = try self.appliedMigrations(db)
|
||||
|
||||
// Subsequent migration must not be applied
|
||||
let appliedMigrations = try self.appliedMigrations(db) // Only known ids
|
||||
if let targetIndex = _migrations.firstIndex(where: { $0.identifier == targetIdentifier }),
|
||||
let lastAppliedIdentifier = appliedIdentifiers.last,
|
||||
let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedIdentifier }),
|
||||
let lastAppliedMigration = appliedMigrations.last,
|
||||
let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedMigration }),
|
||||
targetIndex < lastAppliedIndex
|
||||
{
|
||||
fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
|
||||
}
|
||||
|
||||
let unappliedMigrations = self.unappliedMigrations(
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db) // All ids, even unknown ones
|
||||
let unappliedExecutions = self.unappliedExecutions(
|
||||
upTo: targetIdentifier,
|
||||
appliedIdentifiers: appliedIdentifiers)
|
||||
|
||||
if unappliedMigrations.isEmpty {
|
||||
if unappliedExecutions.isEmpty {
|
||||
return
|
||||
}
|
||||
|
||||
for migration in unappliedMigrations {
|
||||
try migration.run(db)
|
||||
for execution in unappliedExecutions {
|
||||
switch execution.mode {
|
||||
case .run(let mergedIdentifiers):
|
||||
try execution.migration.run(db, mergedIdentifiers: mergedIdentifiers)
|
||||
case .deleteMergedIdentifiers:
|
||||
try execution.migration.deleteMergedIdentifiers(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,40 +6,68 @@ struct Migration: Sendable {
|
||||
case disabled
|
||||
}
|
||||
|
||||
let identifier: String
|
||||
var foreignKeyChecks: ForeignKeyChecks
|
||||
let migrate: @Sendable (Database) throws -> Void
|
||||
typealias Migrate = @Sendable (_ db: Database, _ mergedIdentifiers: Set<String>) throws -> Void
|
||||
|
||||
func run(_ db: Database) throws {
|
||||
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
|
||||
switch foreignKeyChecks {
|
||||
case .deferred:
|
||||
try runWithDeferredForeignKeysChecks(db)
|
||||
case .immediate:
|
||||
try runWithImmediateForeignKeysChecks(db)
|
||||
case .disabled:
|
||||
try runWithDisabledForeignKeysChecks(db)
|
||||
let identifier: String
|
||||
let mergedIdentifiers: Set<String>
|
||||
var foreignKeyChecks: ForeignKeyChecks
|
||||
// Private so that the guarantees of `run(_:)` are enforced.
|
||||
private let migrate: Migrate
|
||||
|
||||
init(
|
||||
identifier: String,
|
||||
mergedIdentifiers: Set<String>,
|
||||
foreignKeyChecks: ForeignKeyChecks,
|
||||
migrate: @escaping Migrate
|
||||
) {
|
||||
self.identifier = identifier
|
||||
self.mergedIdentifiers = mergedIdentifiers
|
||||
self.foreignKeyChecks = foreignKeyChecks
|
||||
self.migrate = migrate
|
||||
}
|
||||
|
||||
func run(_ db: Database, mergedIdentifiers: Set<String>) throws {
|
||||
// Migrations access the raw SQLite schema, without alteration due
|
||||
// to the schemaSource. The goal is to ensure that migrations are
|
||||
// immutable, immune from spooky actions at a distance.
|
||||
try db.withSchemaSource(nil) {
|
||||
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
|
||||
switch foreignKeyChecks {
|
||||
case .deferred:
|
||||
try runWithDeferredForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
|
||||
case .immediate:
|
||||
try runWithImmediateForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
|
||||
case .disabled:
|
||||
try runWithDisabledForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
|
||||
}
|
||||
} else {
|
||||
try runWithImmediateForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
|
||||
}
|
||||
} else {
|
||||
try runWithImmediateForeignKeysChecks(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func runWithImmediateForeignKeysChecks(_ db: Database) throws {
|
||||
|
||||
func deleteMergedIdentifiers(_ db: Database) throws {
|
||||
if mergedIdentifiers.isEmpty == false {
|
||||
try db.execute(literal: "DELETE FROM grdb_migrations WHERE identifier IN \(mergedIdentifiers)")
|
||||
}
|
||||
}
|
||||
|
||||
private func runWithImmediateForeignKeysChecks(_ db: Database, mergedIdentifiers: Set<String>) throws {
|
||||
try db.inTransaction(.immediate) {
|
||||
try migrate(db)
|
||||
try insertAppliedIdentifier(db)
|
||||
try migrate(db, mergedIdentifiers)
|
||||
try updateAppliedIdentifier(db)
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
private func runWithDisabledForeignKeysChecks(_ db: Database) throws {
|
||||
private func runWithDisabledForeignKeysChecks(_ db: Database, mergedIdentifiers: Set<String>) throws {
|
||||
try db.execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
try throwingFirstError(
|
||||
execute: {
|
||||
try db.inTransaction(.immediate) {
|
||||
try migrate(db)
|
||||
try insertAppliedIdentifier(db)
|
||||
try migrate(db, mergedIdentifiers)
|
||||
try updateAppliedIdentifier(db)
|
||||
return .commit
|
||||
}
|
||||
},
|
||||
@@ -48,7 +76,7 @@ struct Migration: Sendable {
|
||||
})
|
||||
}
|
||||
|
||||
private func runWithDeferredForeignKeysChecks(_ db: Database) throws {
|
||||
private func runWithDeferredForeignKeysChecks(_ db: Database, mergedIdentifiers: Set<String>) throws {
|
||||
// Support for database alterations described at
|
||||
// https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
//
|
||||
@@ -60,8 +88,8 @@ struct Migration: Sendable {
|
||||
execute: {
|
||||
// > 2. Start a transaction.
|
||||
try db.inTransaction(.immediate) {
|
||||
try migrate(db)
|
||||
try insertAppliedIdentifier(db)
|
||||
try migrate(db, mergedIdentifiers)
|
||||
try updateAppliedIdentifier(db)
|
||||
|
||||
// > 10. If foreign key constraints were originally enabled
|
||||
// > then run PRAGMA foreign_key_check to verify that the
|
||||
@@ -80,7 +108,8 @@ struct Migration: Sendable {
|
||||
})
|
||||
}
|
||||
|
||||
private func insertAppliedIdentifier(_ db: Database) throws {
|
||||
try db.execute(sql: "INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
|
||||
private func updateAppliedIdentifier(_ db: Database) throws {
|
||||
try deleteMergedIdentifiers(db)
|
||||
try db.execute(literal: "INSERT INTO grdb_migrations (identifier) VALUES (\(identifier))")
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ extension TableRequest where Self: FilteredRequest {
|
||||
}
|
||||
let alias = TableAlias()
|
||||
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
|
||||
return self.aliased(alias).filter(matchExpression)
|
||||
return self._aliased(alias).filter(matchExpression)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ extension TableRequest where Self: FilteredRequest {
|
||||
}
|
||||
let alias = TableAlias()
|
||||
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
|
||||
return self.aliased(alias).filter(matchExpression)
|
||||
return self._aliased(alias).filter(matchExpression)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,9 +25,14 @@
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let authorId = Column("authorId")
|
||||
/// static let translatorId = Column("translatorId")
|
||||
/// }
|
||||
///
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"]))
|
||||
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
|
||||
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
|
||||
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(
|
||||
@@ -41,19 +46,6 @@
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Foreign keys can also be defined from query interface columns:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord {
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, title, authorId, translatorId
|
||||
/// }
|
||||
///
|
||||
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
|
||||
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When the destination table does not define any primary key, you need to
|
||||
/// provide the destination columns:
|
||||
///
|
||||
|
||||
@@ -164,7 +164,7 @@ extension Association {
|
||||
|
||||
// TableRequest conformance
|
||||
extension Association {
|
||||
public func aliased(_ alias: TableAlias) -> Self {
|
||||
public func _aliased(_ alias: TableAliasBase) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.aliased(alias)
|
||||
}
|
||||
@@ -305,15 +305,25 @@ extension AssociationToOne {
|
||||
///
|
||||
/// ### Building Association Aggregates
|
||||
///
|
||||
/// - ``average(_:)``
|
||||
/// - ``average(_:)-1ehdb``
|
||||
/// - ``count``
|
||||
/// - ``isEmpty``
|
||||
/// - ``max(_:)``
|
||||
/// - ``min(_:)``
|
||||
/// - ``sum(_:)``
|
||||
/// - ``total(_:)``
|
||||
/// - ``max(_:)-a32j``
|
||||
/// - ``min(_:)-41jp8``
|
||||
/// - ``sum(_:)-47yg7``
|
||||
/// - ``total(_:)-6dd9d``
|
||||
///
|
||||
/// - ``AssociationAggregate``
|
||||
///
|
||||
/// ### Legacy APIs
|
||||
///
|
||||
/// It is recommended to prefer the closure-based apis defined above.
|
||||
///
|
||||
/// - ``average(_:)-4bbk9``
|
||||
/// - ``max(_:)-4g5ut``
|
||||
/// - ``min(_:)-6al4w``
|
||||
/// - ``sum(_:)-6ge96``
|
||||
/// - ``total(_:)-56v8i``
|
||||
public protocol AssociationToMany: Association { }
|
||||
|
||||
extension AssociationToMany {
|
||||
|
||||
@@ -136,6 +136,56 @@ extension AssociationToMany {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the average of the given expression in associated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Team: FetchableRecord, TableRecord {
|
||||
/// static let players = Team.hasMany(Player.self)
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // Fetch all teams whose average player score is greater than 1000
|
||||
/// let averageScore = Team.players.average(\.score)
|
||||
/// let teams: [Team] = try Team
|
||||
/// .having(averageScore >= 1000)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When the input expression is a ``ColumnExpression``, the returned
|
||||
/// association aggregate is named `"average[Key][Column]"`, where `key` is
|
||||
/// the association key. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var averagePlayerScore: Double
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let averageScore = Team.players.average(\.score)
|
||||
/// let infos: [TeamInfo] = try Team
|
||||
/// .annotated(with: averageScore)
|
||||
/// .asRequest(of: TeamInfo.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public func average(
|
||||
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
|
||||
) rethrows -> AssociationAggregate<OriginRowDecoder>
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try average(expression(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns the maximum value of the given expression in associated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -183,6 +233,56 @@ extension AssociationToMany {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the maximum value of the given expression in associated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Team: FetchableRecord, TableRecord {
|
||||
/// static let players = Team.hasMany(Player.self)
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // Fetch all teams whose maximum player score is greater than 1000
|
||||
/// let maxScore = Team.players.max(\.score)
|
||||
/// let teams: [Team] = try Team
|
||||
/// .having(maxScore >= 1000)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When the input expression is a ``ColumnExpression``, the returned
|
||||
/// association aggregate is named `"maximum[Key][Column]"`, where `key` is
|
||||
/// the association key. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var maximumPlayerScore: Double
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let maxScore = Team.players.max(\.score)
|
||||
/// let infos: [TeamInfo] = try Team
|
||||
/// .annotated(with: maxScore)
|
||||
/// .asRequest(of: TeamInfo.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public func max(
|
||||
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
|
||||
) rethrows -> AssociationAggregate<OriginRowDecoder>
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try max(expression(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns the minimum value of the given expression in associated records.
|
||||
///
|
||||
/// For example:
|
||||
@@ -230,10 +330,61 @@ extension AssociationToMany {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the minimum value of the given expression in associated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Team: FetchableRecord, TableRecord {
|
||||
/// static let players = Team.hasMany(Player.self)
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // Fetch all teams whose minimum player score is less than 1000
|
||||
/// let minScore = Team.players.min(\.score)
|
||||
/// let teams: [Team] = try Team
|
||||
/// .having(minScore < 1000)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When the input expression is a ``ColumnExpression``, the returned
|
||||
/// association aggregate is named `"minimum[Key][Column]"`, where `key` is
|
||||
/// the association key. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var minimumPlayerScore: Double
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let minScore = Team.players.min(\.score)
|
||||
/// let infos: [TeamInfo] = try Team
|
||||
/// .annotated(with: minScore)
|
||||
/// .asRequest(of: TeamInfo.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public func min(
|
||||
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
|
||||
) rethrows -> AssociationAggregate<OriginRowDecoder>
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try min(expression(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns the sum of the given expression in associated records.
|
||||
///
|
||||
/// This aggregate invokes the `SUM` SQL function. See also ``total(_:)``
|
||||
/// and <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
/// This aggregate invokes the `SUM` SQL function.
|
||||
/// See also ``AssociationToMany/total(_:)-56v8i`` and
|
||||
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -282,8 +433,63 @@ extension AssociationToMany {
|
||||
|
||||
/// Returns the sum of the given expression in associated records.
|
||||
///
|
||||
/// This aggregate invokes the `TOTAL` SQL function. See also ``sum(_:)``
|
||||
/// and <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
/// This aggregate invokes the `SUM` SQL function.
|
||||
/// See also ``AssociationToMany/total(_:)-6dd9d`` and
|
||||
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Team: FetchableRecord, TableRecord {
|
||||
/// static let players = Team.hasMany(Player.self)
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // Fetch all teams whose sum of player scores is greater than 1000
|
||||
/// let scoreSum = Team.players.sum(\.score)
|
||||
/// let teams: [Team] = try Team
|
||||
/// .having(scoreSum >= 1000)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When the input expression is a ``ColumnExpression``, the returned
|
||||
/// association aggregate is named `"[key][Column]Sum"`, where `key` is the
|
||||
/// association key. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var playerScoreSum: Double
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let scoreSum = Team.players.sum(\.score)
|
||||
/// let infos: [TeamInfo] = try Team
|
||||
/// .annotated(with: scoreSum)
|
||||
/// .asRequest(of: TeamInfo.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public func sum(
|
||||
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
|
||||
) rethrows -> AssociationAggregate<OriginRowDecoder>
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try sum(expression(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns the sum of the given expression in associated records.
|
||||
///
|
||||
/// This aggregate invokes the `TOTAL` SQL function.
|
||||
/// See also ``AssociationToMany/sum(_:)-6ge96`` and
|
||||
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -331,6 +537,64 @@ extension AssociationToMany {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the sum of the given expression in associated records.
|
||||
///
|
||||
/// This aggregate invokes the `TOTAL` SQL function.
|
||||
/// See also ``AssociationToMany/sum(_:)-47yg7`` and
|
||||
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Team: FetchableRecord, TableRecord {
|
||||
/// static let players = Team.hasMany(Player.self)
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // Fetch all teams whose sum of player scores is greater than 1000
|
||||
/// let totalScore = Team.players.total(\.score)
|
||||
/// let teams: [Team] = try Team
|
||||
/// .having(totalScore >= 1000)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When the input expression is a ``ColumnExpression``, the returned
|
||||
/// association aggregate is named `"[key][Column]Sum"`, where `key` is the
|
||||
/// association key. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var playerScoreSum: Double
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let totalScore = Team.players.total(\.score)
|
||||
/// let infos: [TeamInfo] = try Team
|
||||
/// .annotated(with: totalScore)
|
||||
/// .asRequest(of: TeamInfo.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public func total(
|
||||
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
|
||||
) rethrows -> AssociationAggregate<OriginRowDecoder>
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try total(expression(RowDecoder.databaseComponents))
|
||||
}
|
||||
}
|
||||
|
||||
extension AssociationToMany where RowDecoder: TableRecord {
|
||||
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
|
||||
}
|
||||
|
||||
/// A value aggregated from a population of associated records.
|
||||
@@ -372,7 +636,7 @@ public struct AssociationAggregate<RowDecoder> {
|
||||
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
|
||||
|
||||
/// The SQL name for the value of this aggregate. See forKey(_:).
|
||||
var key: String? = nil
|
||||
var key: String?
|
||||
|
||||
/// Extends the request with the associated records used to compute the
|
||||
/// aggregate, and returns the aggregated expression.
|
||||
|
||||
@@ -385,12 +385,18 @@ extension CommonTableExpression {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>,
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (
|
||||
_ left: TableAlias<RowDecoder>,
|
||||
_ right: TableAlias<Destination>
|
||||
) -> any SQLExpressible
|
||||
)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
to: cte.relationForAll,
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
condition: .expression { left, right in
|
||||
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates an association to a common table expression that you can join
|
||||
@@ -421,13 +427,18 @@ extension CommonTableExpression {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to destination: Destination.Type,
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (
|
||||
_ left: TableAlias<RowDecoder>,
|
||||
_ right: TableAlias<Destination>
|
||||
) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
where Destination: TableRecord
|
||||
{
|
||||
JoinAssociation(
|
||||
to: Destination.relationForAll,
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
condition: .expression { left, right in
|
||||
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates an association to a table record that you can join
|
||||
@@ -458,12 +469,17 @@ extension CommonTableExpression {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to destination: Table<Destination>,
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (
|
||||
_ left: TableAlias<RowDecoder>,
|
||||
_ right: TableAlias<Destination>
|
||||
) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
to: destination.relationForAll,
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
condition: .expression { left, right in
|
||||
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates an association to a table that you can join
|
||||
|
||||
@@ -23,15 +23,20 @@
|
||||
/// ``Table`` instance. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord, FetchableRecord, DecodableRecord { }
|
||||
/// struct Player: TableRecord, FetchableRecord, DecodableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // SELECT * FROM player
|
||||
/// // WHERE name = 'O''Reilly'
|
||||
/// // ORDER BY score DESC
|
||||
/// let request = Player
|
||||
/// .filter(Column("name") == "O'Reilly")
|
||||
/// .order(Column("score").desc)
|
||||
/// .filter { $0.name == "O'Reilly" }
|
||||
/// .order(\.score.desc)
|
||||
/// let players: [Player] = try request.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
@@ -52,8 +57,7 @@
|
||||
/// ### Changing The Type of Fetched Results
|
||||
///
|
||||
/// - ``asRequest(of:)``
|
||||
/// - ``select(_:as:)-282xc``
|
||||
/// - ``select(_:as:)-3o8qw``
|
||||
/// - ``select(_:as:)-4cj9h``
|
||||
/// - ``select(literal:as:)``
|
||||
/// - ``select(sql:arguments:as:)``
|
||||
/// - ``selectID()``
|
||||
@@ -66,17 +70,31 @@
|
||||
/// - ``deleteAndFetchCursor(_:)``
|
||||
/// - ``deleteAndFetchAll(_:)``
|
||||
/// - ``deleteAndFetchSet(_:)``
|
||||
/// - ``deleteAndFetchStatement(_:selection:)``
|
||||
/// - ``deleteAndFetchStatement(_:select:)``
|
||||
///
|
||||
/// ### Batch Update
|
||||
///
|
||||
/// - ``updateAll(_:onConflict:assignment:)``
|
||||
/// - ``updateAll(_:onConflict:assignments:)``
|
||||
/// - ``updateAndFetchCursor(_:onConflict:assignments:)``
|
||||
/// - ``updateAndFetchAll(_:onConflict:assignments:)``
|
||||
/// - ``updateAndFetchSet(_:onConflict:assignments:)``
|
||||
/// - ``updateAndFetchStatement(_:onConflict:assignments:select:)``
|
||||
/// - ``ColumnAssignment``
|
||||
///
|
||||
/// ### Legacy APIs
|
||||
///
|
||||
/// It is recommended to prefer the closure-based apis defined above.
|
||||
///
|
||||
/// - ``deleteAndFetchStatement(_:selection:)``
|
||||
/// - ``select(_:as:)-282xc``
|
||||
/// - ``select(_:as:)-3o8qw``
|
||||
/// - ``updateAll(_:onConflict:_:)-9r4v``
|
||||
/// - ``updateAll(_:onConflict:_:)-49qg8``
|
||||
/// - ``updateAndFetchCursor(_:onConflict:_:)``
|
||||
/// - ``updateAndFetchAll(_:onConflict:_:)``
|
||||
/// - ``updateAndFetchSet(_:onConflict:_:)``
|
||||
/// - ``updateAndFetchStatement(_:onConflict:_:selection:)``
|
||||
/// - ``ColumnAssignment``
|
||||
public struct QueryInterfaceRequest<RowDecoder> {
|
||||
var relation: SQLRelation
|
||||
}
|
||||
@@ -187,6 +205,37 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
select(selection, as: type)
|
||||
}
|
||||
|
||||
/// Defines the result columns, and defines the type of decoded rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id FROM player
|
||||
/// let request = Player.all().select(\.id, as: Int.self)
|
||||
/// let scores = try request.fetchSet(db) // Set<Int>
|
||||
///
|
||||
/// // SELECT MAX(score) FROM player
|
||||
/// let request = Player.all().select({ max($0.score) }, as: Int.self)
|
||||
/// let maxScore = try request.fetchOne(db) // Int?
|
||||
/// ```
|
||||
///
|
||||
/// Any previous selection is discarded.
|
||||
public func select<T>(
|
||||
_ selection: (DatabaseComponents) throws -> any SQLSelectable,
|
||||
as type: T.Type = T.self
|
||||
) rethrows -> QueryInterfaceRequest<T>
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try select(selection).asRequest(of: T.self)
|
||||
}
|
||||
|
||||
/// Defines the result columns with an SQL string, and defines the type of
|
||||
/// decoded rows.
|
||||
///
|
||||
@@ -313,11 +362,13 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
|
||||
where RowDecoder: Identifiable
|
||||
{
|
||||
selectWhenConnected { db in
|
||||
let primaryKey = try db.primaryKey(self.databaseTableName)
|
||||
let databaseTableName = self.databaseTableName
|
||||
|
||||
return selectWhenConnected { db in
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
|
||||
"selectID requires a single-column primary key in the table \(databaseTableName)")
|
||||
return [Column(primaryKey.columns[0])]
|
||||
}.asRequest(of: RowDecoder.ID.self)
|
||||
}
|
||||
@@ -361,15 +412,27 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
|
||||
/// Creates a request that reverses applied orderings.
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name DESC
|
||||
/// var request = Player.all().order(Column("name"))
|
||||
/// request = request.reversed()
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name DESC
|
||||
/// var request = Player.all().order(\.name)
|
||||
/// request = request.reversed()
|
||||
/// ```
|
||||
///
|
||||
/// If no ordering was applied, the returned request is identical.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.reversed()
|
||||
/// ```swift
|
||||
/// // SELECT * FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.reversed()
|
||||
/// ```
|
||||
public func reversed() -> Self {
|
||||
with {
|
||||
$0.relation = $0.relation.reversed()
|
||||
@@ -378,9 +441,18 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
|
||||
/// Creates a request without any ordering.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// var request = Player.all().order(Column("name"))
|
||||
/// request = request.unordered()
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// let request = Player.all()
|
||||
/// .order(\.name)
|
||||
/// .unordered()
|
||||
/// ```
|
||||
public func unordered() -> Self {
|
||||
with {
|
||||
$0.relation = $0.relation.unordered()
|
||||
@@ -455,7 +527,7 @@ extension QueryInterfaceRequest: TableRequest {
|
||||
relation.source.tableName
|
||||
}
|
||||
|
||||
public func aliased(_ alias: TableAlias) -> Self {
|
||||
public func _aliased(_ alias: TableAliasBase) -> Self {
|
||||
with {
|
||||
$0.relation = $0.relation.aliased(alias)
|
||||
}
|
||||
@@ -503,9 +575,15 @@ extension QueryInterfaceRequest {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let maxScore: Int? = try Player
|
||||
/// .select(max(scoreColumn))
|
||||
/// .select { max($0.score) }
|
||||
/// .asRequest(of: Int.self) // <--
|
||||
/// .fetchOne(db)
|
||||
/// }
|
||||
@@ -515,6 +593,10 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: TableRecord {
|
||||
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
|
||||
}
|
||||
|
||||
// MARK: - Check Existence
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
@@ -523,9 +605,15 @@ extension QueryInterfaceRequest {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let arthurIsMissing = try Player
|
||||
/// .filter(Column("name") == "Arthur")
|
||||
/// .filter { $0.name == "Arthur" }
|
||||
/// .isEmpty(db)
|
||||
/// }
|
||||
/// ```
|
||||
@@ -547,15 +635,18 @@ extension QueryInterfaceRequest {
|
||||
@discardableResult
|
||||
public func deleteAll(_ db: Database) throws -> Int {
|
||||
let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db)
|
||||
try statement.execute()
|
||||
return db.changesCount
|
||||
var changesCount = 0
|
||||
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
|
||||
try statement.execute()
|
||||
}
|
||||
return changesCount
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Batch Delete and Fetch
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Returns a `DELETE RETURNING` prepared statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -586,6 +677,43 @@ extension QueryInterfaceRequest {
|
||||
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
|
||||
}
|
||||
|
||||
/// Returns a `DELETE RETURNING` prepared statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Delete all players and return their names
|
||||
/// // DELETE FROM player RETURNING name
|
||||
/// let request = Player.all()
|
||||
/// let statement = try request.deleteAndFetchStatement(db, selection: \.name)
|
||||
/// let deletedNames = try String.fetchSet(statement)
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter select: A closure that returns the returned columns
|
||||
/// (must not be empty).
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The result of `select` is not empty.
|
||||
public func deleteAndFetchStatement(
|
||||
_ db: Database,
|
||||
select: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) throws -> Statement
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns a cursor over the records deleted by a
|
||||
/// `DELETE RETURNING` statement.
|
||||
///
|
||||
@@ -733,6 +861,44 @@ extension QueryInterfaceRequest {
|
||||
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
|
||||
}
|
||||
|
||||
/// Returns a `DELETE RETURNING` prepared statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Delete all players and return their names
|
||||
/// // DELETE FROM player RETURNING name
|
||||
/// let request = Player.all()
|
||||
/// let statement = try request.deleteAndFetchStatement(db, selection: \.name)
|
||||
/// let deletedNames = try String.fetchSet(statement)
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter select: A closure that returns the returned columns
|
||||
/// (must not be empty).
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The result of `select` is not empty.
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func deleteAndFetchStatement(
|
||||
_ db: Database,
|
||||
select: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) throws -> Statement
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns a cursor over the records deleted by a
|
||||
/// `DELETE RETURNING` statement.
|
||||
///
|
||||
@@ -871,6 +1037,75 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates matching rows, and returns the number of updated rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// let request = Player.all()
|
||||
/// try request.updateAll(db) { $0.score.set(to: 0) }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignment: A closure that returns an assignment.
|
||||
/// - returns: The number of updated rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public func updateAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignment: (DatabaseComponents) throws -> ColumnAssignment
|
||||
) throws -> Int
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try updateAll(db, onConflict: conflictResolution, [assignment(RowDecoder.databaseComponents)])
|
||||
}
|
||||
|
||||
/// Updates matching rows, and returns the number of updated rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// let request = Player.all()
|
||||
/// try request.updateAll(db) { $0.score.set(to: 0) }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments.
|
||||
/// - returns: The number of updated rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public func updateAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
|
||||
) throws -> Int
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try updateAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Updates matching rows, and returns the number of updated rows.
|
||||
///
|
||||
/// For example:
|
||||
@@ -903,8 +1138,11 @@ extension QueryInterfaceRequest {
|
||||
// database not hit
|
||||
return 0
|
||||
}
|
||||
try updateStatement.execute()
|
||||
return db.changesCount
|
||||
var changesCount = 0
|
||||
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
|
||||
try updateStatement.execute()
|
||||
}
|
||||
return changesCount
|
||||
}
|
||||
|
||||
/// Updates matching rows, and returns the number of updated rows.
|
||||
@@ -938,7 +1176,58 @@ extension QueryInterfaceRequest {
|
||||
// MARK: - Batch Update and Fetch
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Returns an `UPDATE RETURNING` prepared statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Fetch all updated scores
|
||||
/// // UPDATE player SET score = score + 10 RETURNING score
|
||||
/// let request = Player.all()
|
||||
/// let statement = try request.updateAndFetchStatement(db) {
|
||||
/// $0.score += 10
|
||||
/// } select: {
|
||||
/// [$0.score]
|
||||
/// }
|
||||
/// let updatedScores = try Int.fetchAll(statement)
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments (must not be empty).
|
||||
/// - parameter selection: A closure that returns the returned columns
|
||||
/// (must not be empty).
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The results of `select` and `assignments` results
|
||||
/// are not empty.
|
||||
public func updateAndFetchStatement(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
|
||||
select: (DatabaseComponents) -> [any SQLSelectable]
|
||||
) throws -> Statement
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try updateAndFetchStatement(
|
||||
db,
|
||||
onConflict: conflictResolution,
|
||||
assignments(RowDecoder.databaseComponents),
|
||||
selection: select(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns an `UPDATE RETURNING` prepared statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -987,6 +1276,48 @@ extension QueryInterfaceRequest {
|
||||
return updateStatement
|
||||
}
|
||||
|
||||
/// Returns a cursor over the records updated by an
|
||||
/// `UPDATE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Fetch all updated players
|
||||
/// // UPDATE player SET score = score + 10 RETURNING *
|
||||
/// let request = Player.all()
|
||||
/// let players = try request.updateAndFetchCursor(db) { [$0.score += 10] }
|
||||
/// while let player = try players.next() {
|
||||
/// print("Player \(player) was updated")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments.
|
||||
/// - returns: A cursor over the updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The result of `assignments` is not empty.
|
||||
public func updateAndFetchCursor(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
|
||||
) throws -> RecordCursor<RowDecoder>
|
||||
where RowDecoder: FetchableRecord & TableRecord
|
||||
{
|
||||
try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns a cursor over the records updated by an
|
||||
/// `UPDATE RETURNING` statement.
|
||||
///
|
||||
@@ -1027,6 +1358,45 @@ extension QueryInterfaceRequest {
|
||||
return try RowDecoder.fetchCursor(statement)
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the array of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Fetch all updated players
|
||||
/// // UPDATE player SET score = score + 10 RETURNING *
|
||||
/// let request = Player.all()
|
||||
/// let updatedPlayers = try request.updateAndFetchAll(db) { [$0.score += 10] }
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments.
|
||||
/// - returns: An array of updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The result of `assignments` is not empty.
|
||||
public func updateAndFetchAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
|
||||
) throws -> [RowDecoder]
|
||||
where RowDecoder: FetchableRecord & TableRecord
|
||||
{
|
||||
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the array of
|
||||
/// updated records.
|
||||
///
|
||||
@@ -1059,6 +1429,45 @@ extension QueryInterfaceRequest {
|
||||
try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the set of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Fetch all updated players
|
||||
/// // UPDATE player SET score = score + 10 RETURNING *
|
||||
/// let request = Player.all()
|
||||
/// let updatedPlayers = try request.updateAndFetchSet(db) { [$0.score += 10]) }
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments.
|
||||
/// - returns: A set of updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The result of `assignments` is not empty.
|
||||
public func updateAndFetchSet(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
|
||||
) throws -> Set<RowDecoder>
|
||||
where RowDecoder: FetchableRecord & TableRecord & Hashable
|
||||
{
|
||||
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the set of
|
||||
/// updated records.
|
||||
///
|
||||
@@ -1091,6 +1500,58 @@ extension QueryInterfaceRequest {
|
||||
try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
|
||||
}
|
||||
#else
|
||||
/// Returns an `UPDATE RETURNING` prepared statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Fetch all updated scores
|
||||
/// // UPDATE player SET score = score + 10 RETURNING score
|
||||
/// let request = Player.all()
|
||||
/// let statement = try request.updateAndFetchStatement(db) {
|
||||
/// $0.score += 10
|
||||
/// } select: {
|
||||
/// [$0.score]
|
||||
/// }
|
||||
/// let updatedScores = try Int.fetchAll(statement)
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments (must not be empty).
|
||||
/// - parameter select: A closure that returns the returned columns
|
||||
/// (must not be empty).
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The results of `select` and `assignments` results
|
||||
/// are not empty.
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func updateAndFetchStatement(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
|
||||
select: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) throws -> Statement
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try updateAndFetchStatement(
|
||||
db,
|
||||
onConflict: conflictResolution,
|
||||
assignments(RowDecoder.databaseComponents),
|
||||
selection: select(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns an `UPDATE RETURNING` prepared statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1140,6 +1601,49 @@ extension QueryInterfaceRequest {
|
||||
return updateStatement
|
||||
}
|
||||
|
||||
/// Returns a cursor over the records updated by an
|
||||
/// `UPDATE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Fetch all updated players
|
||||
/// // UPDATE player SET score = score + 10 RETURNING *
|
||||
/// let request = Player.all()
|
||||
/// let players = try request.updateAndFetchCursor(db) { [$0.score += 10] }
|
||||
/// while let player = try players.next() {
|
||||
/// print("Player \(player) was updated")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments.
|
||||
/// - returns: A cursor over the updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The result of `assignments` is not empty.
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func updateAndFetchCursor(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
|
||||
) throws -> RecordCursor<RowDecoder>
|
||||
where RowDecoder: FetchableRecord & TableRecord
|
||||
{
|
||||
try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns a cursor over the records updated by an
|
||||
/// `UPDATE RETURNING` statement.
|
||||
///
|
||||
@@ -1181,6 +1685,46 @@ extension QueryInterfaceRequest {
|
||||
return try RowDecoder.fetchCursor(statement)
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the array of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Fetch all updated players
|
||||
/// // UPDATE player SET score = score + 10 RETURNING *
|
||||
/// let request = Player.all()
|
||||
/// let updatedPlayers = try request.updateAndFetchAll(db) { [$0.score += 10] }
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments.
|
||||
/// - returns: An array of updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The result of `assignments` is not empty.
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func updateAndFetchAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
|
||||
) throws -> [RowDecoder]
|
||||
where RowDecoder: FetchableRecord & TableRecord
|
||||
{
|
||||
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the array of
|
||||
/// updated records.
|
||||
///
|
||||
@@ -1214,6 +1758,46 @@ extension QueryInterfaceRequest {
|
||||
try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the set of
|
||||
/// updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Fetch all updated players
|
||||
/// // UPDATE player SET score = score + 10 RETURNING *
|
||||
/// let request = Player.all()
|
||||
/// let updatedPlayers = try request.updateAndFetchSet(db) { [$0.score += 10]) }
|
||||
/// ```
|
||||
///
|
||||
/// - important: Make sure you check the documentation of the `RETURNING`
|
||||
/// clause, which describes important limitations and caveats:
|
||||
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments.
|
||||
/// - returns: A set of updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: The result of `assignments` is not empty.
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func updateAndFetchSet(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
|
||||
) throws -> Set<RowDecoder>
|
||||
where RowDecoder: FetchableRecord & TableRecord & Hashable
|
||||
{
|
||||
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Execute an `UPDATE RETURNING` statement and returns the set of
|
||||
/// updated records.
|
||||
///
|
||||
@@ -1257,10 +1841,17 @@ extension QueryInterfaceRequest {
|
||||
/// such as ``ColumnExpression/set(to:)`` or `+=`:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// let assignment = Column("score").set(to: 0)
|
||||
/// try Player.updateAll(db, assignment)
|
||||
/// try Player.updateAll(db) {
|
||||
/// $0.score.set(to: 0)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
public struct ColumnAssignment {
|
||||
@@ -1302,9 +1893,15 @@ extension ColumnExpression {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// try Player.updateAll(db, Column("score").set(to: 0))
|
||||
/// try Player.updateAll(db) { $0.set(to: 0) }
|
||||
/// }
|
||||
/// ```
|
||||
public func set(to value: (any SQLExpressible)?) -> ColumnAssignment {
|
||||
@@ -1330,9 +1927,15 @@ extension ColumnExpression {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score + 1
|
||||
/// try Player.updateAll(db, Column("score") += 1)
|
||||
/// try Player.updateAll(db) { $0.score += 1 }
|
||||
/// }
|
||||
/// ```
|
||||
public static func += (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
@@ -1351,9 +1954,15 @@ extension ColumnExpression {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score - 1
|
||||
/// try Player.updateAll(db, Column("score") -= 1)
|
||||
/// try Player.updateAll(db) { $0.score -= 1 }
|
||||
/// }
|
||||
/// ```
|
||||
public static func -= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
@@ -1372,9 +1981,15 @@ extension ColumnExpression {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score * 2
|
||||
/// try Player.updateAll(db, Column("score") *= 2)
|
||||
/// try Player.updateAll(db) { $0.score *= 2 }
|
||||
/// }
|
||||
/// ```
|
||||
public static func *= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
@@ -1393,9 +2008,15 @@ extension ColumnExpression {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score / 2
|
||||
/// try Player.updateAll(db, Column("score") /= 2)
|
||||
/// try Player.updateAll(db) { $0.score /= 2 }
|
||||
/// }
|
||||
/// ```
|
||||
public static func /= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
@@ -1414,9 +2035,15 @@ extension ColumnExpression {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let mask = Column("mask")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score & 2
|
||||
/// try Player.updateAll(db, Column("mask") &= 2)
|
||||
/// // UPDATE player SET mask = mask & 2
|
||||
/// try Player.updateAll(db) { $0.mask &= 2 }
|
||||
/// }
|
||||
/// ```
|
||||
public static func &= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
@@ -1435,9 +2062,15 @@ extension ColumnExpression {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let mask = Column("mask")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score | 2
|
||||
/// try Player.updateAll(db, Column("mask") |= 2)
|
||||
/// // UPDATE player SET mask = mask | 2
|
||||
/// try Player.updateAll(db) { $0.mask |= 2 }
|
||||
/// }
|
||||
/// ```
|
||||
public static func |= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
@@ -1456,9 +2089,15 @@ extension ColumnExpression {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let mask = Column("mask")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score << 2
|
||||
/// try Player.updateAll(db, Column("mask") <<= 2)
|
||||
/// // UPDATE player SET mask = mask << 2
|
||||
/// try Player.updateAll(db) { $0.mask <<= 2 }
|
||||
/// }
|
||||
/// ```
|
||||
public static func <<= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
@@ -1477,9 +2116,15 @@ extension ColumnExpression {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let mask = Column("mask")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score >> 2
|
||||
/// try Player.updateAll(db, Column("mask") >>= 2)
|
||||
/// // UPDATE player SET mask = mask >> 2
|
||||
/// try Player.updateAll(db) { $0.mask >>= 2 }
|
||||
/// }
|
||||
/// ```
|
||||
public static func >>= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
|
||||
@@ -22,14 +22,23 @@ public protocol TypedRequest<RowDecoder> {
|
||||
///
|
||||
/// ### The SELECT Clause
|
||||
///
|
||||
/// - ``annotated(with:)-4qcem``
|
||||
/// - ``annotated(with:)-6ehs4``
|
||||
/// - ``annotated(with:)-9wodv``
|
||||
/// - ``annotated(with:)-69r3``
|
||||
/// - ``annotatedWhenConnected(with:)``
|
||||
/// - ``select(_:)-30yzl``
|
||||
/// - ``select(_:)-7e2y5``
|
||||
/// - ``select(_:)-270ge``
|
||||
/// - ``select(_:)-4jw13``
|
||||
/// - ``select(literal:)``
|
||||
/// - ``select(sql:arguments:)``
|
||||
/// - ``selectWhenConnected(_:)``
|
||||
///
|
||||
/// ### Legacy APIs
|
||||
///
|
||||
/// It is recommended to prefer the closure-based apis defined above.
|
||||
///
|
||||
/// - ``annotated(with:)-4qcem``
|
||||
/// - ``annotated(with:)-6ehs4``
|
||||
/// - ``select(_:)-30yzl``
|
||||
/// - ``select(_:)-7e2y5``
|
||||
public protocol SelectionRequest {
|
||||
/// Defines the result columns.
|
||||
///
|
||||
@@ -209,6 +218,122 @@ extension SelectionRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecord {
|
||||
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
|
||||
|
||||
/// Defines the result column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT score FROM player
|
||||
/// let request = Player.all().select(\.score)
|
||||
/// ```
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT score FROM player
|
||||
/// let request = Player.all()
|
||||
/// .select(\.id)
|
||||
/// .select(\.score)
|
||||
/// ```
|
||||
public func select(
|
||||
_ selection: (DatabaseComponents) throws -> any SQLSelectable
|
||||
) rethrows -> Self {
|
||||
try select(selection(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Defines the result columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, score FROM player
|
||||
/// let request = Player.all().select { [$0.id, $0.score] }
|
||||
/// ```
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT score FROM player
|
||||
/// let request = Player.all()
|
||||
/// .select { [$0.id] }
|
||||
/// .select { [$0.score] }
|
||||
/// ```
|
||||
public func select(
|
||||
_ selection: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) rethrows -> Self {
|
||||
try select(selection(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Appends a result column to the selected columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let bonus = Column("bonus")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, score + bonus AS totalScore FROM player
|
||||
/// let request = Player.all().annotated {
|
||||
/// ($0.score + $0.bonus).forKey("totalScore")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter selection: A closure that accepts a database connection and
|
||||
/// returns an array of result columns.
|
||||
public func annotated(
|
||||
with selection: (DatabaseComponents) throws -> any SQLSelectable
|
||||
) rethrows -> Self {
|
||||
try annotated(with: selection(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Appends result columns to the selected columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let bonus = Column("bonus")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, score + bonus AS totalScore FROM player
|
||||
/// let request = Player.all().annotated {
|
||||
/// [($0.score + $0.bonus).forKey("totalScore")]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter selection: A closure that accepts a database connection and
|
||||
/// returns an array of result columns.
|
||||
public func annotated(
|
||||
with selection: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) rethrows -> Self {
|
||||
try annotated(with: selection(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FilteredRequest
|
||||
|
||||
/// A request that can filter database rows.
|
||||
@@ -221,11 +346,17 @@ extension SelectionRequest {
|
||||
/// ### The WHERE and JOIN ON Clauses
|
||||
///
|
||||
/// - ``all()``
|
||||
/// - ``filter(_:)``
|
||||
/// - ``filter(_:)-7j0nw``
|
||||
/// - ``filter(literal:)``
|
||||
/// - ``filter(sql:arguments:)``
|
||||
/// - ``filterWhenConnected(_:)``
|
||||
/// - ``none()``
|
||||
///
|
||||
/// ### Legacy APIs
|
||||
///
|
||||
/// It is recommended to prefer the closure-based apis defined above.
|
||||
///
|
||||
/// - ``filter(_:)-48a4t``
|
||||
public protocol FilteredRequest {
|
||||
/// Filters the fetched rows with a boolean SQL expression.
|
||||
///
|
||||
@@ -310,6 +441,34 @@ extension FilteredRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension FilteredRequest where Self: TypedRequest, Self.RowDecoder: TableRecord {
|
||||
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
|
||||
|
||||
// Accept SQLSpecificExpressible instead of SQLExpressible, so that we
|
||||
// prevent the `Player.filter { 42 }` misuse.
|
||||
// See https://github.com/groue/GRDB.swift/pull/864
|
||||
/// Filters the fetched rows with a boolean SQL expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player WHERE name = 'O''Brien'
|
||||
/// let name = "O'Brien"
|
||||
/// let request = Player.all().filter { $0.name == name }
|
||||
/// ```
|
||||
public func filter(
|
||||
_ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible
|
||||
) rethrows -> Self {
|
||||
try filter(predicate(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TableRequest
|
||||
|
||||
/// A request that feeds from a database table
|
||||
@@ -322,7 +481,7 @@ extension FilteredRequest {
|
||||
///
|
||||
/// ### Instance Methods
|
||||
///
|
||||
/// - ``aliased(_:)``
|
||||
/// - ``aliased(_:)-3k5h4``
|
||||
/// - ``TableAlias``
|
||||
///
|
||||
/// ### The WHERE Clause
|
||||
@@ -343,11 +502,23 @@ extension FilteredRequest {
|
||||
/// ### The ORDER BY Clause
|
||||
///
|
||||
/// - ``orderByPrimaryKey()``
|
||||
///
|
||||
/// ### Legacy APIs
|
||||
///
|
||||
/// It is recommended to prefer record aliases over anonymous aliases.
|
||||
///
|
||||
/// - ``aliased(_:)-772vb``
|
||||
public protocol TableRequest {
|
||||
/// The name of the database table
|
||||
var databaseTableName: String { get }
|
||||
|
||||
/// Returns a request that can be referred to with the provided alias.
|
||||
func _aliased(_ alias: TableAliasBase) -> Self
|
||||
}
|
||||
|
||||
extension TableRequest where Self: TypedRequest {
|
||||
/// Returns a request that can be referred to with the provided
|
||||
/// anonymous alias.
|
||||
///
|
||||
/// Use this method when you need to refer to this request from
|
||||
/// another request.
|
||||
@@ -402,7 +573,77 @@ public protocol TableRequest {
|
||||
/// .filter(sql: "b.publishDate >= a.deathDate")
|
||||
/// .fetchAll(db)
|
||||
/// ```
|
||||
func aliased(_ alias: TableAlias) -> Self
|
||||
public func aliased(_ alias: TableAlias<Void>) -> Self {
|
||||
self._aliased(alias)
|
||||
}
|
||||
|
||||
/// Returns a request that can be referred to with the provided
|
||||
/// record alias.
|
||||
///
|
||||
/// Use this method when you need to refer to this request from
|
||||
/// another request.
|
||||
///
|
||||
/// The first example fetches posthumous books:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// enum Columns {
|
||||
/// static let deathDate = Column("deathDate")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// enum Columns {
|
||||
/// static let publishDate = Column("publishDate")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT book.*
|
||||
/// // FROM book
|
||||
/// // JOIN author ON author.id = book.authorId
|
||||
/// // WHERE book.publishDate >= author.deathDate
|
||||
/// let authorAlias = TableAlias<Author>()
|
||||
/// let posthumousBooks = try Book
|
||||
/// .joining(required: Book.author.aliased(authorAlias))
|
||||
/// .filter { $0.publishDate >= authorAlias.deathDate }
|
||||
/// .fetchAll(db)
|
||||
/// ```
|
||||
///
|
||||
/// The second example sorts books by author name first, and then by title:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT book.*
|
||||
/// // FROM book
|
||||
/// // JOIN author ON author.id = book.authorId
|
||||
/// // ORDER BY author.name, book.title
|
||||
/// let authorAlias = TableAlias<Author>()
|
||||
/// let books = try Book
|
||||
/// .joining(required: Book.author.aliased(authorAlias))
|
||||
/// .order { [authorAlias.name, $0.title] }
|
||||
/// .fetchAll(db)
|
||||
/// ```
|
||||
///
|
||||
/// The third example uses named ``TableAlias`` so that SQL snippets can
|
||||
/// refer to SQL tables with those names:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT b.*
|
||||
/// // FROM book b
|
||||
/// // JOIN author a ON a.id = b.authorId
|
||||
/// // AND a.countryCode = 'FR'
|
||||
/// // WHERE b.publishDate >= a.deathDate
|
||||
/// let bookAlias = TableAlias<Book>(name: "b")
|
||||
/// let authorAlias = TableAlias<Author>(name: "a")
|
||||
/// let posthumousFrenchBooks = try Book.aliased(bookAlias)
|
||||
/// .joining(required: Book.author.aliased(authorAlias)
|
||||
/// .filter(sql: "a.countryCode = ?", arguments: ["FR"]))
|
||||
/// .filter(sql: "b.publishDate >= a.deathDate")
|
||||
/// .fetchAll(db)
|
||||
/// ```
|
||||
public func aliased(_ alias: TableAlias<RowDecoder>) -> Self {
|
||||
self._aliased(alias)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
@@ -585,10 +826,17 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
// ("foo", "bar") do not contain a unique key (primary key
|
||||
// or unique index).
|
||||
guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
|
||||
fatalError("""
|
||||
table \(databaseTableName) has no unique key on column(s) \
|
||||
\(key.keys.sorted().joined(separator: ", "))
|
||||
""")
|
||||
if (try? db.viewExists(databaseTableName)) == true {
|
||||
fatalError("""
|
||||
database view \(databaseTableName) has no unique key on column(s) \
|
||||
\(key.keys.sorted().joined(separator: ", "))
|
||||
""")
|
||||
} else {
|
||||
fatalError("""
|
||||
table \(databaseTableName) has no unique key on column(s) \
|
||||
\(key.keys.sorted().joined(separator: ", "))
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
let lowercaseColumns = columns.map { $0.lowercased() }
|
||||
@@ -723,18 +971,26 @@ extension TableRequest where Self: AggregatingRequest {
|
||||
///
|
||||
/// ### The GROUP BY Clause
|
||||
///
|
||||
/// - ``group(_:)-edak``
|
||||
/// - ``group(_:)-4216o``
|
||||
/// - ``group(_:)-5soxm``
|
||||
/// - ``group(_:)-32exm``
|
||||
/// - ``group(literal:)``
|
||||
/// - ``group(sql:arguments:)``
|
||||
/// - ``groupWhenConnected(_:)``
|
||||
///
|
||||
/// ### The HAVING Clause
|
||||
///
|
||||
/// - ``having(_:)``
|
||||
/// - ``having(_:)-27hlo``
|
||||
/// - ``having(literal:)``
|
||||
/// - ``having(sql:arguments:)``
|
||||
/// - ``havingWhenConnected(_:)``
|
||||
///
|
||||
/// ### Legacy APIs
|
||||
///
|
||||
/// It is recommended to prefer the closure-based apis defined above.
|
||||
///
|
||||
/// - ``group(_:)-edak``
|
||||
/// - ``group(_:)-4216o``
|
||||
/// - ``having(_:)-2ssg9``
|
||||
public protocol AggregatingRequest {
|
||||
/// Returns an aggregate request grouped on the given SQL expressions.
|
||||
///
|
||||
@@ -925,6 +1181,71 @@ extension AggregatingRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRecord {
|
||||
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
|
||||
|
||||
/// Returns an aggregate request grouped on the given SQL expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let teamId = Column("teamId")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT teamId, MAX(score)
|
||||
/// // FROM player
|
||||
/// // GROUP BY teamId
|
||||
/// let request = Player
|
||||
/// .select { [$0.teamId, max($0.score)] }
|
||||
/// .group(\.teamId)
|
||||
/// ```
|
||||
///
|
||||
/// Any previous grouping is discarded.
|
||||
public func group(
|
||||
_ expression: (DatabaseComponents) throws -> any SQLExpressible
|
||||
) rethrows -> Self {
|
||||
try group(expression(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Returns an aggregate request grouped on the given SQL expressions.
|
||||
public func group(
|
||||
_ expressions: (DatabaseComponents) throws -> [any SQLExpressible]
|
||||
) rethrows -> Self {
|
||||
try group(expressions(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Filters the aggregated groups with a boolean SQL expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let teamId = Column("teamId")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT teamId, MAX(score)
|
||||
/// // FROM player
|
||||
/// // GROUP BY teamId
|
||||
/// // HAVING MAX(score) > 1000
|
||||
/// let request = Player
|
||||
/// .select { [$0.teamId, max($0.score)] }
|
||||
/// .group(\.teamId)
|
||||
/// .having { max($0.score) > 1000 }
|
||||
/// ```
|
||||
public func having(
|
||||
_ predicate: (DatabaseComponents) throws -> any SQLExpressible
|
||||
) rethrows -> Self {
|
||||
try having(predicate(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - OrderedRequest
|
||||
|
||||
/// A request that can sort database rows.
|
||||
@@ -933,14 +1254,21 @@ extension AggregatingRequest {
|
||||
///
|
||||
/// ### The ORDER BY Clause
|
||||
///
|
||||
/// - ``order(_:)-63rzl``
|
||||
/// - ``order(_:)-6co0m``
|
||||
/// - ``order(_:)-5q7wj``
|
||||
/// - ``order(_:)-711zj``
|
||||
/// - ``order(literal:)``
|
||||
/// - ``order(sql:arguments:)``
|
||||
/// - ``orderWhenConnected(_:)``
|
||||
/// - ``reversed()``
|
||||
/// - ``unordered()``
|
||||
/// - ``withStableOrder()``
|
||||
///
|
||||
/// ### Legacy APIs
|
||||
///
|
||||
/// It is recommended to prefer the closure-based apis defined above.
|
||||
///
|
||||
/// - ``order(_:)-63rzl``
|
||||
/// - ``order(_:)-6co0m``
|
||||
public protocol OrderedRequest {
|
||||
/// Sorts the fetched rows according to the given SQL ordering terms.
|
||||
///
|
||||
@@ -978,9 +1306,15 @@ public protocol OrderedRequest {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name DESC
|
||||
/// let request = Player.all()
|
||||
/// .order(Column("name"))
|
||||
/// .order(\.name)
|
||||
/// .reversed()
|
||||
/// ```
|
||||
///
|
||||
@@ -994,12 +1328,16 @@ public protocol OrderedRequest {
|
||||
|
||||
/// Returns a request without any ordering.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// let request = Player.all()
|
||||
/// .order(Column("name"))
|
||||
/// .order(\.name)
|
||||
/// .unordered()
|
||||
/// ```
|
||||
func unordered() -> Self
|
||||
@@ -1092,6 +1430,74 @@ extension OrderedRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension OrderedRequest where Self: TypedRequest, Self.RowDecoder: TableRecord {
|
||||
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
|
||||
|
||||
/// Sorts the fetched rows according to the given SQL ordering term.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// let request = Player.all().order(\.name)
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY score DESC
|
||||
/// let request = Player.all().order(\.score.desc)
|
||||
/// ```
|
||||
///
|
||||
/// Any previous ordering is discarded:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// let request = Player.all()
|
||||
/// .order(\.score.desc)
|
||||
/// .order(\.name)
|
||||
/// ```
|
||||
public func order(
|
||||
_ ordering: (DatabaseComponents) throws -> any SQLOrderingTerm
|
||||
) rethrows -> Self {
|
||||
try order(ordering(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
|
||||
/// Sorts the fetched rows according to the given SQL ordering terms.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY score DESC, name
|
||||
/// let request = Player.all()
|
||||
/// .order { [$0.score.desc, $0.name] }
|
||||
/// ```
|
||||
///
|
||||
/// Any previous ordering is discarded:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// let request = Player.all()
|
||||
/// .order { [$0.score.desc] }
|
||||
/// .order { [$0.name] }
|
||||
/// ```
|
||||
public func order(
|
||||
_ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm]
|
||||
) rethrows -> Self {
|
||||
try order(orderings(Self.RowDecoder.databaseComponents))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JoinableRequest
|
||||
|
||||
/// A request that can join and prefetch associations.
|
||||
@@ -1234,12 +1640,17 @@ extension JoinableRequest {
|
||||
/// For example, we can fetch only books whose author is French:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord, Decodable { }
|
||||
/// struct Book: TableRecord, FetchableRecord, Decodable {
|
||||
/// struct Author: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let countryCode = Column("countryCode")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// let frenchAuthors = Book.author.filter(Column("countryCode") == "FR")
|
||||
/// let frenchAuthors = Book.author.filter { $0.countryCode == "FR" }
|
||||
/// let bookInfos = try Book.all()
|
||||
/// .joining(required: frenchAuthors)
|
||||
/// .fetchAll(db)
|
||||
@@ -1256,9 +1667,19 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Team: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let countryCode = Column("countryCode")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Player: Decodable, TableRecord, FetchableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.color
|
||||
/// // FROM player LEFT JOIN team ...
|
||||
/// let teamColor = Player.team.select(Column("color"))
|
||||
/// let teamColor = Player.team.select(\.color)
|
||||
/// let request = Player.all().annotated(withOptional: teamColor)
|
||||
/// ```
|
||||
///
|
||||
@@ -1284,9 +1705,9 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// ``JoinableRequest/joining(optional:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let teamAlias = TableAlias()
|
||||
/// let teamAlias = TableAlias<Team>()
|
||||
/// let request = Player.all()
|
||||
/// .annotated(with: teamAlias[Column("color")])
|
||||
/// .annotated(with: teamAlias.color)
|
||||
/// .joining(optional: Player.team.aliased(teamAlias))
|
||||
/// ```
|
||||
public func annotated<A: Association>(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
@@ -1308,9 +1729,19 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Team: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let color = Column("color")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.color
|
||||
/// // FROM player JOIN team ...
|
||||
/// let teamColor = Player.team.select(Column("color"))
|
||||
/// let teamColor = Player.team.select(\.color)
|
||||
/// let request = Player.all().annotated(withRequired: teamColor)
|
||||
/// ```
|
||||
///
|
||||
@@ -1336,9 +1767,9 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// ``JoinableRequest/joining(required:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let teamAlias = TableAlias()
|
||||
/// let teamAlias = TableAlias<Team>()
|
||||
/// let request = Player.all()
|
||||
/// .annotated(with: teamAlias[Column("color")])
|
||||
/// .annotated(with: teamAlias.color])
|
||||
/// .joining(required: Player.team.aliased(teamAlias))
|
||||
/// ```
|
||||
public func annotated<A: Association>(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
@@ -1367,7 +1798,7 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
///
|
||||
/// ### Instance Methods
|
||||
///
|
||||
/// - ``TableRequest/aliased(_:)``
|
||||
/// - ``TableRequest/aliased(_:)-3k5h4``
|
||||
/// - ``TableAlias``
|
||||
///
|
||||
/// ### The WITH Clause
|
||||
@@ -1376,12 +1807,12 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
///
|
||||
/// ### The SELECT Clause
|
||||
///
|
||||
/// - ``SelectionRequest/annotated(with:)-4qcem``
|
||||
/// - ``SelectionRequest/annotated(with:)-6ehs4``
|
||||
/// - ``SelectionRequest/annotated(with:)-9wodv``
|
||||
/// - ``SelectionRequest/annotated(with:)-69r3``
|
||||
/// - ``SelectionRequest/annotatedWhenConnected(with:)``
|
||||
/// - ``distinct()``
|
||||
/// - ``SelectionRequest/select(_:)-30yzl``
|
||||
/// - ``SelectionRequest/select(_:)-7e2y5``
|
||||
/// - ``SelectionRequest/select(_:)-270ge``
|
||||
/// - ``SelectionRequest/select(_:)-4jw13``
|
||||
/// - ``SelectionRequest/select(literal:)``
|
||||
/// - ``SelectionRequest/select(sql:arguments:)``
|
||||
/// - ``SelectionRequest/selectWhenConnected(_:)``
|
||||
@@ -1389,7 +1820,7 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// ### The WHERE Clause
|
||||
///
|
||||
/// - ``FilteredRequest/all()``
|
||||
/// - ``FilteredRequest/filter(_:)``
|
||||
/// - ``FilteredRequest/filter(_:)-7j0nw``
|
||||
/// - ``TableRequest/filter(id:)``
|
||||
/// - ``TableRequest/filter(ids:)``
|
||||
/// - ``TableRequest/filter(key:)-1p9sq``
|
||||
@@ -1405,21 +1836,21 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
///
|
||||
/// ### The GROUP BY and HAVING Clauses
|
||||
///
|
||||
/// - ``AggregatingRequest/group(_:)-edak``
|
||||
/// - ``AggregatingRequest/group(_:)-4216o``
|
||||
/// - ``AggregatingRequest/group(_:)-5soxm``
|
||||
/// - ``AggregatingRequest/group(_:)-32exm``
|
||||
/// - ``AggregatingRequest/group(literal:)``
|
||||
/// - ``AggregatingRequest/group(sql:arguments:)``
|
||||
/// - ``TableRequest/groupByPrimaryKey()``
|
||||
/// - ``AggregatingRequest/groupWhenConnected(_:)``
|
||||
/// - ``AggregatingRequest/having(_:)``
|
||||
/// - ``AggregatingRequest/having(_:)-27hlo``
|
||||
/// - ``AggregatingRequest/having(literal:)``
|
||||
/// - ``AggregatingRequest/having(sql:arguments:)``
|
||||
/// - ``AggregatingRequest/havingWhenConnected(_:)``
|
||||
///
|
||||
/// ### The ORDER BY Clause
|
||||
///
|
||||
/// - ``OrderedRequest/order(_:)-63rzl``
|
||||
/// - ``OrderedRequest/order(_:)-6co0m``
|
||||
/// - ``OrderedRequest/order(_:)-5q7wj``
|
||||
/// - ``OrderedRequest/order(_:)-711zj``
|
||||
/// - ``OrderedRequest/order(literal:)``
|
||||
/// - ``OrderedRequest/order(sql:arguments:)``
|
||||
/// - ``OrderedRequest/orderWhenConnected(_:)``
|
||||
@@ -1450,6 +1881,23 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// - ``SelectionRequest``
|
||||
/// - ``TableRequest``
|
||||
/// - ``TypedRequest``
|
||||
///
|
||||
/// ### Legacy APIs
|
||||
///
|
||||
/// It is recommended to prefer the closure-based apis defined above, as
|
||||
/// well as record aliases over anonymous aliases.
|
||||
///
|
||||
/// - ``TableRequest/aliased(_:)-772vb``
|
||||
/// - ``SelectionRequest/annotated(with:)-4qcem``
|
||||
/// - ``SelectionRequest/annotated(with:)-6ehs4``
|
||||
/// - ``FilteredRequest/filter(_:)-48a4t``
|
||||
/// - ``AggregatingRequest/group(_:)-edak``
|
||||
/// - ``AggregatingRequest/group(_:)-4216o``
|
||||
/// - ``AggregatingRequest/having(_:)-2ssg9``
|
||||
/// - ``OrderedRequest/order(_:)-63rzl``
|
||||
/// - ``OrderedRequest/order(_:)-6co0m``
|
||||
/// - ``SelectionRequest/select(_:)-30yzl``
|
||||
/// - ``SelectionRequest/select(_:)-7e2y5``
|
||||
public protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
|
||||
JoinableRequest, OrderedRequest,
|
||||
SelectionRequest, TableRequest
|
||||
@@ -1459,11 +1907,17 @@ public protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredReques
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT DISTINCT * FROM player
|
||||
/// let request = Player.all().distinct()
|
||||
///
|
||||
/// // SELECT DISTINCT name FROM player
|
||||
/// let request = Player.select(Column("name")).distinct()
|
||||
/// let request = Player.select(\.name).distinct()
|
||||
/// ```
|
||||
func distinct() -> Self
|
||||
|
||||
@@ -1476,18 +1930,31 @@ public protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredReques
|
||||
/// latest message:
|
||||
///
|
||||
/// ```swift
|
||||
/// let latestMessageRequest = Message
|
||||
/// .annotated(with: max(Column("date")))
|
||||
/// .group(Column("chatID"))
|
||||
/// struct Chat: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let latestMessageCTE = CommonTableExpression(
|
||||
/// struct Message: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let date = Column("date")
|
||||
/// static let chatId = Column("chatId")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let latestMessageRequest = Message
|
||||
/// .annotated { max($0.date) }
|
||||
/// .group(\.chatId)
|
||||
///
|
||||
/// let latestMessageCTE = CommonTableExpression<Message>(
|
||||
/// named: "latestMessage",
|
||||
/// request: latestMessageRequest)
|
||||
///
|
||||
/// let latestMessageAssociation = Chat.association(
|
||||
/// to: latestMessageCTE,
|
||||
/// on: { chat, latestMessage in
|
||||
/// chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
/// chat.id == latestMessage.chatId
|
||||
/// })
|
||||
///
|
||||
/// // WITH latestMessage AS
|
||||
|
||||
Loaded 100 of 228 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user